babylon.2.0-beta.debug.js 1.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. };
  29. Color3.prototype.toColor4 = function (alpha) {
  30. if (alpha === void 0) { alpha = 1; }
  31. return new Color4(this.r, this.g, this.b, alpha);
  32. };
  33. Color3.prototype.asArray = function () {
  34. var result = [];
  35. this.toArray(result, 0);
  36. return result;
  37. };
  38. Color3.prototype.toLuminance = function () {
  39. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  40. };
  41. Color3.prototype.multiply = function (otherColor) {
  42. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  43. };
  44. Color3.prototype.multiplyToRef = function (otherColor, result) {
  45. result.r = this.r * otherColor.r;
  46. result.g = this.g * otherColor.g;
  47. result.b = this.b * otherColor.b;
  48. };
  49. Color3.prototype.equals = function (otherColor) {
  50. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  51. };
  52. Color3.prototype.scale = function (scale) {
  53. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  54. };
  55. Color3.prototype.scaleToRef = function (scale, result) {
  56. result.r = this.r * scale;
  57. result.g = this.g * scale;
  58. result.b = this.b * scale;
  59. };
  60. Color3.prototype.add = function (otherColor) {
  61. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  62. };
  63. Color3.prototype.addToRef = function (otherColor, result) {
  64. result.r = this.r + otherColor.r;
  65. result.g = this.g + otherColor.g;
  66. result.b = this.b + otherColor.b;
  67. };
  68. Color3.prototype.subtract = function (otherColor) {
  69. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  70. };
  71. Color3.prototype.subtractToRef = function (otherColor, result) {
  72. result.r = this.r - otherColor.r;
  73. result.g = this.g - otherColor.g;
  74. result.b = this.b - otherColor.b;
  75. };
  76. Color3.prototype.clone = function () {
  77. return new Color3(this.r, this.g, this.b);
  78. };
  79. Color3.prototype.copyFrom = function (source) {
  80. this.r = source.r;
  81. this.g = source.g;
  82. this.b = source.b;
  83. };
  84. Color3.prototype.copyFromFloats = function (r, g, b) {
  85. this.r = r;
  86. this.g = g;
  87. this.b = b;
  88. };
  89. // Statics
  90. Color3.FromArray = function (array, offset) {
  91. if (offset === void 0) { offset = 0; }
  92. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  93. };
  94. Color3.FromInts = function (r, g, b) {
  95. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  96. };
  97. Color3.Lerp = function (start, end, amount) {
  98. var r = start.r + ((end.r - start.r) * amount);
  99. var g = start.g + ((end.g - start.g) * amount);
  100. var b = start.b + ((end.b - start.b) * amount);
  101. return new Color3(r, g, b);
  102. };
  103. Color3.Red = function () {
  104. return new Color3(1, 0, 0);
  105. };
  106. Color3.Green = function () {
  107. return new Color3(0, 1, 0);
  108. };
  109. Color3.Blue = function () {
  110. return new Color3(0, 0, 1);
  111. };
  112. Color3.Black = function () {
  113. return new Color3(0, 0, 0);
  114. };
  115. Color3.White = function () {
  116. return new Color3(1, 1, 1);
  117. };
  118. Color3.Purple = function () {
  119. return new Color3(0.5, 0, 0.5);
  120. };
  121. Color3.Magenta = function () {
  122. return new Color3(1, 0, 1);
  123. };
  124. Color3.Yellow = function () {
  125. return new Color3(1, 1, 0);
  126. };
  127. Color3.Gray = function () {
  128. return new Color3(0.5, 0.5, 0.5);
  129. };
  130. return Color3;
  131. })();
  132. BABYLON.Color3 = Color3;
  133. var Color4 = (function () {
  134. function Color4(r, g, b, a) {
  135. this.r = r;
  136. this.g = g;
  137. this.b = b;
  138. this.a = a;
  139. }
  140. // Operators
  141. Color4.prototype.addInPlace = function (right) {
  142. this.r += right.r;
  143. this.g += right.g;
  144. this.b += right.b;
  145. this.a += right.a;
  146. };
  147. Color4.prototype.asArray = function () {
  148. var result = [];
  149. this.toArray(result, 0);
  150. return result;
  151. };
  152. Color4.prototype.toArray = function (array, index) {
  153. if (index === undefined) {
  154. index = 0;
  155. }
  156. array[index] = this.r;
  157. array[index + 1] = this.g;
  158. array[index + 2] = this.b;
  159. array[index + 3] = this.a;
  160. };
  161. Color4.prototype.add = function (right) {
  162. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  163. };
  164. Color4.prototype.subtract = function (right) {
  165. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  166. };
  167. Color4.prototype.subtractToRef = function (right, result) {
  168. result.r = this.r - right.r;
  169. result.g = this.g - right.g;
  170. result.b = this.b - right.b;
  171. result.a = this.a - right.a;
  172. };
  173. Color4.prototype.scale = function (scale) {
  174. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  175. };
  176. Color4.prototype.scaleToRef = function (scale, result) {
  177. result.r = this.r * scale;
  178. result.g = this.g * scale;
  179. result.b = this.b * scale;
  180. result.a = this.a * scale;
  181. };
  182. Color4.prototype.toString = function () {
  183. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  184. };
  185. Color4.prototype.clone = function () {
  186. return new Color4(this.r, this.g, this.b, this.a);
  187. };
  188. Color4.prototype.copyFrom = function (source) {
  189. this.r = source.r;
  190. this.g = source.g;
  191. this.b = source.b;
  192. this.a = source.a;
  193. };
  194. // Statics
  195. Color4.Lerp = function (left, right, amount) {
  196. var result = new Color4(0, 0, 0, 0);
  197. Color4.LerpToRef(left, right, amount, result);
  198. return result;
  199. };
  200. Color4.LerpToRef = function (left, right, amount, result) {
  201. result.r = left.r + (right.r - left.r) * amount;
  202. result.g = left.g + (right.g - left.g) * amount;
  203. result.b = left.b + (right.b - left.b) * amount;
  204. result.a = left.a + (right.a - left.a) * amount;
  205. };
  206. Color4.FromArray = function (array, offset) {
  207. if (offset === void 0) { offset = 0; }
  208. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  209. };
  210. Color4.FromInts = function (r, g, b, a) {
  211. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  212. };
  213. return Color4;
  214. })();
  215. BABYLON.Color4 = Color4;
  216. var Vector2 = (function () {
  217. function Vector2(x, y) {
  218. this.x = x;
  219. this.y = y;
  220. }
  221. Vector2.prototype.toString = function () {
  222. return "{X: " + this.x + " Y:" + this.y + "}";
  223. };
  224. // Operators
  225. Vector2.prototype.toArray = function (array, index) {
  226. if (index === undefined) {
  227. index = 0;
  228. }
  229. array[index] = this.x;
  230. array[index + 1] = this.y;
  231. };
  232. Vector2.prototype.asArray = function () {
  233. var result = [];
  234. this.toArray(result, 0);
  235. return result;
  236. };
  237. Vector2.prototype.copyFrom = function (source) {
  238. this.x = source.x;
  239. this.y = source.y;
  240. };
  241. Vector2.prototype.copyFromFloats = function (x, y) {
  242. this.x = x;
  243. this.y = y;
  244. };
  245. Vector2.prototype.add = function (otherVector) {
  246. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  247. };
  248. Vector2.prototype.addVector3 = function (otherVector) {
  249. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  250. };
  251. Vector2.prototype.subtract = function (otherVector) {
  252. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  253. };
  254. Vector2.prototype.subtractInPlace = function (otherVector) {
  255. this.x -= otherVector.x;
  256. this.y -= otherVector.y;
  257. };
  258. Vector2.prototype.multiplyInPlace = function (otherVector) {
  259. this.x *= otherVector.x;
  260. this.y *= otherVector.y;
  261. };
  262. Vector2.prototype.multiply = function (otherVector) {
  263. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  264. };
  265. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  266. result.x = this.x * otherVector.x;
  267. result.y = this.y * otherVector.y;
  268. };
  269. Vector2.prototype.multiplyByFloats = function (x, y) {
  270. return new Vector2(this.x * x, this.y * y);
  271. };
  272. Vector2.prototype.divide = function (otherVector) {
  273. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  274. };
  275. Vector2.prototype.divideToRef = function (otherVector, result) {
  276. result.x = this.x / otherVector.x;
  277. result.y = this.y / otherVector.y;
  278. };
  279. Vector2.prototype.negate = function () {
  280. return new Vector2(-this.x, -this.y);
  281. };
  282. Vector2.prototype.scaleInPlace = function (scale) {
  283. this.x *= scale;
  284. this.y *= scale;
  285. return this;
  286. };
  287. Vector2.prototype.scale = function (scale) {
  288. return new Vector2(this.x * scale, this.y * scale);
  289. };
  290. Vector2.prototype.equals = function (otherVector) {
  291. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  292. };
  293. // Properties
  294. Vector2.prototype.length = function () {
  295. return Math.sqrt(this.x * this.x + this.y * this.y);
  296. };
  297. Vector2.prototype.lengthSquared = function () {
  298. return (this.x * this.x + this.y * this.y);
  299. };
  300. // Methods
  301. Vector2.prototype.normalize = function () {
  302. var len = this.length();
  303. if (len === 0)
  304. return this;
  305. var num = 1.0 / len;
  306. this.x *= num;
  307. this.y *= num;
  308. return this;
  309. };
  310. Vector2.prototype.clone = function () {
  311. return new Vector2(this.x, this.y);
  312. };
  313. // Statics
  314. Vector2.Zero = function () {
  315. return new Vector2(0, 0);
  316. };
  317. Vector2.FromArray = function (array, offset) {
  318. if (offset === void 0) { offset = 0; }
  319. return new Vector2(array[offset], array[offset + 1]);
  320. };
  321. Vector2.FromArrayToRef = function (array, offset, result) {
  322. result.x = array[offset];
  323. result.y = array[offset + 1];
  324. };
  325. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  326. var squared = amount * amount;
  327. var cubed = amount * squared;
  328. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  329. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  330. return new Vector2(x, y);
  331. };
  332. Vector2.Clamp = function (value, min, max) {
  333. var x = value.x;
  334. x = (x > max.x) ? max.x : x;
  335. x = (x < min.x) ? min.x : x;
  336. var y = value.y;
  337. y = (y > max.y) ? max.y : y;
  338. y = (y < min.y) ? min.y : y;
  339. return new Vector2(x, y);
  340. };
  341. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  342. var squared = amount * amount;
  343. var cubed = amount * squared;
  344. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  345. var part2 = (-2.0 * cubed) + (3.0 * squared);
  346. var part3 = (cubed - (2.0 * squared)) + amount;
  347. var part4 = cubed - squared;
  348. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  349. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  350. return new Vector2(x, y);
  351. };
  352. Vector2.Lerp = function (start, end, amount) {
  353. var x = start.x + ((end.x - start.x) * amount);
  354. var y = start.y + ((end.y - start.y) * amount);
  355. return new Vector2(x, y);
  356. };
  357. Vector2.Dot = function (left, right) {
  358. return left.x * right.x + left.y * right.y;
  359. };
  360. Vector2.Normalize = function (vector) {
  361. var newVector = vector.clone();
  362. newVector.normalize();
  363. return newVector;
  364. };
  365. Vector2.Minimize = function (left, right) {
  366. var x = (left.x < right.x) ? left.x : right.x;
  367. var y = (left.y < right.y) ? left.y : right.y;
  368. return new Vector2(x, y);
  369. };
  370. Vector2.Maximize = function (left, right) {
  371. var x = (left.x > right.x) ? left.x : right.x;
  372. var y = (left.y > right.y) ? left.y : right.y;
  373. return new Vector2(x, y);
  374. };
  375. Vector2.Transform = function (vector, transformation) {
  376. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  377. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  378. return new Vector2(x, y);
  379. };
  380. Vector2.Distance = function (value1, value2) {
  381. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  382. };
  383. Vector2.DistanceSquared = function (value1, value2) {
  384. var x = value1.x - value2.x;
  385. var y = value1.y - value2.y;
  386. return (x * x) + (y * y);
  387. };
  388. return Vector2;
  389. })();
  390. BABYLON.Vector2 = Vector2;
  391. var Vector3 = (function () {
  392. function Vector3(x, y, z) {
  393. this.x = x;
  394. this.y = y;
  395. this.z = z;
  396. }
  397. Vector3.prototype.toString = function () {
  398. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  399. };
  400. // Operators
  401. Vector3.prototype.asArray = function () {
  402. var result = [];
  403. this.toArray(result, 0);
  404. return result;
  405. };
  406. Vector3.prototype.toArray = function (array, index) {
  407. if (index === undefined) {
  408. index = 0;
  409. }
  410. array[index] = this.x;
  411. array[index + 1] = this.y;
  412. array[index + 2] = this.z;
  413. };
  414. Vector3.prototype.addInPlace = function (otherVector) {
  415. this.x += otherVector.x;
  416. this.y += otherVector.y;
  417. this.z += otherVector.z;
  418. };
  419. Vector3.prototype.add = function (otherVector) {
  420. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  421. };
  422. Vector3.prototype.addToRef = function (otherVector, result) {
  423. result.x = this.x + otherVector.x;
  424. result.y = this.y + otherVector.y;
  425. result.z = this.z + otherVector.z;
  426. };
  427. Vector3.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. this.z -= otherVector.z;
  431. };
  432. Vector3.prototype.subtract = function (otherVector) {
  433. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  434. };
  435. Vector3.prototype.subtractToRef = function (otherVector, result) {
  436. result.x = this.x - otherVector.x;
  437. result.y = this.y - otherVector.y;
  438. result.z = this.z - otherVector.z;
  439. };
  440. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  441. return new Vector3(this.x - x, this.y - y, this.z - z);
  442. };
  443. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  444. result.x = this.x - x;
  445. result.y = this.y - y;
  446. result.z = this.z - z;
  447. };
  448. Vector3.prototype.negate = function () {
  449. return new Vector3(-this.x, -this.y, -this.z);
  450. };
  451. Vector3.prototype.scaleInPlace = function (scale) {
  452. this.x *= scale;
  453. this.y *= scale;
  454. this.z *= scale;
  455. return this;
  456. };
  457. Vector3.prototype.scale = function (scale) {
  458. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  459. };
  460. Vector3.prototype.scaleToRef = function (scale, result) {
  461. result.x = this.x * scale;
  462. result.y = this.y * scale;
  463. result.z = this.z * scale;
  464. };
  465. Vector3.prototype.equals = function (otherVector) {
  466. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  467. };
  468. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  469. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  470. };
  471. Vector3.prototype.equalsToFloats = function (x, y, z) {
  472. return this.x === x && this.y === y && this.z === z;
  473. };
  474. Vector3.prototype.multiplyInPlace = function (otherVector) {
  475. this.x *= otherVector.x;
  476. this.y *= otherVector.y;
  477. this.z *= otherVector.z;
  478. };
  479. Vector3.prototype.multiply = function (otherVector) {
  480. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  481. };
  482. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  483. result.x = this.x * otherVector.x;
  484. result.y = this.y * otherVector.y;
  485. result.z = this.z * otherVector.z;
  486. };
  487. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  488. return new Vector3(this.x * x, this.y * y, this.z * z);
  489. };
  490. Vector3.prototype.divide = function (otherVector) {
  491. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  492. };
  493. Vector3.prototype.divideToRef = function (otherVector, result) {
  494. result.x = this.x / otherVector.x;
  495. result.y = this.y / otherVector.y;
  496. result.z = this.z / otherVector.z;
  497. };
  498. Vector3.prototype.MinimizeInPlace = function (other) {
  499. if (other.x < this.x)
  500. this.x = other.x;
  501. if (other.y < this.y)
  502. this.y = other.y;
  503. if (other.z < this.z)
  504. this.z = other.z;
  505. };
  506. Vector3.prototype.MaximizeInPlace = function (other) {
  507. if (other.x > this.x)
  508. this.x = other.x;
  509. if (other.y > this.y)
  510. this.y = other.y;
  511. if (other.z > this.z)
  512. this.z = other.z;
  513. };
  514. // Properties
  515. Vector3.prototype.length = function () {
  516. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  517. };
  518. Vector3.prototype.lengthSquared = function () {
  519. return (this.x * this.x + this.y * this.y + this.z * this.z);
  520. };
  521. // Methods
  522. Vector3.prototype.normalize = function () {
  523. var len = this.length();
  524. if (len === 0)
  525. return this;
  526. var num = 1.0 / len;
  527. this.x *= num;
  528. this.y *= num;
  529. this.z *= num;
  530. return this;
  531. };
  532. Vector3.prototype.clone = function () {
  533. return new Vector3(this.x, this.y, this.z);
  534. };
  535. Vector3.prototype.copyFrom = function (source) {
  536. this.x = source.x;
  537. this.y = source.y;
  538. this.z = source.z;
  539. };
  540. Vector3.prototype.copyFromFloats = function (x, y, z) {
  541. this.x = x;
  542. this.y = y;
  543. this.z = z;
  544. };
  545. // Statics
  546. Vector3.FromArray = function (array, offset) {
  547. if (!offset) {
  548. offset = 0;
  549. }
  550. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  551. };
  552. Vector3.FromArrayToRef = function (array, offset, result) {
  553. result.x = array[offset];
  554. result.y = array[offset + 1];
  555. result.z = array[offset + 2];
  556. };
  557. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  558. result.x = array[offset];
  559. result.y = array[offset + 1];
  560. result.z = array[offset + 2];
  561. };
  562. Vector3.FromFloatsToRef = function (x, y, z, result) {
  563. result.x = x;
  564. result.y = y;
  565. result.z = z;
  566. };
  567. Vector3.Zero = function () {
  568. return new Vector3(0, 0, 0);
  569. };
  570. Vector3.Up = function () {
  571. return new Vector3(0, 1.0, 0);
  572. };
  573. Vector3.TransformCoordinates = function (vector, transformation) {
  574. var result = Vector3.Zero();
  575. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  576. return result;
  577. };
  578. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  579. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  580. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  581. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  582. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  583. result.x = x / w;
  584. result.y = y / w;
  585. result.z = z / w;
  586. };
  587. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  588. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  589. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  590. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  591. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  592. result.x = rx / rw;
  593. result.y = ry / rw;
  594. result.z = rz / rw;
  595. };
  596. Vector3.TransformNormal = function (vector, transformation) {
  597. var result = Vector3.Zero();
  598. Vector3.TransformNormalToRef(vector, transformation, result);
  599. return result;
  600. };
  601. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  602. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  603. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  604. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  605. };
  606. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  607. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  608. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  609. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  610. };
  611. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  612. var squared = amount * amount;
  613. var cubed = amount * squared;
  614. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  615. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  616. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  617. return new Vector3(x, y, z);
  618. };
  619. Vector3.Clamp = function (value, min, max) {
  620. var x = value.x;
  621. x = (x > max.x) ? max.x : x;
  622. x = (x < min.x) ? min.x : x;
  623. var y = value.y;
  624. y = (y > max.y) ? max.y : y;
  625. y = (y < min.y) ? min.y : y;
  626. var z = value.z;
  627. z = (z > max.z) ? max.z : z;
  628. z = (z < min.z) ? min.z : z;
  629. return new Vector3(x, y, z);
  630. };
  631. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  632. var squared = amount * amount;
  633. var cubed = amount * squared;
  634. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  635. var part2 = (-2.0 * cubed) + (3.0 * squared);
  636. var part3 = (cubed - (2.0 * squared)) + amount;
  637. var part4 = cubed - squared;
  638. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  639. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  640. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  641. return new Vector3(x, y, z);
  642. };
  643. Vector3.Lerp = function (start, end, amount) {
  644. var x = start.x + ((end.x - start.x) * amount);
  645. var y = start.y + ((end.y - start.y) * amount);
  646. var z = start.z + ((end.z - start.z) * amount);
  647. return new Vector3(x, y, z);
  648. };
  649. Vector3.Dot = function (left, right) {
  650. return (left.x * right.x + left.y * right.y + left.z * right.z);
  651. };
  652. Vector3.Cross = function (left, right) {
  653. var result = Vector3.Zero();
  654. Vector3.CrossToRef(left, right, result);
  655. return result;
  656. };
  657. Vector3.CrossToRef = function (left, right, result) {
  658. result.x = left.y * right.z - left.z * right.y;
  659. result.y = left.z * right.x - left.x * right.z;
  660. result.z = left.x * right.y - left.y * right.x;
  661. };
  662. Vector3.Normalize = function (vector) {
  663. var result = Vector3.Zero();
  664. Vector3.NormalizeToRef(vector, result);
  665. return result;
  666. };
  667. Vector3.NormalizeToRef = function (vector, result) {
  668. result.copyFrom(vector);
  669. result.normalize();
  670. };
  671. Vector3.Project = function (vector, world, transform, viewport) {
  672. var cw = viewport.width;
  673. var ch = viewport.height;
  674. var cx = viewport.x;
  675. var cy = viewport.y;
  676. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  677. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  678. return Vector3.TransformCoordinates(vector, finalMatrix);
  679. };
  680. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  681. var matrix = world.multiply(transform);
  682. matrix.invert();
  683. source.x = source.x / viewportWidth * 2 - 1;
  684. source.y = -(source.y / viewportHeight * 2 - 1);
  685. var vector = Vector3.TransformCoordinates(source, matrix);
  686. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  687. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  688. vector = vector.scale(1.0 / num);
  689. }
  690. return vector;
  691. };
  692. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  693. var matrix = world.multiply(view).multiply(projection);
  694. matrix.invert();
  695. source.x = source.x / viewportWidth * 2 - 1;
  696. source.y = -(source.y / viewportHeight * 2 - 1);
  697. var vector = Vector3.TransformCoordinates(source, matrix);
  698. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  699. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  700. vector = vector.scale(1.0 / num);
  701. }
  702. return vector;
  703. };
  704. Vector3.Minimize = function (left, right) {
  705. var min = left.clone();
  706. min.MinimizeInPlace(right);
  707. return min;
  708. };
  709. Vector3.Maximize = function (left, right) {
  710. var max = left.clone();
  711. max.MaximizeInPlace(right);
  712. return max;
  713. };
  714. Vector3.Distance = function (value1, value2) {
  715. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  716. };
  717. Vector3.DistanceSquared = function (value1, value2) {
  718. var x = value1.x - value2.x;
  719. var y = value1.y - value2.y;
  720. var z = value1.z - value2.z;
  721. return (x * x) + (y * y) + (z * z);
  722. };
  723. Vector3.Center = function (value1, value2) {
  724. var center = value1.add(value2);
  725. center.scaleInPlace(0.5);
  726. return center;
  727. };
  728. return Vector3;
  729. })();
  730. BABYLON.Vector3 = Vector3;
  731. //Vector4 class created for EulerAngle class conversion to Quaternion
  732. var Vector4 = (function () {
  733. function Vector4(x, y, z, w) {
  734. this.x = x;
  735. this.y = y;
  736. this.z = z;
  737. this.w = w;
  738. }
  739. Vector4.prototype.toString = function () {
  740. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  741. };
  742. // Operators
  743. Vector4.prototype.asArray = function () {
  744. var result = [];
  745. this.toArray(result, 0);
  746. return result;
  747. };
  748. Vector4.prototype.toArray = function (array, index) {
  749. if (index === undefined) {
  750. index = 0;
  751. }
  752. array[index] = this.x;
  753. array[index + 1] = this.y;
  754. array[index + 2] = this.z;
  755. array[index + 3] = this.w;
  756. };
  757. Vector4.prototype.addInPlace = function (otherVector) {
  758. this.x += otherVector.x;
  759. this.y += otherVector.y;
  760. this.z += otherVector.z;
  761. this.w += otherVector.w;
  762. };
  763. Vector4.prototype.add = function (otherVector) {
  764. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  765. };
  766. Vector4.prototype.addToRef = function (otherVector, result) {
  767. result.x = this.x + otherVector.x;
  768. result.y = this.y + otherVector.y;
  769. result.z = this.z + otherVector.z;
  770. result.w = this.w + otherVector.w;
  771. };
  772. Vector4.prototype.subtractInPlace = function (otherVector) {
  773. this.x -= otherVector.x;
  774. this.y -= otherVector.y;
  775. this.z -= otherVector.z;
  776. this.w -= otherVector.w;
  777. };
  778. Vector4.prototype.subtract = function (otherVector) {
  779. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  780. };
  781. Vector4.prototype.subtractToRef = function (otherVector, result) {
  782. result.x = this.x - otherVector.x;
  783. result.y = this.y - otherVector.y;
  784. result.z = this.z - otherVector.z;
  785. result.w = this.w - otherVector.w;
  786. };
  787. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  788. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  789. };
  790. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  791. result.x = this.x - x;
  792. result.y = this.y - y;
  793. result.z = this.z - z;
  794. result.w = this.w - w;
  795. };
  796. Vector4.prototype.negate = function () {
  797. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  798. };
  799. Vector4.prototype.scaleInPlace = function (scale) {
  800. this.x *= scale;
  801. this.y *= scale;
  802. this.z *= scale;
  803. this.w *= scale;
  804. return this;
  805. };
  806. Vector4.prototype.scale = function (scale) {
  807. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  808. };
  809. Vector4.prototype.scaleToRef = function (scale, result) {
  810. result.x = this.x * scale;
  811. result.y = this.y * scale;
  812. result.z = this.z * scale;
  813. result.w = this.w * scale;
  814. };
  815. Vector4.prototype.equals = function (otherVector) {
  816. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  817. };
  818. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  819. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  820. };
  821. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  822. return this.x === x && this.y === y && this.z === z && this.w === w;
  823. };
  824. Vector4.prototype.multiplyInPlace = function (otherVector) {
  825. this.x *= otherVector.x;
  826. this.y *= otherVector.y;
  827. this.z *= otherVector.z;
  828. this.w *= otherVector.w;
  829. };
  830. Vector4.prototype.multiply = function (otherVector) {
  831. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  832. };
  833. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  834. result.x = this.x * otherVector.x;
  835. result.y = this.y * otherVector.y;
  836. result.z = this.z * otherVector.z;
  837. result.w = this.w * otherVector.w;
  838. };
  839. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  840. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  841. };
  842. Vector4.prototype.divide = function (otherVector) {
  843. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  844. };
  845. Vector4.prototype.divideToRef = function (otherVector, result) {
  846. result.x = this.x / otherVector.x;
  847. result.y = this.y / otherVector.y;
  848. result.z = this.z / otherVector.z;
  849. result.w = this.w / otherVector.w;
  850. };
  851. Vector4.prototype.MinimizeInPlace = function (other) {
  852. if (other.x < this.x)
  853. this.x = other.x;
  854. if (other.y < this.y)
  855. this.y = other.y;
  856. if (other.z < this.z)
  857. this.z = other.z;
  858. if (other.w < this.w)
  859. this.w = other.w;
  860. };
  861. Vector4.prototype.MaximizeInPlace = function (other) {
  862. if (other.x > this.x)
  863. this.x = other.x;
  864. if (other.y > this.y)
  865. this.y = other.y;
  866. if (other.z > this.z)
  867. this.z = other.z;
  868. if (other.w > this.w)
  869. this.w = other.w;
  870. };
  871. // Properties
  872. Vector4.prototype.length = function () {
  873. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  874. };
  875. Vector4.prototype.lengthSquared = function () {
  876. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  877. };
  878. // Methods
  879. Vector4.prototype.normalize = function () {
  880. var len = this.length();
  881. if (len === 0)
  882. return this;
  883. var num = 1.0 / len;
  884. this.x *= num;
  885. this.y *= num;
  886. this.z *= num;
  887. this.w *= num;
  888. return this;
  889. };
  890. Vector4.prototype.clone = function () {
  891. return new Vector4(this.x, this.y, this.z, this.w);
  892. };
  893. Vector4.prototype.copyFrom = function (source) {
  894. this.x = source.x;
  895. this.y = source.y;
  896. this.z = source.z;
  897. this.w = source.w;
  898. };
  899. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  900. this.x = x;
  901. this.y = y;
  902. this.z = z;
  903. this.w = w;
  904. };
  905. // Statics
  906. Vector4.FromArray = function (array, offset) {
  907. if (!offset) {
  908. offset = 0;
  909. }
  910. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  911. };
  912. Vector4.FromArrayToRef = function (array, offset, result) {
  913. result.x = array[offset];
  914. result.y = array[offset + 1];
  915. result.z = array[offset + 2];
  916. result.w = array[offset + 3];
  917. };
  918. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  919. result.x = array[offset];
  920. result.y = array[offset + 1];
  921. result.z = array[offset + 2];
  922. result.w = array[offset + 3];
  923. };
  924. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  925. result.x = x;
  926. result.y = y;
  927. result.z = z;
  928. result.w = w;
  929. };
  930. Vector4.Zero = function () {
  931. return new Vector4(0, 0, 0, 0);
  932. };
  933. Vector4.Normalize = function (vector) {
  934. var result = Vector4.Zero();
  935. Vector4.NormalizeToRef(vector, result);
  936. return result;
  937. };
  938. Vector4.NormalizeToRef = function (vector, result) {
  939. result.copyFrom(vector);
  940. result.normalize();
  941. };
  942. Vector4.Minimize = function (left, right) {
  943. var min = left.clone();
  944. min.MinimizeInPlace(right);
  945. return min;
  946. };
  947. Vector4.Maximize = function (left, right) {
  948. var max = left.clone();
  949. max.MaximizeInPlace(right);
  950. return max;
  951. };
  952. Vector4.Distance = function (value1, value2) {
  953. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  954. };
  955. Vector4.DistanceSquared = function (value1, value2) {
  956. var x = value1.x - value2.x;
  957. var y = value1.y - value2.y;
  958. var z = value1.z - value2.z;
  959. var w = value1.w - value2.w;
  960. return (x * x) + (y * y) + (z * z) + (w * w);
  961. };
  962. Vector4.Center = function (value1, value2) {
  963. var center = value1.add(value2);
  964. center.scaleInPlace(0.5);
  965. return center;
  966. };
  967. return Vector4;
  968. })();
  969. BABYLON.Vector4 = Vector4;
  970. var Quaternion = (function () {
  971. function Quaternion(x, y, z, w) {
  972. if (x === void 0) { x = 0; }
  973. if (y === void 0) { y = 0; }
  974. if (z === void 0) { z = 0; }
  975. if (w === void 0) { w = 1; }
  976. this.x = x;
  977. this.y = y;
  978. this.z = z;
  979. this.w = w;
  980. }
  981. Quaternion.prototype.toString = function () {
  982. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  983. };
  984. Quaternion.prototype.asArray = function () {
  985. return [this.x, this.y, this.z, this.w];
  986. };
  987. Quaternion.prototype.equals = function (otherQuaternion) {
  988. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  989. };
  990. Quaternion.prototype.clone = function () {
  991. return new Quaternion(this.x, this.y, this.z, this.w);
  992. };
  993. Quaternion.prototype.copyFrom = function (other) {
  994. this.x = other.x;
  995. this.y = other.y;
  996. this.z = other.z;
  997. this.w = other.w;
  998. };
  999. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1000. this.x = x;
  1001. this.y = y;
  1002. this.z = z;
  1003. this.w = w;
  1004. };
  1005. Quaternion.prototype.add = function (other) {
  1006. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1007. };
  1008. Quaternion.prototype.subtract = function (other) {
  1009. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1010. };
  1011. Quaternion.prototype.scale = function (value) {
  1012. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1013. };
  1014. Quaternion.prototype.multiply = function (q1) {
  1015. var result = new Quaternion(0, 0, 0, 1.0);
  1016. this.multiplyToRef(q1, result);
  1017. return result;
  1018. };
  1019. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1020. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1021. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1022. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1023. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1024. };
  1025. Quaternion.prototype.length = function () {
  1026. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1027. };
  1028. Quaternion.prototype.normalize = function () {
  1029. var length = 1.0 / this.length();
  1030. this.x *= length;
  1031. this.y *= length;
  1032. this.z *= length;
  1033. this.w *= length;
  1034. };
  1035. Quaternion.prototype.toEulerAngles = function () {
  1036. var result = Vector3.Zero();
  1037. this.toEulerAnglesToRef(result);
  1038. return result;
  1039. };
  1040. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1041. //result is an EulerAngles in the in the z-x-z convention
  1042. var qx = this.x;
  1043. var qy = this.y;
  1044. var qz = this.z;
  1045. var qw = this.w;
  1046. var qxy = qx * qy;
  1047. var qxz = qx * qz;
  1048. var qwy = qw * qy;
  1049. var qwz = qw * qz;
  1050. var qwx = qw * qx;
  1051. var qyz = qy * qz;
  1052. var sqx = qx * qx;
  1053. var sqy = qy * qy;
  1054. var determinant = sqx + sqy;
  1055. if (determinant !== 0.000 && determinant !== 1.000) {
  1056. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1057. result.y = Math.acos(1 - 2 * determinant);
  1058. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1059. }
  1060. else {
  1061. if (determinant === 0.0) {
  1062. result.x = 0.0;
  1063. result.y = 0.0;
  1064. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1065. }
  1066. else {
  1067. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1068. result.y = Math.PI;
  1069. result.z = 0.0;
  1070. }
  1071. }
  1072. };
  1073. Quaternion.prototype.toRotationMatrix = function (result) {
  1074. var xx = this.x * this.x;
  1075. var yy = this.y * this.y;
  1076. var zz = this.z * this.z;
  1077. var xy = this.x * this.y;
  1078. var zw = this.z * this.w;
  1079. var zx = this.z * this.x;
  1080. var yw = this.y * this.w;
  1081. var yz = this.y * this.z;
  1082. var xw = this.x * this.w;
  1083. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1084. result.m[1] = 2.0 * (xy + zw);
  1085. result.m[2] = 2.0 * (zx - yw);
  1086. result.m[3] = 0;
  1087. result.m[4] = 2.0 * (xy - zw);
  1088. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1089. result.m[6] = 2.0 * (yz + xw);
  1090. result.m[7] = 0;
  1091. result.m[8] = 2.0 * (zx + yw);
  1092. result.m[9] = 2.0 * (yz - xw);
  1093. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1094. result.m[11] = 0;
  1095. result.m[12] = 0;
  1096. result.m[13] = 0;
  1097. result.m[14] = 0;
  1098. result.m[15] = 1.0;
  1099. };
  1100. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1101. var data = matrix.m;
  1102. var m11 = data[0], m12 = data[4], m13 = data[8];
  1103. var m21 = data[1], m22 = data[5], m23 = data[9];
  1104. var m31 = data[2], m32 = data[6], m33 = data[10];
  1105. var trace = m11 + m22 + m33;
  1106. var s;
  1107. if (trace > 0) {
  1108. s = 0.5 / Math.sqrt(trace + 1.0);
  1109. this.w = 0.25 / s;
  1110. this.x = (m32 - m23) * s;
  1111. this.y = (m13 - m31) * s;
  1112. this.z = (m21 - m12) * s;
  1113. return;
  1114. }
  1115. if (m11 > m22 && m11 > m33) {
  1116. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1117. this.w = (m32 - m23) / s;
  1118. this.x = 0.25 * s;
  1119. this.y = (m12 + m21) / s;
  1120. this.z = (m13 + m31) / s;
  1121. return;
  1122. }
  1123. if (m22 > m33) {
  1124. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1125. this.w = (m13 - m31) / s;
  1126. this.x = (m12 + m21) / s;
  1127. this.y = 0.25 * s;
  1128. this.z = (m23 + m32) / s;
  1129. return;
  1130. }
  1131. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1132. this.w = (m21 - m12) / s;
  1133. this.x = (m13 + m31) / s;
  1134. this.y = (m23 + m32) / s;
  1135. this.z = 0.25 * s;
  1136. };
  1137. // Statics
  1138. Quaternion.Inverse = function (q) {
  1139. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1140. };
  1141. Quaternion.Identity = function () {
  1142. return new Quaternion(0, 0, 0, 1);
  1143. };
  1144. Quaternion.RotationAxis = function (axis, angle) {
  1145. var result = new Quaternion();
  1146. var sin = Math.sin(angle / 2);
  1147. result.w = Math.cos(angle / 2);
  1148. result.x = axis.x * sin;
  1149. result.y = axis.y * sin;
  1150. result.z = axis.z * sin;
  1151. return result;
  1152. };
  1153. Quaternion.FromArray = function (array, offset) {
  1154. if (!offset) {
  1155. offset = 0;
  1156. }
  1157. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1158. };
  1159. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1160. var result = new Quaternion();
  1161. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1162. return result;
  1163. };
  1164. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1165. var halfRoll = roll * 0.5;
  1166. var halfPitch = pitch * 0.5;
  1167. var halfYaw = yaw * 0.5;
  1168. var sinRoll = Math.sin(halfRoll);
  1169. var cosRoll = Math.cos(halfRoll);
  1170. var sinPitch = Math.sin(halfPitch);
  1171. var cosPitch = Math.cos(halfPitch);
  1172. var sinYaw = Math.sin(halfYaw);
  1173. var cosYaw = Math.cos(halfYaw);
  1174. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1175. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1176. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1177. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1178. };
  1179. Quaternion.Slerp = function (left, right, amount) {
  1180. var num2;
  1181. var num3;
  1182. var num = amount;
  1183. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1184. var flag = false;
  1185. if (num4 < 0) {
  1186. flag = true;
  1187. num4 = -num4;
  1188. }
  1189. if (num4 > 0.999999) {
  1190. num3 = 1 - num;
  1191. num2 = flag ? -num : num;
  1192. }
  1193. else {
  1194. var num5 = Math.acos(num4);
  1195. var num6 = (1.0 / Math.sin(num5));
  1196. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1197. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1198. }
  1199. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1200. };
  1201. return Quaternion;
  1202. })();
  1203. BABYLON.Quaternion = Quaternion;
  1204. var Matrix = (function () {
  1205. function Matrix() {
  1206. this.m = new Float32Array(16);
  1207. }
  1208. // Properties
  1209. Matrix.prototype.isIdentity = function () {
  1210. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1211. return false;
  1212. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1213. return false;
  1214. return true;
  1215. };
  1216. Matrix.prototype.determinant = function () {
  1217. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1218. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1219. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1220. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1221. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1222. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1223. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1224. };
  1225. // Methods
  1226. Matrix.prototype.toArray = function () {
  1227. return this.m;
  1228. };
  1229. Matrix.prototype.asArray = function () {
  1230. return this.toArray();
  1231. };
  1232. Matrix.prototype.invert = function () {
  1233. this.invertToRef(this);
  1234. };
  1235. Matrix.prototype.invertToRef = function (other) {
  1236. var l1 = this.m[0];
  1237. var l2 = this.m[1];
  1238. var l3 = this.m[2];
  1239. var l4 = this.m[3];
  1240. var l5 = this.m[4];
  1241. var l6 = this.m[5];
  1242. var l7 = this.m[6];
  1243. var l8 = this.m[7];
  1244. var l9 = this.m[8];
  1245. var l10 = this.m[9];
  1246. var l11 = this.m[10];
  1247. var l12 = this.m[11];
  1248. var l13 = this.m[12];
  1249. var l14 = this.m[13];
  1250. var l15 = this.m[14];
  1251. var l16 = this.m[15];
  1252. var l17 = (l11 * l16) - (l12 * l15);
  1253. var l18 = (l10 * l16) - (l12 * l14);
  1254. var l19 = (l10 * l15) - (l11 * l14);
  1255. var l20 = (l9 * l16) - (l12 * l13);
  1256. var l21 = (l9 * l15) - (l11 * l13);
  1257. var l22 = (l9 * l14) - (l10 * l13);
  1258. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1259. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1260. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1261. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1262. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1263. var l28 = (l7 * l16) - (l8 * l15);
  1264. var l29 = (l6 * l16) - (l8 * l14);
  1265. var l30 = (l6 * l15) - (l7 * l14);
  1266. var l31 = (l5 * l16) - (l8 * l13);
  1267. var l32 = (l5 * l15) - (l7 * l13);
  1268. var l33 = (l5 * l14) - (l6 * l13);
  1269. var l34 = (l7 * l12) - (l8 * l11);
  1270. var l35 = (l6 * l12) - (l8 * l10);
  1271. var l36 = (l6 * l11) - (l7 * l10);
  1272. var l37 = (l5 * l12) - (l8 * l9);
  1273. var l38 = (l5 * l11) - (l7 * l9);
  1274. var l39 = (l5 * l10) - (l6 * l9);
  1275. other.m[0] = l23 * l27;
  1276. other.m[4] = l24 * l27;
  1277. other.m[8] = l25 * l27;
  1278. other.m[12] = l26 * l27;
  1279. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1280. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1281. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1282. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1283. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1284. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1285. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1286. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1287. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1288. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1289. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1290. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1291. };
  1292. Matrix.prototype.setTranslation = function (vector3) {
  1293. this.m[12] = vector3.x;
  1294. this.m[13] = vector3.y;
  1295. this.m[14] = vector3.z;
  1296. };
  1297. Matrix.prototype.multiply = function (other) {
  1298. var result = new Matrix();
  1299. this.multiplyToRef(other, result);
  1300. return result;
  1301. };
  1302. Matrix.prototype.copyFrom = function (other) {
  1303. for (var index = 0; index < 16; index++) {
  1304. this.m[index] = other.m[index];
  1305. }
  1306. };
  1307. Matrix.prototype.copyToArray = function (array, offset) {
  1308. if (offset === void 0) { offset = 0; }
  1309. for (var index = 0; index < 16; index++) {
  1310. array[offset + index] = this.m[index];
  1311. }
  1312. };
  1313. Matrix.prototype.multiplyToRef = function (other, result) {
  1314. this.multiplyToArray(other, result.m, 0);
  1315. };
  1316. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1317. var tm0 = this.m[0];
  1318. var tm1 = this.m[1];
  1319. var tm2 = this.m[2];
  1320. var tm3 = this.m[3];
  1321. var tm4 = this.m[4];
  1322. var tm5 = this.m[5];
  1323. var tm6 = this.m[6];
  1324. var tm7 = this.m[7];
  1325. var tm8 = this.m[8];
  1326. var tm9 = this.m[9];
  1327. var tm10 = this.m[10];
  1328. var tm11 = this.m[11];
  1329. var tm12 = this.m[12];
  1330. var tm13 = this.m[13];
  1331. var tm14 = this.m[14];
  1332. var tm15 = this.m[15];
  1333. var om0 = other.m[0];
  1334. var om1 = other.m[1];
  1335. var om2 = other.m[2];
  1336. var om3 = other.m[3];
  1337. var om4 = other.m[4];
  1338. var om5 = other.m[5];
  1339. var om6 = other.m[6];
  1340. var om7 = other.m[7];
  1341. var om8 = other.m[8];
  1342. var om9 = other.m[9];
  1343. var om10 = other.m[10];
  1344. var om11 = other.m[11];
  1345. var om12 = other.m[12];
  1346. var om13 = other.m[13];
  1347. var om14 = other.m[14];
  1348. var om15 = other.m[15];
  1349. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1350. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1351. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1352. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1353. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1354. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1355. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1356. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1357. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1358. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1359. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1360. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1361. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1362. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1363. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1364. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1365. };
  1366. Matrix.prototype.equals = function (value) {
  1367. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1368. };
  1369. Matrix.prototype.clone = function () {
  1370. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1371. };
  1372. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1373. translation.x = this.m[12];
  1374. translation.y = this.m[13];
  1375. translation.z = this.m[14];
  1376. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1377. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1378. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1379. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1380. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1381. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1382. if (scale.x == 0 || scale.y == 0 || scale.z == 0) {
  1383. rotation.x = 0;
  1384. rotation.y = 0;
  1385. rotation.z = 0;
  1386. rotation.w = 1;
  1387. return false;
  1388. }
  1389. var rotationMatrix = BABYLON.Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1390. rotation.fromRotationMatrix(rotationMatrix);
  1391. return true;
  1392. };
  1393. // Statics
  1394. Matrix.FromArray = function (array, offset) {
  1395. var result = new Matrix();
  1396. if (!offset) {
  1397. offset = 0;
  1398. }
  1399. Matrix.FromArrayToRef(array, offset, result);
  1400. return result;
  1401. };
  1402. Matrix.FromArrayToRef = function (array, offset, result) {
  1403. for (var index = 0; index < 16; index++) {
  1404. result.m[index] = array[index + offset];
  1405. }
  1406. };
  1407. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1408. result.m[0] = initialM11;
  1409. result.m[1] = initialM12;
  1410. result.m[2] = initialM13;
  1411. result.m[3] = initialM14;
  1412. result.m[4] = initialM21;
  1413. result.m[5] = initialM22;
  1414. result.m[6] = initialM23;
  1415. result.m[7] = initialM24;
  1416. result.m[8] = initialM31;
  1417. result.m[9] = initialM32;
  1418. result.m[10] = initialM33;
  1419. result.m[11] = initialM34;
  1420. result.m[12] = initialM41;
  1421. result.m[13] = initialM42;
  1422. result.m[14] = initialM43;
  1423. result.m[15] = initialM44;
  1424. };
  1425. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1426. var result = new Matrix();
  1427. result.m[0] = initialM11;
  1428. result.m[1] = initialM12;
  1429. result.m[2] = initialM13;
  1430. result.m[3] = initialM14;
  1431. result.m[4] = initialM21;
  1432. result.m[5] = initialM22;
  1433. result.m[6] = initialM23;
  1434. result.m[7] = initialM24;
  1435. result.m[8] = initialM31;
  1436. result.m[9] = initialM32;
  1437. result.m[10] = initialM33;
  1438. result.m[11] = initialM34;
  1439. result.m[12] = initialM41;
  1440. result.m[13] = initialM42;
  1441. result.m[14] = initialM43;
  1442. result.m[15] = initialM44;
  1443. return result;
  1444. };
  1445. Matrix.Compose = function (scale, rotation, translation) {
  1446. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1447. var rotationMatrix = Matrix.Identity();
  1448. rotation.toRotationMatrix(rotationMatrix);
  1449. result = result.multiply(rotationMatrix);
  1450. result.setTranslation(translation);
  1451. return result;
  1452. };
  1453. Matrix.Identity = function () {
  1454. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1455. };
  1456. Matrix.IdentityToRef = function (result) {
  1457. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1458. };
  1459. Matrix.Zero = function () {
  1460. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1461. };
  1462. Matrix.RotationX = function (angle) {
  1463. var result = new Matrix();
  1464. Matrix.RotationXToRef(angle, result);
  1465. return result;
  1466. };
  1467. Matrix.Invert = function (source) {
  1468. var result = new Matrix();
  1469. source.invertToRef(result);
  1470. return result;
  1471. };
  1472. Matrix.RotationXToRef = function (angle, result) {
  1473. var s = Math.sin(angle);
  1474. var c = Math.cos(angle);
  1475. result.m[0] = 1.0;
  1476. result.m[15] = 1.0;
  1477. result.m[5] = c;
  1478. result.m[10] = c;
  1479. result.m[9] = -s;
  1480. result.m[6] = s;
  1481. result.m[1] = 0;
  1482. result.m[2] = 0;
  1483. result.m[3] = 0;
  1484. result.m[4] = 0;
  1485. result.m[7] = 0;
  1486. result.m[8] = 0;
  1487. result.m[11] = 0;
  1488. result.m[12] = 0;
  1489. result.m[13] = 0;
  1490. result.m[14] = 0;
  1491. };
  1492. Matrix.RotationY = function (angle) {
  1493. var result = new Matrix();
  1494. Matrix.RotationYToRef(angle, result);
  1495. return result;
  1496. };
  1497. Matrix.RotationYToRef = function (angle, result) {
  1498. var s = Math.sin(angle);
  1499. var c = Math.cos(angle);
  1500. result.m[5] = 1.0;
  1501. result.m[15] = 1.0;
  1502. result.m[0] = c;
  1503. result.m[2] = -s;
  1504. result.m[8] = s;
  1505. result.m[10] = c;
  1506. result.m[1] = 0;
  1507. result.m[3] = 0;
  1508. result.m[4] = 0;
  1509. result.m[6] = 0;
  1510. result.m[7] = 0;
  1511. result.m[9] = 0;
  1512. result.m[11] = 0;
  1513. result.m[12] = 0;
  1514. result.m[13] = 0;
  1515. result.m[14] = 0;
  1516. };
  1517. Matrix.RotationZ = function (angle) {
  1518. var result = new Matrix();
  1519. Matrix.RotationZToRef(angle, result);
  1520. return result;
  1521. };
  1522. Matrix.RotationZToRef = function (angle, result) {
  1523. var s = Math.sin(angle);
  1524. var c = Math.cos(angle);
  1525. result.m[10] = 1.0;
  1526. result.m[15] = 1.0;
  1527. result.m[0] = c;
  1528. result.m[1] = s;
  1529. result.m[4] = -s;
  1530. result.m[5] = c;
  1531. result.m[2] = 0;
  1532. result.m[3] = 0;
  1533. result.m[6] = 0;
  1534. result.m[7] = 0;
  1535. result.m[8] = 0;
  1536. result.m[9] = 0;
  1537. result.m[11] = 0;
  1538. result.m[12] = 0;
  1539. result.m[13] = 0;
  1540. result.m[14] = 0;
  1541. };
  1542. Matrix.RotationAxis = function (axis, angle) {
  1543. var s = Math.sin(-angle);
  1544. var c = Math.cos(-angle);
  1545. var c1 = 1 - c;
  1546. axis.normalize();
  1547. var result = Matrix.Zero();
  1548. result.m[0] = (axis.x * axis.x) * c1 + c;
  1549. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1550. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1551. result.m[3] = 0.0;
  1552. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1553. result.m[5] = (axis.y * axis.y) * c1 + c;
  1554. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1555. result.m[7] = 0.0;
  1556. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1557. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1558. result.m[10] = (axis.z * axis.z) * c1 + c;
  1559. result.m[11] = 0.0;
  1560. result.m[15] = 1.0;
  1561. return result;
  1562. };
  1563. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1564. var result = new Matrix();
  1565. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1566. return result;
  1567. };
  1568. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1569. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1570. this._tempQuaternion.toRotationMatrix(result);
  1571. };
  1572. Matrix.Scaling = function (x, y, z) {
  1573. var result = Matrix.Zero();
  1574. Matrix.ScalingToRef(x, y, z, result);
  1575. return result;
  1576. };
  1577. Matrix.ScalingToRef = function (x, y, z, result) {
  1578. result.m[0] = x;
  1579. result.m[1] = 0;
  1580. result.m[2] = 0;
  1581. result.m[3] = 0;
  1582. result.m[4] = 0;
  1583. result.m[5] = y;
  1584. result.m[6] = 0;
  1585. result.m[7] = 0;
  1586. result.m[8] = 0;
  1587. result.m[9] = 0;
  1588. result.m[10] = z;
  1589. result.m[11] = 0;
  1590. result.m[12] = 0;
  1591. result.m[13] = 0;
  1592. result.m[14] = 0;
  1593. result.m[15] = 1.0;
  1594. };
  1595. Matrix.Translation = function (x, y, z) {
  1596. var result = Matrix.Identity();
  1597. Matrix.TranslationToRef(x, y, z, result);
  1598. return result;
  1599. };
  1600. Matrix.TranslationToRef = function (x, y, z, result) {
  1601. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1602. };
  1603. Matrix.LookAtLH = function (eye, target, up) {
  1604. var result = Matrix.Zero();
  1605. Matrix.LookAtLHToRef(eye, target, up, result);
  1606. return result;
  1607. };
  1608. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1609. // Z axis
  1610. target.subtractToRef(eye, this._zAxis);
  1611. this._zAxis.normalize();
  1612. // X axis
  1613. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1614. this._xAxis.normalize();
  1615. // Y axis
  1616. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1617. this._yAxis.normalize();
  1618. // Eye angles
  1619. var ex = -Vector3.Dot(this._xAxis, eye);
  1620. var ey = -Vector3.Dot(this._yAxis, eye);
  1621. var ez = -Vector3.Dot(this._zAxis, eye);
  1622. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1623. };
  1624. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1625. var hw = 2.0 / width;
  1626. var hh = 2.0 / height;
  1627. var id = 1.0 / (zfar - znear);
  1628. var nid = znear / (znear - zfar);
  1629. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1630. };
  1631. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1632. var matrix = Matrix.Zero();
  1633. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1634. return matrix;
  1635. };
  1636. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1637. result.m[0] = 2.0 / (right - left);
  1638. result.m[1] = result.m[2] = result.m[3] = 0;
  1639. result.m[5] = 2.0 / (top - bottom);
  1640. result.m[4] = result.m[6] = result.m[7] = 0;
  1641. result.m[10] = -1.0 / (znear - zfar);
  1642. result.m[8] = result.m[9] = result.m[11] = 0;
  1643. result.m[12] = (left + right) / (left - right);
  1644. result.m[13] = (top + bottom) / (bottom - top);
  1645. result.m[14] = znear / (znear - zfar);
  1646. result.m[15] = 1.0;
  1647. };
  1648. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1649. var matrix = Matrix.Zero();
  1650. matrix.m[0] = (2.0 * znear) / width;
  1651. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1652. matrix.m[5] = (2.0 * znear) / height;
  1653. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1654. matrix.m[10] = -zfar / (znear - zfar);
  1655. matrix.m[8] = matrix.m[9] = 0.0;
  1656. matrix.m[11] = 1.0;
  1657. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1658. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1659. return matrix;
  1660. };
  1661. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1662. var matrix = Matrix.Zero();
  1663. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1664. return matrix;
  1665. };
  1666. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1667. var tan = 1.0 / (Math.tan(fov * 0.5));
  1668. result.m[0] = tan / aspect;
  1669. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1670. result.m[5] = tan;
  1671. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1672. result.m[8] = result.m[9] = 0.0;
  1673. result.m[10] = -zfar / (znear - zfar);
  1674. result.m[11] = 1.0;
  1675. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1676. result.m[14] = (znear * zfar) / (znear - zfar);
  1677. };
  1678. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1679. var cw = viewport.width;
  1680. var ch = viewport.height;
  1681. var cx = viewport.x;
  1682. var cy = viewport.y;
  1683. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  1684. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1685. };
  1686. Matrix.Transpose = function (matrix) {
  1687. var result = new Matrix();
  1688. result.m[0] = matrix.m[0];
  1689. result.m[1] = matrix.m[4];
  1690. result.m[2] = matrix.m[8];
  1691. result.m[3] = matrix.m[12];
  1692. result.m[4] = matrix.m[1];
  1693. result.m[5] = matrix.m[5];
  1694. result.m[6] = matrix.m[9];
  1695. result.m[7] = matrix.m[13];
  1696. result.m[8] = matrix.m[2];
  1697. result.m[9] = matrix.m[6];
  1698. result.m[10] = matrix.m[10];
  1699. result.m[11] = matrix.m[14];
  1700. result.m[12] = matrix.m[3];
  1701. result.m[13] = matrix.m[7];
  1702. result.m[14] = matrix.m[11];
  1703. result.m[15] = matrix.m[15];
  1704. return result;
  1705. };
  1706. Matrix.Reflection = function (plane) {
  1707. var matrix = new Matrix();
  1708. Matrix.ReflectionToRef(plane, matrix);
  1709. return matrix;
  1710. };
  1711. Matrix.ReflectionToRef = function (plane, result) {
  1712. plane.normalize();
  1713. var x = plane.normal.x;
  1714. var y = plane.normal.y;
  1715. var z = plane.normal.z;
  1716. var temp = -2 * x;
  1717. var temp2 = -2 * y;
  1718. var temp3 = -2 * z;
  1719. result.m[0] = (temp * x) + 1;
  1720. result.m[1] = temp2 * x;
  1721. result.m[2] = temp3 * x;
  1722. result.m[3] = 0.0;
  1723. result.m[4] = temp * y;
  1724. result.m[5] = (temp2 * y) + 1;
  1725. result.m[6] = temp3 * y;
  1726. result.m[7] = 0.0;
  1727. result.m[8] = temp * z;
  1728. result.m[9] = temp2 * z;
  1729. result.m[10] = (temp3 * z) + 1;
  1730. result.m[11] = 0.0;
  1731. result.m[12] = temp * plane.d;
  1732. result.m[13] = temp2 * plane.d;
  1733. result.m[14] = temp3 * plane.d;
  1734. result.m[15] = 1.0;
  1735. };
  1736. Matrix._tempQuaternion = new Quaternion();
  1737. Matrix._xAxis = Vector3.Zero();
  1738. Matrix._yAxis = Vector3.Zero();
  1739. Matrix._zAxis = Vector3.Zero();
  1740. return Matrix;
  1741. })();
  1742. BABYLON.Matrix = Matrix;
  1743. var Plane = (function () {
  1744. function Plane(a, b, c, d) {
  1745. this.normal = new Vector3(a, b, c);
  1746. this.d = d;
  1747. }
  1748. Plane.prototype.asArray = function () {
  1749. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1750. };
  1751. // Methods
  1752. Plane.prototype.clone = function () {
  1753. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1754. };
  1755. Plane.prototype.normalize = function () {
  1756. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1757. var magnitude = 0;
  1758. if (norm !== 0) {
  1759. magnitude = 1.0 / norm;
  1760. }
  1761. this.normal.x *= magnitude;
  1762. this.normal.y *= magnitude;
  1763. this.normal.z *= magnitude;
  1764. this.d *= magnitude;
  1765. };
  1766. Plane.prototype.transform = function (transformation) {
  1767. var transposedMatrix = Matrix.Transpose(transformation);
  1768. var x = this.normal.x;
  1769. var y = this.normal.y;
  1770. var z = this.normal.z;
  1771. var d = this.d;
  1772. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1773. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1774. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1775. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1776. return new Plane(normalX, normalY, normalZ, finalD);
  1777. };
  1778. Plane.prototype.dotCoordinate = function (point) {
  1779. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1780. };
  1781. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1782. var x1 = point2.x - point1.x;
  1783. var y1 = point2.y - point1.y;
  1784. var z1 = point2.z - point1.z;
  1785. var x2 = point3.x - point1.x;
  1786. var y2 = point3.y - point1.y;
  1787. var z2 = point3.z - point1.z;
  1788. var yz = (y1 * z2) - (z1 * y2);
  1789. var xz = (z1 * x2) - (x1 * z2);
  1790. var xy = (x1 * y2) - (y1 * x2);
  1791. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1792. var invPyth;
  1793. if (pyth !== 0) {
  1794. invPyth = 1.0 / pyth;
  1795. }
  1796. else {
  1797. invPyth = 0;
  1798. }
  1799. this.normal.x = yz * invPyth;
  1800. this.normal.y = xz * invPyth;
  1801. this.normal.z = xy * invPyth;
  1802. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1803. };
  1804. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1805. var dot = Vector3.Dot(this.normal, direction);
  1806. return (dot <= epsilon);
  1807. };
  1808. Plane.prototype.signedDistanceTo = function (point) {
  1809. return Vector3.Dot(point, this.normal) + this.d;
  1810. };
  1811. // Statics
  1812. Plane.FromArray = function (array) {
  1813. return new Plane(array[0], array[1], array[2], array[3]);
  1814. };
  1815. Plane.FromPoints = function (point1, point2, point3) {
  1816. var result = new Plane(0, 0, 0, 0);
  1817. result.copyFromPoints(point1, point2, point3);
  1818. return result;
  1819. };
  1820. Plane.FromPositionAndNormal = function (origin, normal) {
  1821. var result = new Plane(0, 0, 0, 0);
  1822. normal.normalize();
  1823. result.normal = normal;
  1824. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1825. return result;
  1826. };
  1827. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1828. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1829. return Vector3.Dot(point, normal) + d;
  1830. };
  1831. return Plane;
  1832. })();
  1833. BABYLON.Plane = Plane;
  1834. var Viewport = (function () {
  1835. function Viewport(x, y, width, height) {
  1836. this.x = x;
  1837. this.y = y;
  1838. this.width = width;
  1839. this.height = height;
  1840. }
  1841. Viewport.prototype.toGlobal = function (engine) {
  1842. var width = engine.getRenderWidth();
  1843. var height = engine.getRenderHeight();
  1844. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1845. };
  1846. return Viewport;
  1847. })();
  1848. BABYLON.Viewport = Viewport;
  1849. var Frustum = (function () {
  1850. function Frustum() {
  1851. }
  1852. Frustum.GetPlanes = function (transform) {
  1853. var frustumPlanes = [];
  1854. for (var index = 0; index < 6; index++) {
  1855. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1856. }
  1857. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1858. return frustumPlanes;
  1859. };
  1860. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1861. // Near
  1862. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1863. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1864. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1865. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1866. frustumPlanes[0].normalize();
  1867. // Far
  1868. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1869. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1870. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1871. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1872. frustumPlanes[1].normalize();
  1873. // Left
  1874. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1875. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1876. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1877. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1878. frustumPlanes[2].normalize();
  1879. // Right
  1880. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1881. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1882. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1883. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1884. frustumPlanes[3].normalize();
  1885. // Top
  1886. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1887. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1888. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1889. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1890. frustumPlanes[4].normalize();
  1891. // Bottom
  1892. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1893. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1894. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1895. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1896. frustumPlanes[5].normalize();
  1897. };
  1898. return Frustum;
  1899. })();
  1900. BABYLON.Frustum = Frustum;
  1901. var Ray = (function () {
  1902. function Ray(origin, direction, length) {
  1903. if (length === void 0) { length = Number.MAX_VALUE; }
  1904. this.origin = origin;
  1905. this.direction = direction;
  1906. this.length = length;
  1907. }
  1908. // Methods
  1909. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1910. var d = 0.0;
  1911. var maxValue = Number.MAX_VALUE;
  1912. if (Math.abs(this.direction.x) < 0.0000001) {
  1913. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1914. return false;
  1915. }
  1916. }
  1917. else {
  1918. var inv = 1.0 / this.direction.x;
  1919. var min = (minimum.x - this.origin.x) * inv;
  1920. var max = (maximum.x - this.origin.x) * inv;
  1921. if (max === -Infinity) {
  1922. max = Infinity;
  1923. }
  1924. if (min > max) {
  1925. var temp = min;
  1926. min = max;
  1927. max = temp;
  1928. }
  1929. d = Math.max(min, d);
  1930. maxValue = Math.min(max, maxValue);
  1931. if (d > maxValue) {
  1932. return false;
  1933. }
  1934. }
  1935. if (Math.abs(this.direction.y) < 0.0000001) {
  1936. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1937. return false;
  1938. }
  1939. }
  1940. else {
  1941. inv = 1.0 / this.direction.y;
  1942. min = (minimum.y - this.origin.y) * inv;
  1943. max = (maximum.y - this.origin.y) * inv;
  1944. if (max === -Infinity) {
  1945. max = Infinity;
  1946. }
  1947. if (min > max) {
  1948. temp = min;
  1949. min = max;
  1950. max = temp;
  1951. }
  1952. d = Math.max(min, d);
  1953. maxValue = Math.min(max, maxValue);
  1954. if (d > maxValue) {
  1955. return false;
  1956. }
  1957. }
  1958. if (Math.abs(this.direction.z) < 0.0000001) {
  1959. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1960. return false;
  1961. }
  1962. }
  1963. else {
  1964. inv = 1.0 / this.direction.z;
  1965. min = (minimum.z - this.origin.z) * inv;
  1966. max = (maximum.z - this.origin.z) * inv;
  1967. if (max === -Infinity) {
  1968. max = Infinity;
  1969. }
  1970. if (min > max) {
  1971. temp = min;
  1972. min = max;
  1973. max = temp;
  1974. }
  1975. d = Math.max(min, d);
  1976. maxValue = Math.min(max, maxValue);
  1977. if (d > maxValue) {
  1978. return false;
  1979. }
  1980. }
  1981. return true;
  1982. };
  1983. Ray.prototype.intersectsBox = function (box) {
  1984. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1985. };
  1986. Ray.prototype.intersectsSphere = function (sphere) {
  1987. var x = sphere.center.x - this.origin.x;
  1988. var y = sphere.center.y - this.origin.y;
  1989. var z = sphere.center.z - this.origin.z;
  1990. var pyth = (x * x) + (y * y) + (z * z);
  1991. var rr = sphere.radius * sphere.radius;
  1992. if (pyth <= rr) {
  1993. return true;
  1994. }
  1995. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1996. if (dot < 0.0) {
  1997. return false;
  1998. }
  1999. var temp = pyth - (dot * dot);
  2000. return temp <= rr;
  2001. };
  2002. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2003. if (!this._edge1) {
  2004. this._edge1 = Vector3.Zero();
  2005. this._edge2 = Vector3.Zero();
  2006. this._pvec = Vector3.Zero();
  2007. this._tvec = Vector3.Zero();
  2008. this._qvec = Vector3.Zero();
  2009. }
  2010. vertex1.subtractToRef(vertex0, this._edge1);
  2011. vertex2.subtractToRef(vertex0, this._edge2);
  2012. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2013. var det = Vector3.Dot(this._edge1, this._pvec);
  2014. if (det === 0) {
  2015. return null;
  2016. }
  2017. var invdet = 1 / det;
  2018. this.origin.subtractToRef(vertex0, this._tvec);
  2019. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2020. if (bu < 0 || bu > 1.0) {
  2021. return null;
  2022. }
  2023. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2024. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2025. if (bv < 0 || bu + bv > 1.0) {
  2026. return null;
  2027. }
  2028. //check if the distance is longer than the predefined length.
  2029. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2030. if (distance > this.length) {
  2031. return null;
  2032. }
  2033. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2034. };
  2035. // Statics
  2036. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2037. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2038. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2039. var direction = end.subtract(start);
  2040. direction.normalize();
  2041. return new Ray(start, direction);
  2042. };
  2043. /**
  2044. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2045. * transformed to the given world matrix.
  2046. * @param origin The origin point
  2047. * @param end The end point
  2048. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2049. */
  2050. Ray.CreateNewFromTo = function (origin, end, world) {
  2051. if (world === void 0) { world = Matrix.Identity(); }
  2052. var direction = end.subtract(origin);
  2053. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2054. direction.normalize();
  2055. return Ray.Transform(new Ray(origin, direction, length), world);
  2056. };
  2057. Ray.Transform = function (ray, matrix) {
  2058. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2059. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2060. return new Ray(newOrigin, newDirection, ray.length);
  2061. };
  2062. return Ray;
  2063. })();
  2064. BABYLON.Ray = Ray;
  2065. (function (Space) {
  2066. Space[Space["LOCAL"] = 0] = "LOCAL";
  2067. Space[Space["WORLD"] = 1] = "WORLD";
  2068. })(BABYLON.Space || (BABYLON.Space = {}));
  2069. var Space = BABYLON.Space;
  2070. var Axis = (function () {
  2071. function Axis() {
  2072. }
  2073. Axis.X = new Vector3(1, 0, 0);
  2074. Axis.Y = new Vector3(0, 1, 0);
  2075. Axis.Z = new Vector3(0, 0, 1);
  2076. return Axis;
  2077. })();
  2078. BABYLON.Axis = Axis;
  2079. ;
  2080. var BezierCurve = (function () {
  2081. function BezierCurve() {
  2082. }
  2083. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2084. // Extract X (which is equal to time here)
  2085. var f0 = 1 - 3 * x2 + 3 * x1;
  2086. var f1 = 3 * x2 - 6 * x1;
  2087. var f2 = 3 * x1;
  2088. var refinedT = t;
  2089. for (var i = 0; i < 5; i++) {
  2090. var refinedT2 = refinedT * refinedT;
  2091. var refinedT3 = refinedT2 * refinedT;
  2092. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2093. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2094. refinedT -= (x - t) * slope;
  2095. refinedT = Math.min(1, Math.max(0, refinedT));
  2096. }
  2097. // Resolve cubic bezier for the given x
  2098. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2099. };
  2100. return BezierCurve;
  2101. })();
  2102. BABYLON.BezierCurve = BezierCurve;
  2103. (function (Orientation) {
  2104. Orientation[Orientation["CW"] = 0] = "CW";
  2105. Orientation[Orientation["CCW"] = 1] = "CCW";
  2106. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2107. var Orientation = BABYLON.Orientation;
  2108. var Angle = (function () {
  2109. function Angle(radians) {
  2110. var _this = this;
  2111. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2112. this.radians = function () { return _this._radians; };
  2113. this._radians = radians;
  2114. if (this._radians < 0)
  2115. this._radians += (2 * Math.PI);
  2116. }
  2117. Angle.BetweenTwoPoints = function (a, b) {
  2118. var delta = b.subtract(a);
  2119. var theta = Math.atan2(delta.y, delta.x);
  2120. return new Angle(theta);
  2121. };
  2122. Angle.FromRadians = function (radians) {
  2123. return new Angle(radians);
  2124. };
  2125. Angle.FromDegrees = function (degrees) {
  2126. return new Angle(degrees * Math.PI / 180);
  2127. };
  2128. return Angle;
  2129. })();
  2130. BABYLON.Angle = Angle;
  2131. var Arc2 = (function () {
  2132. function Arc2(startPoint, midPoint, endPoint) {
  2133. this.startPoint = startPoint;
  2134. this.midPoint = midPoint;
  2135. this.endPoint = endPoint;
  2136. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2137. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2138. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2139. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2140. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2141. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2142. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2143. var a1 = this.startAngle.degrees();
  2144. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2145. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2146. // angles correction
  2147. if (a2 - a1 > +180.0)
  2148. a2 -= 360.0;
  2149. if (a2 - a1 < -180.0)
  2150. a2 += 360.0;
  2151. if (a3 - a2 > +180.0)
  2152. a3 -= 360.0;
  2153. if (a3 - a2 < -180.0)
  2154. a3 += 360.0;
  2155. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2156. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2157. }
  2158. return Arc2;
  2159. })();
  2160. BABYLON.Arc2 = Arc2;
  2161. var PathCursor = (function () {
  2162. function PathCursor(path) {
  2163. this.path = path;
  2164. this._onchange = new Array();
  2165. this.value = 0;
  2166. this.animations = new Array();
  2167. }
  2168. PathCursor.prototype.getPoint = function () {
  2169. var point = this.path.getPointAtLengthPosition(this.value);
  2170. return new Vector3(point.x, 0, point.y);
  2171. };
  2172. PathCursor.prototype.moveAhead = function (step) {
  2173. if (step === void 0) { step = 0.002; }
  2174. this.move(step);
  2175. };
  2176. PathCursor.prototype.moveBack = function (step) {
  2177. if (step === void 0) { step = 0.002; }
  2178. this.move(-step);
  2179. };
  2180. PathCursor.prototype.move = function (step) {
  2181. if (Math.abs(step) > 1) {
  2182. throw "step size should be less than 1.";
  2183. }
  2184. this.value += step;
  2185. this.ensureLimits();
  2186. this.raiseOnChange();
  2187. };
  2188. PathCursor.prototype.ensureLimits = function () {
  2189. while (this.value > 1) {
  2190. this.value -= 1;
  2191. }
  2192. while (this.value < 0) {
  2193. this.value += 1;
  2194. }
  2195. };
  2196. // used by animation engine
  2197. PathCursor.prototype.markAsDirty = function (propertyName) {
  2198. this.ensureLimits();
  2199. this.raiseOnChange();
  2200. };
  2201. PathCursor.prototype.raiseOnChange = function () {
  2202. var _this = this;
  2203. this._onchange.forEach(function (f) { return f(_this); });
  2204. };
  2205. PathCursor.prototype.onchange = function (f) {
  2206. this._onchange.push(f);
  2207. };
  2208. return PathCursor;
  2209. })();
  2210. BABYLON.PathCursor = PathCursor;
  2211. var Path2 = (function () {
  2212. function Path2(x, y) {
  2213. this._points = [];
  2214. this._length = 0;
  2215. this.closed = false;
  2216. this._points.push(new Vector2(x, y));
  2217. }
  2218. Path2.prototype.addLineTo = function (x, y) {
  2219. if (closed) {
  2220. BABYLON.Tools.Error("cannot add lines to closed paths");
  2221. return this;
  2222. }
  2223. var newPoint = new Vector2(x, y);
  2224. var previousPoint = this._points[this._points.length - 1];
  2225. this._points.push(newPoint);
  2226. this._length += newPoint.subtract(previousPoint).length();
  2227. return this;
  2228. };
  2229. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2230. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2231. if (closed) {
  2232. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2233. return this;
  2234. }
  2235. var startPoint = this._points[this._points.length - 1];
  2236. var midPoint = new Vector2(midX, midY);
  2237. var endPoint = new Vector2(endX, endY);
  2238. var arc = new Arc2(startPoint, midPoint, endPoint);
  2239. var increment = arc.angle.radians() / numberOfSegments;
  2240. if (arc.orientation === 0 /* CW */)
  2241. increment *= -1;
  2242. var currentAngle = arc.startAngle.radians() + increment;
  2243. for (var i = 0; i < numberOfSegments; i++) {
  2244. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2245. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2246. this.addLineTo(x, y);
  2247. currentAngle += increment;
  2248. }
  2249. return this;
  2250. };
  2251. Path2.prototype.close = function () {
  2252. this.closed = true;
  2253. return this;
  2254. };
  2255. Path2.prototype.length = function () {
  2256. var result = this._length;
  2257. if (!this.closed) {
  2258. var lastPoint = this._points[this._points.length - 1];
  2259. var firstPoint = this._points[0];
  2260. result += (firstPoint.subtract(lastPoint).length());
  2261. }
  2262. return result;
  2263. };
  2264. Path2.prototype.getPoints = function () {
  2265. return this._points;
  2266. };
  2267. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2268. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2269. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2270. return;
  2271. }
  2272. var lengthPosition = normalizedLengthPosition * this.length();
  2273. var previousOffset = 0;
  2274. for (var i = 0; i < this._points.length; i++) {
  2275. var j = (i + 1) % this._points.length;
  2276. var a = this._points[i];
  2277. var b = this._points[j];
  2278. var bToA = b.subtract(a);
  2279. var nextOffset = (bToA.length() + previousOffset);
  2280. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2281. var dir = bToA.normalize();
  2282. var localOffset = lengthPosition - previousOffset;
  2283. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2284. }
  2285. previousOffset = nextOffset;
  2286. }
  2287. BABYLON.Tools.Error("internal error");
  2288. };
  2289. Path2.StartingAt = function (x, y) {
  2290. return new Path2(x, y);
  2291. };
  2292. return Path2;
  2293. })();
  2294. BABYLON.Path2 = Path2;
  2295. })(BABYLON || (BABYLON = {}));
  2296. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2297. (function (BABYLON) {
  2298. // Screenshots
  2299. var screenshotCanvas;
  2300. var cloneValue = function (source, destinationObject) {
  2301. if (!source)
  2302. return null;
  2303. if (source instanceof BABYLON.Mesh) {
  2304. return null;
  2305. }
  2306. if (source instanceof BABYLON.SubMesh) {
  2307. return source.clone(destinationObject);
  2308. }
  2309. else if (source.clone) {
  2310. return source.clone();
  2311. }
  2312. return null;
  2313. };
  2314. var Tools = (function () {
  2315. function Tools() {
  2316. }
  2317. Tools.GetFilename = function (path) {
  2318. var index = path.lastIndexOf("/");
  2319. if (index < 0)
  2320. return path;
  2321. return path.substring(index + 1);
  2322. };
  2323. Tools.GetDOMTextContent = function (element) {
  2324. var result = "";
  2325. var child = element.firstChild;
  2326. while (child) {
  2327. if (child.nodeType == 3) {
  2328. result += child.textContent;
  2329. }
  2330. child = child.nextSibling;
  2331. }
  2332. return result;
  2333. };
  2334. Tools.ToDegrees = function (angle) {
  2335. return angle * 180 / Math.PI;
  2336. };
  2337. Tools.ToRadians = function (angle) {
  2338. return angle * Math.PI / 180;
  2339. };
  2340. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2341. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2342. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2343. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2344. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2345. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2346. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2347. }
  2348. return {
  2349. minimum: minimum,
  2350. maximum: maximum
  2351. };
  2352. };
  2353. Tools.ExtractMinAndMax = function (positions, start, count) {
  2354. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2355. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2356. for (var index = start; index < start + count; index++) {
  2357. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2358. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2359. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2360. }
  2361. return {
  2362. minimum: minimum,
  2363. maximum: maximum
  2364. };
  2365. };
  2366. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2367. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2368. return undefined;
  2369. return Array.isArray(obj) ? obj : [obj];
  2370. };
  2371. // Misc.
  2372. Tools.GetPointerPrefix = function () {
  2373. var eventPrefix = "pointer";
  2374. // Check if hand.js is referenced or if the browser natively supports pointer events
  2375. if (!navigator.pointerEnabled) {
  2376. eventPrefix = "mouse";
  2377. }
  2378. return eventPrefix;
  2379. };
  2380. Tools.QueueNewFrame = function (func) {
  2381. if (window.requestAnimationFrame)
  2382. window.requestAnimationFrame(func);
  2383. else if (window.msRequestAnimationFrame)
  2384. window.msRequestAnimationFrame(func);
  2385. else if (window.webkitRequestAnimationFrame)
  2386. window.webkitRequestAnimationFrame(func);
  2387. else if (window.mozRequestAnimationFrame)
  2388. window.mozRequestAnimationFrame(func);
  2389. else if (window.oRequestAnimationFrame)
  2390. window.oRequestAnimationFrame(func);
  2391. else {
  2392. window.setTimeout(func, 16);
  2393. }
  2394. };
  2395. Tools.RequestFullscreen = function (element) {
  2396. if (element.requestFullscreen)
  2397. element.requestFullscreen();
  2398. else if (element.msRequestFullscreen)
  2399. element.msRequestFullscreen();
  2400. else if (element.webkitRequestFullscreen)
  2401. element.webkitRequestFullscreen();
  2402. else if (element.mozRequestFullScreen)
  2403. element.mozRequestFullScreen();
  2404. };
  2405. Tools.ExitFullscreen = function () {
  2406. if (document.exitFullscreen) {
  2407. document.exitFullscreen();
  2408. }
  2409. else if (document.mozCancelFullScreen) {
  2410. document.mozCancelFullScreen();
  2411. }
  2412. else if (document.webkitCancelFullScreen) {
  2413. document.webkitCancelFullScreen();
  2414. }
  2415. else if (document.msCancelFullScreen) {
  2416. document.msCancelFullScreen();
  2417. }
  2418. };
  2419. // External files
  2420. Tools.CleanUrl = function (url) {
  2421. url = url.replace(/#/mg, "%23");
  2422. return url;
  2423. };
  2424. Tools.LoadImage = function (url, onload, onerror, database) {
  2425. url = Tools.CleanUrl(url);
  2426. var img = new Image();
  2427. if (url.substr(0, 5) != "data:")
  2428. img.crossOrigin = 'anonymous';
  2429. img.onload = function () {
  2430. onload(img);
  2431. };
  2432. img.onerror = function (err) {
  2433. onerror(img, err);
  2434. };
  2435. var noIndexedDB = function () {
  2436. img.src = url;
  2437. };
  2438. var loadFromIndexedDB = function () {
  2439. database.loadImageFromDB(url, img);
  2440. };
  2441. //ANY database to do!
  2442. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2443. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2444. }
  2445. else {
  2446. if (url.indexOf("file:") === -1) {
  2447. noIndexedDB();
  2448. }
  2449. else {
  2450. try {
  2451. var textureName = url.substring(5);
  2452. var blobURL;
  2453. try {
  2454. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2455. }
  2456. catch (ex) {
  2457. // Chrome doesn't support oneTimeOnly parameter
  2458. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2459. }
  2460. img.src = blobURL;
  2461. }
  2462. catch (e) {
  2463. Tools.Log("Error while trying to load texture: " + textureName);
  2464. img.src = null;
  2465. }
  2466. }
  2467. }
  2468. return img;
  2469. };
  2470. //ANY
  2471. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2472. url = Tools.CleanUrl(url);
  2473. var noIndexedDB = function () {
  2474. var request = new XMLHttpRequest();
  2475. var loadUrl = Tools.BaseUrl + url;
  2476. request.open('GET', loadUrl, true);
  2477. if (useArrayBuffer) {
  2478. request.responseType = "arraybuffer";
  2479. }
  2480. request.onprogress = progressCallBack;
  2481. request.onreadystatechange = function () {
  2482. if (request.readyState == 4) {
  2483. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2484. callback(!useArrayBuffer ? request.responseText : request.response);
  2485. }
  2486. else {
  2487. if (onError) {
  2488. onError();
  2489. }
  2490. else {
  2491. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2492. }
  2493. }
  2494. }
  2495. };
  2496. request.send(null);
  2497. };
  2498. var loadFromIndexedDB = function () {
  2499. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2500. };
  2501. if (url.indexOf("file:") !== -1) {
  2502. var fileName = url.substring(5);
  2503. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2504. }
  2505. else {
  2506. // Caching all files
  2507. if (database && database.enableSceneOffline) {
  2508. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2509. }
  2510. else {
  2511. noIndexedDB();
  2512. }
  2513. }
  2514. };
  2515. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2516. var reader = new FileReader();
  2517. reader.onload = function (e) {
  2518. callback(e.target.result);
  2519. };
  2520. reader.onprogress = progressCallback;
  2521. reader.readAsDataURL(fileToLoad);
  2522. };
  2523. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2524. var reader = new FileReader();
  2525. reader.onload = function (e) {
  2526. callback(e.target.result);
  2527. };
  2528. reader.onprogress = progressCallBack;
  2529. if (!useArrayBuffer) {
  2530. // Asynchronous read
  2531. reader.readAsText(fileToLoad);
  2532. }
  2533. else {
  2534. reader.readAsArrayBuffer(fileToLoad);
  2535. }
  2536. };
  2537. // Misc.
  2538. Tools.Clamp = function (value, min, max) {
  2539. if (min === void 0) { min = 0; }
  2540. if (max === void 0) { max = 1; }
  2541. return Math.min(max, Math.max(min, value));
  2542. };
  2543. // Returns -1 when value is a negative number and
  2544. // +1 when value is a positive number.
  2545. Tools.Sign = function (value) {
  2546. value = +value; // convert to a number
  2547. if (value === 0 || isNaN(value))
  2548. return value;
  2549. return value > 0 ? 1 : -1;
  2550. };
  2551. Tools.Format = function (value, decimals) {
  2552. if (decimals === void 0) { decimals = 2; }
  2553. return value.toFixed(decimals);
  2554. };
  2555. Tools.CheckExtends = function (v, min, max) {
  2556. if (v.x < min.x)
  2557. min.x = v.x;
  2558. if (v.y < min.y)
  2559. min.y = v.y;
  2560. if (v.z < min.z)
  2561. min.z = v.z;
  2562. if (v.x > max.x)
  2563. max.x = v.x;
  2564. if (v.y > max.y)
  2565. max.y = v.y;
  2566. if (v.z > max.z)
  2567. max.z = v.z;
  2568. };
  2569. Tools.WithinEpsilon = function (a, b, epsilon) {
  2570. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2571. var num = a - b;
  2572. return -epsilon <= num && num <= epsilon;
  2573. };
  2574. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2575. for (var prop in source) {
  2576. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2577. continue;
  2578. }
  2579. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2580. continue;
  2581. }
  2582. var sourceValue = source[prop];
  2583. var typeOfSourceValue = typeof sourceValue;
  2584. if (typeOfSourceValue == "function") {
  2585. continue;
  2586. }
  2587. if (typeOfSourceValue == "object") {
  2588. if (sourceValue instanceof Array) {
  2589. destination[prop] = [];
  2590. if (sourceValue.length > 0) {
  2591. if (typeof sourceValue[0] == "object") {
  2592. for (var index = 0; index < sourceValue.length; index++) {
  2593. var clonedValue = cloneValue(sourceValue[index], destination);
  2594. if (destination[prop].indexOf(clonedValue) === -1) {
  2595. destination[prop].push(clonedValue);
  2596. }
  2597. }
  2598. }
  2599. else {
  2600. destination[prop] = sourceValue.slice(0);
  2601. }
  2602. }
  2603. }
  2604. else {
  2605. destination[prop] = cloneValue(sourceValue, destination);
  2606. }
  2607. }
  2608. else {
  2609. destination[prop] = sourceValue;
  2610. }
  2611. }
  2612. };
  2613. Tools.IsEmpty = function (obj) {
  2614. for (var i in obj) {
  2615. return false;
  2616. }
  2617. return true;
  2618. };
  2619. Tools.RegisterTopRootEvents = function (events) {
  2620. for (var index = 0; index < events.length; index++) {
  2621. var event = events[index];
  2622. window.addEventListener(event.name, event.handler, false);
  2623. try {
  2624. if (window.parent) {
  2625. window.parent.addEventListener(event.name, event.handler, false);
  2626. }
  2627. }
  2628. catch (e) {
  2629. }
  2630. }
  2631. };
  2632. Tools.UnregisterTopRootEvents = function (events) {
  2633. for (var index = 0; index < events.length; index++) {
  2634. var event = events[index];
  2635. window.removeEventListener(event.name, event.handler);
  2636. try {
  2637. if (window.parent) {
  2638. window.parent.removeEventListener(event.name, event.handler);
  2639. }
  2640. }
  2641. catch (e) {
  2642. }
  2643. }
  2644. };
  2645. Tools.CreateScreenshot = function (engine, camera, size) {
  2646. var width;
  2647. var height;
  2648. var scene = camera.getScene();
  2649. var previousCamera = null;
  2650. if (scene.activeCamera !== camera) {
  2651. previousCamera = scene.activeCamera;
  2652. scene.activeCamera = camera;
  2653. }
  2654. //If a precision value is specified
  2655. if (size.precision) {
  2656. width = Math.round(engine.getRenderWidth() * size.precision);
  2657. height = Math.round(width / engine.getAspectRatio(camera));
  2658. size = { width: width, height: height };
  2659. }
  2660. else if (size.width && size.height) {
  2661. width = size.width;
  2662. height = size.height;
  2663. }
  2664. else if (size.width && !size.height) {
  2665. width = size.width;
  2666. height = Math.round(width / engine.getAspectRatio(camera));
  2667. size = { width: width, height: height };
  2668. }
  2669. else if (size.height && !size.width) {
  2670. height = size.height;
  2671. width = Math.round(height * engine.getAspectRatio(camera));
  2672. size = { width: width, height: height };
  2673. }
  2674. else if (!isNaN(size)) {
  2675. height = size;
  2676. width = size;
  2677. }
  2678. else {
  2679. Tools.Error("Invalid 'size' parameter !");
  2680. return;
  2681. }
  2682. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2683. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2684. texture.renderList = scene.meshes;
  2685. texture.onAfterRender = function () {
  2686. // Read the contents of the framebuffer
  2687. var numberOfChannelsByLine = width * 4;
  2688. var halfHeight = height / 2;
  2689. //Reading datas from WebGL
  2690. var data = engine.readPixels(0, 0, width, height);
  2691. for (var i = 0; i < halfHeight; i++) {
  2692. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2693. var currentCell = j + i * numberOfChannelsByLine;
  2694. var targetLine = height - i - 1;
  2695. var targetCell = j + targetLine * numberOfChannelsByLine;
  2696. var temp = data[currentCell];
  2697. data[currentCell] = data[targetCell];
  2698. data[targetCell] = temp;
  2699. }
  2700. }
  2701. // Create a 2D canvas to store the result
  2702. if (!screenshotCanvas) {
  2703. screenshotCanvas = document.createElement('canvas');
  2704. }
  2705. screenshotCanvas.width = width;
  2706. screenshotCanvas.height = height;
  2707. var context = screenshotCanvas.getContext('2d');
  2708. // Copy the pixels to a 2D canvas
  2709. var imageData = context.createImageData(width, height);
  2710. imageData.data.set(data);
  2711. context.putImageData(imageData, 0, 0);
  2712. var base64Image = screenshotCanvas.toDataURL();
  2713. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2714. if (("download" in document.createElement("a"))) {
  2715. var a = window.document.createElement("a");
  2716. a.href = base64Image;
  2717. var date = new Date();
  2718. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2719. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2720. window.document.body.appendChild(a);
  2721. a.addEventListener("click", function () {
  2722. a.parentElement.removeChild(a);
  2723. });
  2724. a.click();
  2725. }
  2726. else {
  2727. var newWindow = window.open("");
  2728. var img = newWindow.document.createElement("img");
  2729. img.src = base64Image;
  2730. newWindow.document.body.appendChild(img);
  2731. }
  2732. };
  2733. scene.incrementRenderId();
  2734. texture.render(true);
  2735. texture.dispose();
  2736. if (previousCamera) {
  2737. scene.activeCamera = previousCamera;
  2738. }
  2739. };
  2740. // XHR response validator for local file scenario
  2741. Tools.ValidateXHRData = function (xhr, dataType) {
  2742. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2743. if (dataType === void 0) { dataType = 7; }
  2744. try {
  2745. if (dataType & 1) {
  2746. if (xhr.responseText && xhr.responseText.length > 0) {
  2747. return true;
  2748. }
  2749. else if (dataType === 1) {
  2750. return false;
  2751. }
  2752. }
  2753. if (dataType & 2) {
  2754. // Check header width and height since there is no "TGA" magic number
  2755. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2756. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2757. return true;
  2758. }
  2759. else if (dataType === 2) {
  2760. return false;
  2761. }
  2762. }
  2763. if (dataType & 4) {
  2764. // Check for the "DDS" magic number
  2765. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2766. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2767. return true;
  2768. }
  2769. else {
  2770. return false;
  2771. }
  2772. }
  2773. }
  2774. catch (e) {
  2775. }
  2776. return false;
  2777. };
  2778. Object.defineProperty(Tools, "NoneLogLevel", {
  2779. get: function () {
  2780. return Tools._NoneLogLevel;
  2781. },
  2782. enumerable: true,
  2783. configurable: true
  2784. });
  2785. Object.defineProperty(Tools, "MessageLogLevel", {
  2786. get: function () {
  2787. return Tools._MessageLogLevel;
  2788. },
  2789. enumerable: true,
  2790. configurable: true
  2791. });
  2792. Object.defineProperty(Tools, "WarningLogLevel", {
  2793. get: function () {
  2794. return Tools._WarningLogLevel;
  2795. },
  2796. enumerable: true,
  2797. configurable: true
  2798. });
  2799. Object.defineProperty(Tools, "ErrorLogLevel", {
  2800. get: function () {
  2801. return Tools._ErrorLogLevel;
  2802. },
  2803. enumerable: true,
  2804. configurable: true
  2805. });
  2806. Object.defineProperty(Tools, "AllLogLevel", {
  2807. get: function () {
  2808. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2809. },
  2810. enumerable: true,
  2811. configurable: true
  2812. });
  2813. Tools._AddLogEntry = function (entry) {
  2814. Tools._LogCache = entry + Tools._LogCache;
  2815. if (Tools.OnNewCacheEntry) {
  2816. Tools.OnNewCacheEntry(entry);
  2817. }
  2818. };
  2819. Tools._FormatMessage = function (message) {
  2820. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  2821. var date = new Date();
  2822. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2823. };
  2824. Tools._LogDisabled = function (message) {
  2825. // nothing to do
  2826. };
  2827. Tools._LogEnabled = function (message) {
  2828. var formattedMessage = Tools._FormatMessage(message);
  2829. console.log("BJS - " + formattedMessage);
  2830. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2831. Tools._AddLogEntry(entry);
  2832. };
  2833. Tools._WarnDisabled = function (message) {
  2834. // nothing to do
  2835. };
  2836. Tools._WarnEnabled = function (message) {
  2837. var formattedMessage = Tools._FormatMessage(message);
  2838. console.warn("BJS - " + formattedMessage);
  2839. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2840. Tools._AddLogEntry(entry);
  2841. };
  2842. Tools._ErrorDisabled = function (message) {
  2843. // nothing to do
  2844. };
  2845. Tools._ErrorEnabled = function (message) {
  2846. var formattedMessage = Tools._FormatMessage(message);
  2847. console.error("BJS - " + formattedMessage);
  2848. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2849. Tools._AddLogEntry(entry);
  2850. };
  2851. Object.defineProperty(Tools, "LogCache", {
  2852. get: function () {
  2853. return Tools._LogCache;
  2854. },
  2855. enumerable: true,
  2856. configurable: true
  2857. });
  2858. Object.defineProperty(Tools, "LogLevels", {
  2859. set: function (level) {
  2860. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2861. Tools.Log = Tools._LogEnabled;
  2862. }
  2863. else {
  2864. Tools.Log = Tools._LogDisabled;
  2865. }
  2866. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2867. Tools.Warn = Tools._WarnEnabled;
  2868. }
  2869. else {
  2870. Tools.Warn = Tools._WarnDisabled;
  2871. }
  2872. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2873. Tools.Error = Tools._ErrorEnabled;
  2874. }
  2875. else {
  2876. Tools.Error = Tools._ErrorDisabled;
  2877. }
  2878. },
  2879. enumerable: true,
  2880. configurable: true
  2881. });
  2882. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2883. get: function () {
  2884. return Tools._PerformanceNoneLogLevel;
  2885. },
  2886. enumerable: true,
  2887. configurable: true
  2888. });
  2889. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2890. get: function () {
  2891. return Tools._PerformanceUserMarkLogLevel;
  2892. },
  2893. enumerable: true,
  2894. configurable: true
  2895. });
  2896. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2897. get: function () {
  2898. return Tools._PerformanceConsoleLogLevel;
  2899. },
  2900. enumerable: true,
  2901. configurable: true
  2902. });
  2903. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2904. set: function (level) {
  2905. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2906. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2907. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2908. return;
  2909. }
  2910. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2911. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2912. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2913. return;
  2914. }
  2915. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2916. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2917. },
  2918. enumerable: true,
  2919. configurable: true
  2920. });
  2921. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2922. };
  2923. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2924. };
  2925. Tools._StartUserMark = function (counterName, condition) {
  2926. if (condition === void 0) { condition = true; }
  2927. if (!condition || !Tools._performance.mark) {
  2928. return;
  2929. }
  2930. Tools._performance.mark(counterName + "-Begin");
  2931. };
  2932. Tools._EndUserMark = function (counterName, condition) {
  2933. if (condition === void 0) { condition = true; }
  2934. if (!condition || !Tools._performance.mark) {
  2935. return;
  2936. }
  2937. Tools._performance.mark(counterName + "-End");
  2938. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2939. };
  2940. Tools._StartPerformanceConsole = function (counterName, condition) {
  2941. if (condition === void 0) { condition = true; }
  2942. if (!condition) {
  2943. return;
  2944. }
  2945. Tools._StartUserMark(counterName, condition);
  2946. if (console.time) {
  2947. console.time(counterName);
  2948. }
  2949. };
  2950. Tools._EndPerformanceConsole = function (counterName, condition) {
  2951. if (condition === void 0) { condition = true; }
  2952. if (!condition) {
  2953. return;
  2954. }
  2955. Tools._EndUserMark(counterName, condition);
  2956. if (console.time) {
  2957. console.timeEnd(counterName);
  2958. }
  2959. };
  2960. Object.defineProperty(Tools, "Now", {
  2961. get: function () {
  2962. if (window.performance && window.performance.now) {
  2963. return window.performance.now();
  2964. }
  2965. return new Date().getTime();
  2966. },
  2967. enumerable: true,
  2968. configurable: true
  2969. });
  2970. // Deprecated
  2971. Tools.GetFps = function () {
  2972. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  2973. return 0;
  2974. };
  2975. Tools.BaseUrl = "";
  2976. Tools.GetExponantOfTwo = function (value, max) {
  2977. var count = 1;
  2978. do {
  2979. count *= 2;
  2980. } while (count < value);
  2981. if (count > max)
  2982. count = max;
  2983. return count;
  2984. };
  2985. // Logs
  2986. Tools._NoneLogLevel = 0;
  2987. Tools._MessageLogLevel = 1;
  2988. Tools._WarningLogLevel = 2;
  2989. Tools._ErrorLogLevel = 4;
  2990. Tools._LogCache = "";
  2991. Tools.Log = Tools._LogEnabled;
  2992. Tools.Warn = Tools._WarnEnabled;
  2993. Tools.Error = Tools._ErrorEnabled;
  2994. // Performances
  2995. Tools._PerformanceNoneLogLevel = 0;
  2996. Tools._PerformanceUserMarkLogLevel = 1;
  2997. Tools._PerformanceConsoleLogLevel = 2;
  2998. Tools._performance = window.performance;
  2999. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3000. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3001. return Tools;
  3002. })();
  3003. BABYLON.Tools = Tools;
  3004. /**
  3005. * An implementation of a loop for asynchronous functions.
  3006. */
  3007. var AsyncLoop = (function () {
  3008. /**
  3009. * Constroctor.
  3010. * @param iterations the number of iterations.
  3011. * @param _fn the function to run each iteration
  3012. * @param _successCallback the callback that will be called upon succesful execution
  3013. * @param offset starting offset.
  3014. */
  3015. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3016. if (offset === void 0) { offset = 0; }
  3017. this.iterations = iterations;
  3018. this._fn = _fn;
  3019. this._successCallback = _successCallback;
  3020. this.index = offset - 1;
  3021. this._done = false;
  3022. }
  3023. /**
  3024. * Execute the next iteration. Must be called after the last iteration was finished.
  3025. */
  3026. AsyncLoop.prototype.executeNext = function () {
  3027. if (!this._done) {
  3028. if (this.index + 1 < this.iterations) {
  3029. ++this.index;
  3030. this._fn(this);
  3031. }
  3032. else {
  3033. this.breakLoop();
  3034. }
  3035. }
  3036. };
  3037. /**
  3038. * Break the loop and run the success callback.
  3039. */
  3040. AsyncLoop.prototype.breakLoop = function () {
  3041. this._done = true;
  3042. this._successCallback();
  3043. };
  3044. /**
  3045. * Helper function
  3046. */
  3047. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3048. if (offset === void 0) { offset = 0; }
  3049. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3050. loop.executeNext();
  3051. return loop;
  3052. };
  3053. /**
  3054. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3055. * @param iterations total number of iterations
  3056. * @param syncedIterations number of synchronous iterations in each async iteration.
  3057. * @param fn the function to call each iteration.
  3058. * @param callback a success call back that will be called when iterating stops.
  3059. * @param breakFunction a break condition (optional)
  3060. * @param timeout timeout settings for the setTimeout function. default - 0.
  3061. * @constructor
  3062. */
  3063. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3064. if (timeout === void 0) { timeout = 0; }
  3065. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3066. if (breakFunction && breakFunction())
  3067. loop.breakLoop();
  3068. else {
  3069. setTimeout(function () {
  3070. for (var i = 0; i < syncedIterations; ++i) {
  3071. var iteration = (loop.index * syncedIterations) + i;
  3072. if (iteration >= iterations)
  3073. break;
  3074. fn(iteration);
  3075. if (breakFunction && breakFunction()) {
  3076. loop.breakLoop();
  3077. break;
  3078. }
  3079. }
  3080. loop.executeNext();
  3081. }, timeout);
  3082. }
  3083. }, callback);
  3084. };
  3085. return AsyncLoop;
  3086. })();
  3087. BABYLON.AsyncLoop = AsyncLoop;
  3088. })(BABYLON || (BABYLON = {}));
  3089. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3090. (function (BABYLON) {
  3091. var _DepthCullingState = (function () {
  3092. function _DepthCullingState() {
  3093. this._isDepthTestDirty = false;
  3094. this._isDepthMaskDirty = false;
  3095. this._isDepthFuncDirty = false;
  3096. this._isCullFaceDirty = false;
  3097. this._isCullDirty = false;
  3098. }
  3099. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3100. get: function () {
  3101. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3102. },
  3103. enumerable: true,
  3104. configurable: true
  3105. });
  3106. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3107. get: function () {
  3108. return this._cullFace;
  3109. },
  3110. set: function (value) {
  3111. if (this._cullFace === value) {
  3112. return;
  3113. }
  3114. this._cullFace = value;
  3115. this._isCullFaceDirty = true;
  3116. },
  3117. enumerable: true,
  3118. configurable: true
  3119. });
  3120. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3121. get: function () {
  3122. return this._cull;
  3123. },
  3124. set: function (value) {
  3125. if (this._cull === value) {
  3126. return;
  3127. }
  3128. this._cull = value;
  3129. this._isCullDirty = true;
  3130. },
  3131. enumerable: true,
  3132. configurable: true
  3133. });
  3134. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3135. get: function () {
  3136. return this._depthFunc;
  3137. },
  3138. set: function (value) {
  3139. if (this._depthFunc === value) {
  3140. return;
  3141. }
  3142. this._depthFunc = value;
  3143. this._isDepthFuncDirty = true;
  3144. },
  3145. enumerable: true,
  3146. configurable: true
  3147. });
  3148. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3149. get: function () {
  3150. return this._depthMask;
  3151. },
  3152. set: function (value) {
  3153. if (this._depthMask === value) {
  3154. return;
  3155. }
  3156. this._depthMask = value;
  3157. this._isDepthMaskDirty = true;
  3158. },
  3159. enumerable: true,
  3160. configurable: true
  3161. });
  3162. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3163. get: function () {
  3164. return this._depthTest;
  3165. },
  3166. set: function (value) {
  3167. if (this._depthTest === value) {
  3168. return;
  3169. }
  3170. this._depthTest = value;
  3171. this._isDepthTestDirty = true;
  3172. },
  3173. enumerable: true,
  3174. configurable: true
  3175. });
  3176. _DepthCullingState.prototype.reset = function () {
  3177. this._depthMask = true;
  3178. this._depthTest = true;
  3179. this._depthFunc = null;
  3180. this._cull = null;
  3181. this._cullFace = null;
  3182. this._isDepthTestDirty = true;
  3183. this._isDepthMaskDirty = true;
  3184. this._isDepthFuncDirty = false;
  3185. this._isCullFaceDirty = false;
  3186. this._isCullDirty = false;
  3187. };
  3188. _DepthCullingState.prototype.apply = function (gl) {
  3189. if (!this.isDirty) {
  3190. return;
  3191. }
  3192. // Cull
  3193. if (this._isCullDirty) {
  3194. if (this.cull) {
  3195. gl.enable(gl.CULL_FACE);
  3196. }
  3197. else {
  3198. gl.disable(gl.CULL_FACE);
  3199. }
  3200. this._isCullDirty = false;
  3201. }
  3202. // Cull face
  3203. if (this._isCullFaceDirty) {
  3204. gl.cullFace(this.cullFace);
  3205. this._isCullFaceDirty = false;
  3206. }
  3207. // Depth mask
  3208. if (this._isDepthMaskDirty) {
  3209. gl.depthMask(this.depthMask);
  3210. this._isDepthMaskDirty = false;
  3211. }
  3212. // Depth test
  3213. if (this._isDepthTestDirty) {
  3214. if (this.depthTest) {
  3215. gl.enable(gl.DEPTH_TEST);
  3216. }
  3217. else {
  3218. gl.disable(gl.DEPTH_TEST);
  3219. }
  3220. this._isDepthTestDirty = false;
  3221. }
  3222. // Depth func
  3223. if (this._isDepthFuncDirty) {
  3224. gl.depthFunc(this.depthFunc);
  3225. this._isDepthFuncDirty = false;
  3226. }
  3227. };
  3228. return _DepthCullingState;
  3229. })();
  3230. BABYLON._DepthCullingState = _DepthCullingState;
  3231. var _AlphaState = (function () {
  3232. function _AlphaState() {
  3233. this._isAlphaBlendDirty = false;
  3234. this._isBlendFunctionParametersDirty = false;
  3235. this._alphaBlend = false;
  3236. this._blendFunctionParameters = new Array(4);
  3237. }
  3238. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3239. get: function () {
  3240. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3241. },
  3242. enumerable: true,
  3243. configurable: true
  3244. });
  3245. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3246. get: function () {
  3247. return this._alphaBlend;
  3248. },
  3249. set: function (value) {
  3250. if (this._alphaBlend === value) {
  3251. return;
  3252. }
  3253. this._alphaBlend = value;
  3254. this._isAlphaBlendDirty = true;
  3255. },
  3256. enumerable: true,
  3257. configurable: true
  3258. });
  3259. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3260. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3261. return;
  3262. }
  3263. this._blendFunctionParameters[0] = value0;
  3264. this._blendFunctionParameters[1] = value1;
  3265. this._blendFunctionParameters[2] = value2;
  3266. this._blendFunctionParameters[3] = value3;
  3267. this._isBlendFunctionParametersDirty = true;
  3268. };
  3269. _AlphaState.prototype.reset = function () {
  3270. this._alphaBlend = false;
  3271. this._blendFunctionParameters[0] = null;
  3272. this._blendFunctionParameters[1] = null;
  3273. this._blendFunctionParameters[2] = null;
  3274. this._blendFunctionParameters[3] = null;
  3275. this._isAlphaBlendDirty = true;
  3276. this._isBlendFunctionParametersDirty = false;
  3277. };
  3278. _AlphaState.prototype.apply = function (gl) {
  3279. if (!this.isDirty) {
  3280. return;
  3281. }
  3282. // Alpha blend
  3283. if (this._isAlphaBlendDirty) {
  3284. if (this._alphaBlend) {
  3285. gl.enable(gl.BLEND);
  3286. }
  3287. else {
  3288. gl.disable(gl.BLEND);
  3289. }
  3290. this._isAlphaBlendDirty = false;
  3291. }
  3292. // Alpha function
  3293. if (this._isBlendFunctionParametersDirty) {
  3294. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3295. this._isBlendFunctionParametersDirty = false;
  3296. }
  3297. };
  3298. return _AlphaState;
  3299. })();
  3300. BABYLON._AlphaState = _AlphaState;
  3301. var compileShader = function (gl, source, type, defines) {
  3302. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3303. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3304. gl.compileShader(shader);
  3305. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3306. throw new Error(gl.getShaderInfoLog(shader));
  3307. }
  3308. return shader;
  3309. };
  3310. var getWebGLTextureType = function (gl, type) {
  3311. var textureType = gl.UNSIGNED_BYTE;
  3312. if (type === Engine.TEXTURETYPE_FLOAT)
  3313. textureType = gl.FLOAT;
  3314. return textureType;
  3315. };
  3316. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3317. var magFilter = gl.NEAREST;
  3318. var minFilter = gl.NEAREST;
  3319. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3320. magFilter = gl.LINEAR;
  3321. if (generateMipMaps) {
  3322. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3323. }
  3324. else {
  3325. minFilter = gl.LINEAR;
  3326. }
  3327. }
  3328. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3329. magFilter = gl.LINEAR;
  3330. if (generateMipMaps) {
  3331. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3332. }
  3333. else {
  3334. minFilter = gl.LINEAR;
  3335. }
  3336. }
  3337. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3338. magFilter = gl.NEAREST;
  3339. if (generateMipMaps) {
  3340. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3341. }
  3342. else {
  3343. minFilter = gl.NEAREST;
  3344. }
  3345. }
  3346. return {
  3347. min: minFilter,
  3348. mag: magFilter
  3349. };
  3350. };
  3351. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3352. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3353. var engine = scene.getEngine();
  3354. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3355. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3356. gl.bindTexture(gl.TEXTURE_2D, texture);
  3357. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3358. processFunction(potWidth, potHeight);
  3359. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3360. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3361. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3362. if (!noMipmap && !isCompressed) {
  3363. gl.generateMipmap(gl.TEXTURE_2D);
  3364. }
  3365. gl.bindTexture(gl.TEXTURE_2D, null);
  3366. engine._activeTexturesCache = [];
  3367. texture._baseWidth = width;
  3368. texture._baseHeight = height;
  3369. texture._width = potWidth;
  3370. texture._height = potHeight;
  3371. texture.isReady = true;
  3372. texture.samplingMode = samplingMode;
  3373. scene._removePendingData(texture);
  3374. };
  3375. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3376. var onload = function () {
  3377. loadedImages[index] = img;
  3378. loadedImages._internalCount++;
  3379. scene._removePendingData(img);
  3380. if (loadedImages._internalCount === 6) {
  3381. onfinish(loadedImages);
  3382. }
  3383. };
  3384. var onerror = function () {
  3385. scene._removePendingData(img);
  3386. };
  3387. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3388. scene._addPendingData(img);
  3389. };
  3390. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3391. var loadedImages = [];
  3392. loadedImages._internalCount = 0;
  3393. for (var index = 0; index < 6; index++) {
  3394. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3395. }
  3396. };
  3397. var EngineCapabilities = (function () {
  3398. function EngineCapabilities() {
  3399. }
  3400. return EngineCapabilities;
  3401. })();
  3402. BABYLON.EngineCapabilities = EngineCapabilities;
  3403. /**
  3404. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3405. */
  3406. var Engine = (function () {
  3407. /**
  3408. * @constructor
  3409. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3410. * @param {boolean} [antialias] - enable antialias
  3411. * @param options - further options to be sent to the getContext function
  3412. */
  3413. function Engine(canvas, antialias, options) {
  3414. var _this = this;
  3415. // Public members
  3416. this.isFullscreen = false;
  3417. this.isPointerLock = false;
  3418. this.cullBackFaces = true;
  3419. this.renderEvenInBackground = true;
  3420. this.scenes = new Array();
  3421. this._windowIsBackground = false;
  3422. this._loadingDivBackgroundColor = "black";
  3423. this._drawCalls = 0;
  3424. this._renderingQueueLaunched = false;
  3425. this._activeRenderLoops = [];
  3426. // FPS
  3427. this.fpsRange = 60;
  3428. this.previousFramesDuration = [];
  3429. this.fps = 60;
  3430. this.deltaTime = 0;
  3431. // States
  3432. this._depthCullingState = new _DepthCullingState();
  3433. this._alphaState = new _AlphaState();
  3434. this._alphaMode = Engine.ALPHA_DISABLE;
  3435. // Cache
  3436. this._loadedTexturesCache = new Array();
  3437. this._activeTexturesCache = new Array();
  3438. this._compiledEffects = {};
  3439. this._uintIndicesCurrentlySet = false;
  3440. this._renderingCanvas = canvas;
  3441. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3442. options = options || {};
  3443. options.antialias = antialias;
  3444. try {
  3445. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3446. }
  3447. catch (e) {
  3448. throw new Error("WebGL not supported");
  3449. }
  3450. if (!this._gl) {
  3451. throw new Error("WebGL not supported");
  3452. }
  3453. this._onBlur = function () {
  3454. _this._windowIsBackground = true;
  3455. };
  3456. this._onFocus = function () {
  3457. _this._windowIsBackground = false;
  3458. };
  3459. window.addEventListener("blur", this._onBlur);
  3460. window.addEventListener("focus", this._onFocus);
  3461. // Textures
  3462. this._workingCanvas = document.createElement("canvas");
  3463. this._workingContext = this._workingCanvas.getContext("2d");
  3464. // Viewport
  3465. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3466. this.resize();
  3467. // Caps
  3468. this._caps = new EngineCapabilities();
  3469. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3470. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3471. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3472. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3473. // Infos
  3474. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3475. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3476. if (rendererInfo != null) {
  3477. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3478. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3479. }
  3480. if (!this._glVendor) {
  3481. this._glVendor = "Unknown vendor";
  3482. }
  3483. if (!this._glRenderer) {
  3484. this._glRenderer = "Unknown renderer";
  3485. }
  3486. // Extensions
  3487. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3488. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3489. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3490. 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');
  3491. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3492. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3493. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3494. // Depth buffer
  3495. this.setDepthBuffer(true);
  3496. this.setDepthFunctionToLessOrEqual();
  3497. this.setDepthWrite(true);
  3498. // Fullscreen
  3499. this._onFullscreenChange = function () {
  3500. if (document.fullscreen !== undefined) {
  3501. _this.isFullscreen = document.fullscreen;
  3502. }
  3503. else if (document.mozFullScreen !== undefined) {
  3504. _this.isFullscreen = document.mozFullScreen;
  3505. }
  3506. else if (document.webkitIsFullScreen !== undefined) {
  3507. _this.isFullscreen = document.webkitIsFullScreen;
  3508. }
  3509. else if (document.msIsFullScreen !== undefined) {
  3510. _this.isFullscreen = document.msIsFullScreen;
  3511. }
  3512. // Pointer lock
  3513. if (_this.isFullscreen && _this._pointerLockRequested) {
  3514. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3515. if (canvas.requestPointerLock) {
  3516. canvas.requestPointerLock();
  3517. }
  3518. }
  3519. };
  3520. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3521. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3522. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3523. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3524. // Pointer lock
  3525. this._onPointerLockChange = function () {
  3526. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3527. };
  3528. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3529. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3530. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3531. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3532. if (!Engine.audioEngine) {
  3533. Engine.audioEngine = new BABYLON.AudioEngine();
  3534. }
  3535. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3536. }
  3537. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3538. get: function () {
  3539. return Engine._ALPHA_DISABLE;
  3540. },
  3541. enumerable: true,
  3542. configurable: true
  3543. });
  3544. Object.defineProperty(Engine, "ALPHA_ADD", {
  3545. get: function () {
  3546. return Engine._ALPHA_ADD;
  3547. },
  3548. enumerable: true,
  3549. configurable: true
  3550. });
  3551. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3552. get: function () {
  3553. return Engine._ALPHA_COMBINE;
  3554. },
  3555. enumerable: true,
  3556. configurable: true
  3557. });
  3558. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3559. get: function () {
  3560. return Engine._DELAYLOADSTATE_NONE;
  3561. },
  3562. enumerable: true,
  3563. configurable: true
  3564. });
  3565. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3566. get: function () {
  3567. return Engine._DELAYLOADSTATE_LOADED;
  3568. },
  3569. enumerable: true,
  3570. configurable: true
  3571. });
  3572. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3573. get: function () {
  3574. return Engine._DELAYLOADSTATE_LOADING;
  3575. },
  3576. enumerable: true,
  3577. configurable: true
  3578. });
  3579. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3580. get: function () {
  3581. return Engine._DELAYLOADSTATE_NOTLOADED;
  3582. },
  3583. enumerable: true,
  3584. configurable: true
  3585. });
  3586. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3587. get: function () {
  3588. return Engine._TEXTUREFORMAT_ALPHA;
  3589. },
  3590. enumerable: true,
  3591. configurable: true
  3592. });
  3593. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3594. get: function () {
  3595. return Engine._TEXTUREFORMAT_LUMINANCE;
  3596. },
  3597. enumerable: true,
  3598. configurable: true
  3599. });
  3600. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3601. get: function () {
  3602. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3603. },
  3604. enumerable: true,
  3605. configurable: true
  3606. });
  3607. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3608. get: function () {
  3609. return Engine._TEXTUREFORMAT_RGB;
  3610. },
  3611. enumerable: true,
  3612. configurable: true
  3613. });
  3614. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3615. get: function () {
  3616. return Engine._TEXTUREFORMAT_RGBA;
  3617. },
  3618. enumerable: true,
  3619. configurable: true
  3620. });
  3621. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3622. get: function () {
  3623. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3624. },
  3625. enumerable: true,
  3626. configurable: true
  3627. });
  3628. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3629. get: function () {
  3630. return Engine._TEXTURETYPE_FLOAT;
  3631. },
  3632. enumerable: true,
  3633. configurable: true
  3634. });
  3635. Object.defineProperty(Engine, "Version", {
  3636. get: function () {
  3637. return "2.0.0";
  3638. },
  3639. enumerable: true,
  3640. configurable: true
  3641. });
  3642. Engine.prototype.getGlInfo = function () {
  3643. return {
  3644. vendor: this._glVendor,
  3645. renderer: this._glRenderer,
  3646. version: this._glVersion
  3647. };
  3648. };
  3649. Engine.prototype.getAspectRatio = function (camera) {
  3650. var viewport = camera.viewport;
  3651. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3652. };
  3653. Engine.prototype.getRenderWidth = function () {
  3654. if (this._currentRenderTarget) {
  3655. return this._currentRenderTarget._width;
  3656. }
  3657. return this._renderingCanvas.width;
  3658. };
  3659. Engine.prototype.getRenderHeight = function () {
  3660. if (this._currentRenderTarget) {
  3661. return this._currentRenderTarget._height;
  3662. }
  3663. return this._renderingCanvas.height;
  3664. };
  3665. Engine.prototype.getRenderingCanvas = function () {
  3666. return this._renderingCanvas;
  3667. };
  3668. Engine.prototype.getRenderingCanvasClientRect = function () {
  3669. return this._renderingCanvas.getBoundingClientRect();
  3670. };
  3671. Engine.prototype.setHardwareScalingLevel = function (level) {
  3672. this._hardwareScalingLevel = level;
  3673. this.resize();
  3674. };
  3675. Engine.prototype.getHardwareScalingLevel = function () {
  3676. return this._hardwareScalingLevel;
  3677. };
  3678. Engine.prototype.getLoadedTexturesCache = function () {
  3679. return this._loadedTexturesCache;
  3680. };
  3681. Engine.prototype.getCaps = function () {
  3682. return this._caps;
  3683. };
  3684. Object.defineProperty(Engine.prototype, "drawCalls", {
  3685. get: function () {
  3686. return this._drawCalls;
  3687. },
  3688. enumerable: true,
  3689. configurable: true
  3690. });
  3691. // Methods
  3692. Engine.prototype.resetDrawCalls = function () {
  3693. this._drawCalls = 0;
  3694. };
  3695. Engine.prototype.setDepthFunctionToGreater = function () {
  3696. this._depthCullingState.depthFunc = this._gl.GREATER;
  3697. };
  3698. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3699. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3700. };
  3701. Engine.prototype.setDepthFunctionToLess = function () {
  3702. this._depthCullingState.depthFunc = this._gl.LESS;
  3703. };
  3704. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3705. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3706. };
  3707. /**
  3708. * stop executing a render loop function and remove it from the execution array
  3709. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3710. */
  3711. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3712. if (!renderFunction) {
  3713. this._activeRenderLoops = [];
  3714. return;
  3715. }
  3716. var index = this._activeRenderLoops.indexOf(renderFunction);
  3717. if (index >= 0) {
  3718. this._activeRenderLoops.splice(index, 1);
  3719. }
  3720. };
  3721. Engine.prototype._renderLoop = function () {
  3722. var _this = this;
  3723. var shouldRender = true;
  3724. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3725. shouldRender = false;
  3726. }
  3727. if (shouldRender) {
  3728. // Start new frame
  3729. this.beginFrame();
  3730. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3731. var renderFunction = this._activeRenderLoops[index];
  3732. renderFunction();
  3733. }
  3734. // Present
  3735. this.endFrame();
  3736. }
  3737. if (this._activeRenderLoops.length > 0) {
  3738. // Register new frame
  3739. BABYLON.Tools.QueueNewFrame(function () {
  3740. _this._renderLoop();
  3741. });
  3742. }
  3743. else {
  3744. this._renderingQueueLaunched = false;
  3745. }
  3746. };
  3747. /**
  3748. * Register and execute a render loop. The engine can have more than one render function.
  3749. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  3750. * @example
  3751. * engine.runRenderLoop(function () {
  3752. * scene.render()
  3753. * })
  3754. */
  3755. Engine.prototype.runRenderLoop = function (renderFunction) {
  3756. var _this = this;
  3757. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3758. return;
  3759. }
  3760. this._activeRenderLoops.push(renderFunction);
  3761. if (!this._renderingQueueLaunched) {
  3762. this._renderingQueueLaunched = true;
  3763. BABYLON.Tools.QueueNewFrame(function () {
  3764. _this._renderLoop();
  3765. });
  3766. }
  3767. };
  3768. /**
  3769. * Toggle full screen mode.
  3770. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  3771. */
  3772. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3773. if (this.isFullscreen) {
  3774. BABYLON.Tools.ExitFullscreen();
  3775. }
  3776. else {
  3777. this._pointerLockRequested = requestPointerLock;
  3778. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3779. }
  3780. };
  3781. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3782. this.applyStates();
  3783. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3784. if (this._depthCullingState.depthMask) {
  3785. this._gl.clearDepth(1.0);
  3786. }
  3787. var mode = 0;
  3788. if (backBuffer)
  3789. mode |= this._gl.COLOR_BUFFER_BIT;
  3790. if (depthStencil && this._depthCullingState.depthMask)
  3791. mode |= this._gl.DEPTH_BUFFER_BIT;
  3792. this._gl.clear(mode);
  3793. };
  3794. /**
  3795. * Set the WebGL's viewport
  3796. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  3797. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  3798. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  3799. */
  3800. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3801. var width = requiredWidth || this._renderingCanvas.width;
  3802. var height = requiredHeight || this._renderingCanvas.height;
  3803. var x = viewport.x || 0;
  3804. var y = viewport.y || 0;
  3805. this._cachedViewport = viewport;
  3806. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3807. };
  3808. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3809. this._cachedViewport = null;
  3810. this._gl.viewport(x, y, width, height);
  3811. };
  3812. Engine.prototype.beginFrame = function () {
  3813. this._measureFps();
  3814. };
  3815. Engine.prototype.endFrame = function () {
  3816. this.flushFramebuffer();
  3817. };
  3818. /**
  3819. * resize the view according to the canvas' size.
  3820. * @example
  3821. * window.addEventListener("resize", function () {
  3822. * engine.resize();
  3823. * });
  3824. */
  3825. Engine.prototype.resize = function () {
  3826. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3827. };
  3828. /**
  3829. * force a specific size of the canvas
  3830. * @param {number} width - the new canvas' width
  3831. * @param {number} height - the new canvas' height
  3832. */
  3833. Engine.prototype.setSize = function (width, height) {
  3834. this._renderingCanvas.width = width;
  3835. this._renderingCanvas.height = height;
  3836. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3837. };
  3838. Engine.prototype.bindFramebuffer = function (texture) {
  3839. this._currentRenderTarget = texture;
  3840. var gl = this._gl;
  3841. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3842. this._gl.viewport(0, 0, texture._width, texture._height);
  3843. this.wipeCaches();
  3844. };
  3845. Engine.prototype.unBindFramebuffer = function (texture) {
  3846. this._currentRenderTarget = null;
  3847. if (texture.generateMipMaps) {
  3848. var gl = this._gl;
  3849. gl.bindTexture(gl.TEXTURE_2D, texture);
  3850. gl.generateMipmap(gl.TEXTURE_2D);
  3851. gl.bindTexture(gl.TEXTURE_2D, null);
  3852. }
  3853. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3854. };
  3855. Engine.prototype.flushFramebuffer = function () {
  3856. // this._gl.flush();
  3857. };
  3858. Engine.prototype.restoreDefaultFramebuffer = function () {
  3859. this._currentRenderTarget = null;
  3860. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3861. this.setViewport(this._cachedViewport);
  3862. this.wipeCaches();
  3863. };
  3864. // VBOs
  3865. Engine.prototype._resetVertexBufferBinding = function () {
  3866. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3867. this._cachedVertexBuffers = null;
  3868. };
  3869. Engine.prototype.createVertexBuffer = function (vertices) {
  3870. var vbo = this._gl.createBuffer();
  3871. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3872. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3873. this._resetVertexBufferBinding();
  3874. vbo.references = 1;
  3875. return vbo;
  3876. };
  3877. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3878. var vbo = this._gl.createBuffer();
  3879. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3880. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3881. this._resetVertexBufferBinding();
  3882. vbo.references = 1;
  3883. return vbo;
  3884. };
  3885. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3886. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3887. if (offset === undefined) {
  3888. offset = 0;
  3889. }
  3890. if (vertices instanceof Float32Array) {
  3891. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3892. }
  3893. else {
  3894. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3895. }
  3896. this._resetVertexBufferBinding();
  3897. };
  3898. Engine.prototype._resetIndexBufferBinding = function () {
  3899. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3900. this._cachedIndexBuffer = null;
  3901. };
  3902. Engine.prototype.createIndexBuffer = function (indices) {
  3903. var vbo = this._gl.createBuffer();
  3904. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3905. // Check for 32 bits indices
  3906. var arrayBuffer;
  3907. var need32Bits = false;
  3908. if (this._caps.uintIndices) {
  3909. for (var index = 0; index < indices.length; index++) {
  3910. if (indices[index] > 65535) {
  3911. need32Bits = true;
  3912. break;
  3913. }
  3914. }
  3915. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3916. }
  3917. else {
  3918. arrayBuffer = new Uint16Array(indices);
  3919. }
  3920. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3921. this._resetIndexBufferBinding();
  3922. vbo.references = 1;
  3923. vbo.is32Bits = need32Bits;
  3924. return vbo;
  3925. };
  3926. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3927. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3928. this._cachedVertexBuffers = vertexBuffer;
  3929. this._cachedEffectForVertexBuffers = effect;
  3930. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3931. var offset = 0;
  3932. for (var index = 0; index < vertexDeclaration.length; index++) {
  3933. var order = effect.getAttributeLocation(index);
  3934. if (order >= 0) {
  3935. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3936. }
  3937. offset += vertexDeclaration[index] * 4;
  3938. }
  3939. }
  3940. if (this._cachedIndexBuffer !== indexBuffer) {
  3941. this._cachedIndexBuffer = indexBuffer;
  3942. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3943. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3944. }
  3945. };
  3946. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3947. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3948. this._cachedVertexBuffers = vertexBuffers;
  3949. this._cachedEffectForVertexBuffers = effect;
  3950. var attributes = effect.getAttributesNames();
  3951. for (var index = 0; index < attributes.length; index++) {
  3952. var order = effect.getAttributeLocation(index);
  3953. if (order >= 0) {
  3954. var vertexBuffer = vertexBuffers[attributes[index]];
  3955. if (!vertexBuffer) {
  3956. continue;
  3957. }
  3958. var stride = vertexBuffer.getStrideSize();
  3959. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3960. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3961. }
  3962. }
  3963. }
  3964. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3965. this._cachedIndexBuffer = indexBuffer;
  3966. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3967. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3968. }
  3969. };
  3970. Engine.prototype._releaseBuffer = function (buffer) {
  3971. buffer.references--;
  3972. if (buffer.references === 0) {
  3973. this._gl.deleteBuffer(buffer);
  3974. return true;
  3975. }
  3976. return false;
  3977. };
  3978. Engine.prototype.createInstancesBuffer = function (capacity) {
  3979. var buffer = this._gl.createBuffer();
  3980. buffer.capacity = capacity;
  3981. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3982. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3983. return buffer;
  3984. };
  3985. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3986. this._gl.deleteBuffer(buffer);
  3987. };
  3988. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3989. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3990. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3991. for (var index = 0; index < 4; index++) {
  3992. var offsetLocation = offsetLocations[index];
  3993. this._gl.enableVertexAttribArray(offsetLocation);
  3994. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3995. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3996. }
  3997. };
  3998. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3999. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4000. for (var index = 0; index < 4; index++) {
  4001. var offsetLocation = offsetLocations[index];
  4002. this._gl.disableVertexAttribArray(offsetLocation);
  4003. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4004. }
  4005. };
  4006. Engine.prototype.applyStates = function () {
  4007. this._depthCullingState.apply(this._gl);
  4008. this._alphaState.apply(this._gl);
  4009. };
  4010. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4011. // Apply states
  4012. this.applyStates();
  4013. this._drawCalls++;
  4014. // Render
  4015. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4016. if (instancesCount) {
  4017. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4018. return;
  4019. }
  4020. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4021. };
  4022. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4023. // Apply states
  4024. this.applyStates();
  4025. this._drawCalls++;
  4026. if (instancesCount) {
  4027. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4028. return;
  4029. }
  4030. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4031. };
  4032. // Shaders
  4033. Engine.prototype._releaseEffect = function (effect) {
  4034. if (this._compiledEffects[effect._key]) {
  4035. delete this._compiledEffects[effect._key];
  4036. if (effect.getProgram()) {
  4037. this._gl.deleteProgram(effect.getProgram());
  4038. }
  4039. }
  4040. };
  4041. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4042. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4043. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4044. var name = vertex + "+" + fragment + "@" + defines;
  4045. if (this._compiledEffects[name]) {
  4046. return this._compiledEffects[name];
  4047. }
  4048. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4049. effect._key = name;
  4050. this._compiledEffects[name] = effect;
  4051. return effect;
  4052. };
  4053. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4054. if (uniformsNames === void 0) { uniformsNames = []; }
  4055. if (samplers === void 0) { samplers = []; }
  4056. if (defines === void 0) { defines = ""; }
  4057. return this.createEffect({
  4058. vertex: "particles",
  4059. fragmentElement: fragmentName
  4060. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4061. };
  4062. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4063. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4064. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4065. var shaderProgram = this._gl.createProgram();
  4066. this._gl.attachShader(shaderProgram, vertexShader);
  4067. this._gl.attachShader(shaderProgram, fragmentShader);
  4068. this._gl.linkProgram(shaderProgram);
  4069. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4070. if (!linked) {
  4071. var error = this._gl.getProgramInfoLog(shaderProgram);
  4072. if (error) {
  4073. throw new Error(error);
  4074. }
  4075. }
  4076. this._gl.deleteShader(vertexShader);
  4077. this._gl.deleteShader(fragmentShader);
  4078. return shaderProgram;
  4079. };
  4080. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4081. var results = [];
  4082. for (var index = 0; index < uniformsNames.length; index++) {
  4083. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4084. }
  4085. return results;
  4086. };
  4087. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4088. var results = [];
  4089. for (var index = 0; index < attributesNames.length; index++) {
  4090. try {
  4091. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4092. }
  4093. catch (e) {
  4094. results.push(-1);
  4095. }
  4096. }
  4097. return results;
  4098. };
  4099. Engine.prototype.enableEffect = function (effect) {
  4100. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4101. if (effect && effect.onBind) {
  4102. effect.onBind(effect);
  4103. }
  4104. return;
  4105. }
  4106. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4107. // Use program
  4108. this._gl.useProgram(effect.getProgram());
  4109. for (var i in this._vertexAttribArrays) {
  4110. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4111. continue;
  4112. }
  4113. this._vertexAttribArrays[i] = false;
  4114. this._gl.disableVertexAttribArray(i);
  4115. }
  4116. var attributesCount = effect.getAttributesCount();
  4117. for (var index = 0; index < attributesCount; index++) {
  4118. // Attributes
  4119. var order = effect.getAttributeLocation(index);
  4120. if (order >= 0) {
  4121. this._vertexAttribArrays[order] = true;
  4122. this._gl.enableVertexAttribArray(order);
  4123. }
  4124. }
  4125. this._currentEffect = effect;
  4126. if (effect.onBind) {
  4127. effect.onBind(effect);
  4128. }
  4129. };
  4130. Engine.prototype.setArray = function (uniform, array) {
  4131. if (!uniform)
  4132. return;
  4133. this._gl.uniform1fv(uniform, array);
  4134. };
  4135. Engine.prototype.setArray2 = function (uniform, array) {
  4136. if (!uniform || array.length % 2 !== 0)
  4137. return;
  4138. this._gl.uniform2fv(uniform, array);
  4139. };
  4140. Engine.prototype.setArray3 = function (uniform, array) {
  4141. if (!uniform || array.length % 3 !== 0)
  4142. return;
  4143. this._gl.uniform3fv(uniform, array);
  4144. };
  4145. Engine.prototype.setArray4 = function (uniform, array) {
  4146. if (!uniform || array.length % 4 !== 0)
  4147. return;
  4148. this._gl.uniform4fv(uniform, array);
  4149. };
  4150. Engine.prototype.setMatrices = function (uniform, matrices) {
  4151. if (!uniform)
  4152. return;
  4153. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4154. };
  4155. Engine.prototype.setMatrix = function (uniform, matrix) {
  4156. if (!uniform)
  4157. return;
  4158. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4159. };
  4160. Engine.prototype.setFloat = function (uniform, value) {
  4161. if (!uniform)
  4162. return;
  4163. this._gl.uniform1f(uniform, value);
  4164. };
  4165. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4166. if (!uniform)
  4167. return;
  4168. this._gl.uniform2f(uniform, x, y);
  4169. };
  4170. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4171. if (!uniform)
  4172. return;
  4173. this._gl.uniform3f(uniform, x, y, z);
  4174. };
  4175. Engine.prototype.setBool = function (uniform, bool) {
  4176. if (!uniform)
  4177. return;
  4178. this._gl.uniform1i(uniform, bool);
  4179. };
  4180. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4181. if (!uniform)
  4182. return;
  4183. this._gl.uniform4f(uniform, x, y, z, w);
  4184. };
  4185. Engine.prototype.setColor3 = function (uniform, color3) {
  4186. if (!uniform)
  4187. return;
  4188. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4189. };
  4190. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4191. if (!uniform)
  4192. return;
  4193. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4194. };
  4195. // States
  4196. Engine.prototype.setState = function (culling, force) {
  4197. // Culling
  4198. if (this._depthCullingState.cull !== culling || force) {
  4199. if (culling) {
  4200. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4201. this._depthCullingState.cull = true;
  4202. }
  4203. else {
  4204. this._depthCullingState.cull = false;
  4205. }
  4206. }
  4207. };
  4208. Engine.prototype.setDepthBuffer = function (enable) {
  4209. this._depthCullingState.depthTest = enable;
  4210. };
  4211. Engine.prototype.getDepthWrite = function () {
  4212. return this._depthCullingState.depthMask;
  4213. };
  4214. Engine.prototype.setDepthWrite = function (enable) {
  4215. this._depthCullingState.depthMask = enable;
  4216. };
  4217. Engine.prototype.setColorWrite = function (enable) {
  4218. this._gl.colorMask(enable, enable, enable, enable);
  4219. };
  4220. Engine.prototype.setAlphaMode = function (mode) {
  4221. switch (mode) {
  4222. case Engine.ALPHA_DISABLE:
  4223. this.setDepthWrite(true);
  4224. this._alphaState.alphaBlend = false;
  4225. break;
  4226. case Engine.ALPHA_COMBINE:
  4227. this.setDepthWrite(false);
  4228. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4229. this._alphaState.alphaBlend = true;
  4230. break;
  4231. case Engine.ALPHA_ADD:
  4232. this.setDepthWrite(false);
  4233. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4234. this._alphaState.alphaBlend = true;
  4235. break;
  4236. }
  4237. this._alphaMode = mode;
  4238. };
  4239. Engine.prototype.getAlphaMode = function () {
  4240. return this._alphaMode;
  4241. };
  4242. Engine.prototype.setAlphaTesting = function (enable) {
  4243. this._alphaTest = enable;
  4244. };
  4245. Engine.prototype.getAlphaTesting = function () {
  4246. return this._alphaTest;
  4247. };
  4248. // Textures
  4249. Engine.prototype.wipeCaches = function () {
  4250. this._activeTexturesCache = [];
  4251. this._currentEffect = null;
  4252. this._depthCullingState.reset();
  4253. this._alphaState.reset();
  4254. this._cachedVertexBuffers = null;
  4255. this._cachedIndexBuffer = null;
  4256. this._cachedEffectForVertexBuffers = null;
  4257. };
  4258. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4259. var gl = this._gl;
  4260. gl.bindTexture(gl.TEXTURE_2D, texture);
  4261. var magFilter = gl.NEAREST;
  4262. var minFilter = gl.NEAREST;
  4263. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4264. magFilter = gl.LINEAR;
  4265. minFilter = gl.LINEAR;
  4266. }
  4267. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4268. magFilter = gl.LINEAR;
  4269. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4270. }
  4271. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4272. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4273. gl.bindTexture(gl.TEXTURE_2D, null);
  4274. texture.samplingMode = samplingMode;
  4275. };
  4276. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4277. var _this = this;
  4278. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4279. if (onLoad === void 0) { onLoad = null; }
  4280. if (onError === void 0) { onError = null; }
  4281. if (buffer === void 0) { buffer = null; }
  4282. var texture = this._gl.createTexture();
  4283. var extension;
  4284. var fromData = false;
  4285. if (url.substr(0, 5) === "data:") {
  4286. fromData = true;
  4287. }
  4288. if (!fromData)
  4289. extension = url.substr(url.length - 4, 4).toLowerCase();
  4290. else {
  4291. var oldUrl = url;
  4292. fromData = oldUrl.split(':');
  4293. url = oldUrl;
  4294. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4295. }
  4296. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4297. var isTGA = (extension === ".tga");
  4298. scene._addPendingData(texture);
  4299. texture.url = url;
  4300. texture.noMipmap = noMipmap;
  4301. texture.references = 1;
  4302. this._loadedTexturesCache.push(texture);
  4303. var onerror = function () {
  4304. scene._removePendingData(texture);
  4305. if (onError) {
  4306. onError();
  4307. }
  4308. };
  4309. if (isTGA) {
  4310. var callback = function (arrayBuffer) {
  4311. var data = new Uint8Array(arrayBuffer);
  4312. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4313. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4314. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4315. if (onLoad) {
  4316. onLoad();
  4317. }
  4318. }, samplingMode);
  4319. };
  4320. if (!(fromData instanceof Array))
  4321. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4322. callback(arrayBuffer);
  4323. }, onerror, scene.database, true);
  4324. else
  4325. callback(buffer);
  4326. }
  4327. else if (isDDS) {
  4328. callback = function (data) {
  4329. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4330. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4331. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4332. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4333. if (onLoad) {
  4334. onLoad();
  4335. }
  4336. }, samplingMode);
  4337. };
  4338. if (!(fromData instanceof Array))
  4339. BABYLON.Tools.LoadFile(url, function (data) {
  4340. callback(data);
  4341. }, onerror, scene.database, true);
  4342. else
  4343. callback(buffer);
  4344. }
  4345. else {
  4346. var onload = function (img) {
  4347. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4348. var isPot = (img.width === potWidth && img.height === potHeight);
  4349. if (!isPot) {
  4350. _this._workingCanvas.width = potWidth;
  4351. _this._workingCanvas.height = potHeight;
  4352. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4353. _this._workingContext.imageSmoothingEnabled = false;
  4354. _this._workingContext.mozImageSmoothingEnabled = false;
  4355. _this._workingContext.oImageSmoothingEnabled = false;
  4356. _this._workingContext.webkitImageSmoothingEnabled = false;
  4357. _this._workingContext.msImageSmoothingEnabled = false;
  4358. }
  4359. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4360. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4361. _this._workingContext.imageSmoothingEnabled = true;
  4362. _this._workingContext.mozImageSmoothingEnabled = true;
  4363. _this._workingContext.oImageSmoothingEnabled = true;
  4364. _this._workingContext.webkitImageSmoothingEnabled = true;
  4365. _this._workingContext.msImageSmoothingEnabled = true;
  4366. }
  4367. }
  4368. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4369. if (onLoad) {
  4370. onLoad();
  4371. }
  4372. }, samplingMode);
  4373. };
  4374. if (!(fromData instanceof Array))
  4375. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4376. else
  4377. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4378. }
  4379. return texture;
  4380. };
  4381. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4382. var texture = this._gl.createTexture();
  4383. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4384. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4385. // Format
  4386. var internalFormat = this._gl.RGBA;
  4387. switch (format) {
  4388. case Engine.TEXTUREFORMAT_ALPHA:
  4389. internalFormat = this._gl.ALPHA;
  4390. break;
  4391. case Engine.TEXTUREFORMAT_LUMINANCE:
  4392. internalFormat = this._gl.LUMINANCE;
  4393. break;
  4394. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4395. internalFormat = this._gl.LUMINANCE_ALPHA;
  4396. break;
  4397. case Engine.TEXTUREFORMAT_RGB:
  4398. internalFormat = this._gl.RGB;
  4399. break;
  4400. case Engine.TEXTUREFORMAT_RGBA:
  4401. internalFormat = this._gl.RGBA;
  4402. break;
  4403. }
  4404. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4405. if (generateMipMaps) {
  4406. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4407. }
  4408. // Filters
  4409. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4410. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4411. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4412. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4413. this._activeTexturesCache = [];
  4414. texture._baseWidth = width;
  4415. texture._baseHeight = height;
  4416. texture._width = width;
  4417. texture._height = height;
  4418. texture.isReady = true;
  4419. texture.references = 1;
  4420. texture.samplingMode = samplingMode;
  4421. this._loadedTexturesCache.push(texture);
  4422. return texture;
  4423. };
  4424. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4425. var texture = this._gl.createTexture();
  4426. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4427. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4428. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4429. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4430. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4431. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4432. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4433. this._activeTexturesCache = [];
  4434. texture._baseWidth = width;
  4435. texture._baseHeight = height;
  4436. texture._width = width;
  4437. texture._height = height;
  4438. texture.isReady = false;
  4439. texture.generateMipMaps = generateMipMaps;
  4440. texture.references = 1;
  4441. texture.samplingMode = samplingMode;
  4442. this._loadedTexturesCache.push(texture);
  4443. return texture;
  4444. };
  4445. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4446. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4447. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4448. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4449. if (texture.generateMipMaps) {
  4450. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4451. }
  4452. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4453. this._activeTexturesCache = [];
  4454. texture.isReady = true;
  4455. };
  4456. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4457. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4458. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4459. // Scale the video if it is a NPOT using the current working canvas
  4460. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4461. if (!texture._workingCanvas) {
  4462. texture._workingCanvas = document.createElement("canvas");
  4463. texture._workingContext = texture._workingCanvas.getContext("2d");
  4464. texture._workingCanvas.width = texture._width;
  4465. texture._workingCanvas.height = texture._height;
  4466. }
  4467. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4468. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4469. }
  4470. else {
  4471. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4472. }
  4473. if (texture.generateMipMaps) {
  4474. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4475. }
  4476. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4477. this._activeTexturesCache = [];
  4478. texture.isReady = true;
  4479. };
  4480. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4481. // old version had a "generateMipMaps" arg instead of options.
  4482. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4483. // in the same way, generateDepthBuffer is defaulted to true
  4484. var generateMipMaps = false;
  4485. var generateDepthBuffer = true;
  4486. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4487. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4488. if (options !== undefined) {
  4489. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4490. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4491. type = options.type === undefined ? type : options.type;
  4492. if (options.samplingMode !== undefined) {
  4493. samplingMode = options.samplingMode;
  4494. }
  4495. if (type === Engine.TEXTURETYPE_FLOAT) {
  4496. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4497. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4498. }
  4499. }
  4500. var gl = this._gl;
  4501. var texture = gl.createTexture();
  4502. gl.bindTexture(gl.TEXTURE_2D, texture);
  4503. var width = size.width || size;
  4504. var height = size.height || size;
  4505. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4506. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4507. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4508. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4509. }
  4510. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4511. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4512. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4513. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4514. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4515. var depthBuffer;
  4516. // Create the depth buffer
  4517. if (generateDepthBuffer) {
  4518. depthBuffer = gl.createRenderbuffer();
  4519. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4520. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4521. }
  4522. // Create the framebuffer
  4523. var framebuffer = gl.createFramebuffer();
  4524. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4525. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4526. if (generateDepthBuffer) {
  4527. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4528. }
  4529. // Unbind
  4530. gl.bindTexture(gl.TEXTURE_2D, null);
  4531. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4532. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4533. texture._framebuffer = framebuffer;
  4534. if (generateDepthBuffer) {
  4535. texture._depthBuffer = depthBuffer;
  4536. }
  4537. texture._width = width;
  4538. texture._height = height;
  4539. texture.isReady = true;
  4540. texture.generateMipMaps = generateMipMaps;
  4541. texture.references = 1;
  4542. texture.samplingMode = samplingMode;
  4543. this._activeTexturesCache = [];
  4544. this._loadedTexturesCache.push(texture);
  4545. return texture;
  4546. };
  4547. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4548. var _this = this;
  4549. var gl = this._gl;
  4550. var texture = gl.createTexture();
  4551. texture.isCube = true;
  4552. texture.url = rootUrl;
  4553. texture.references = 1;
  4554. this._loadedTexturesCache.push(texture);
  4555. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4556. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4557. if (isDDS) {
  4558. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4559. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4560. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4561. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4562. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4563. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4564. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4565. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4566. }
  4567. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4568. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4569. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4570. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4571. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4572. _this._activeTexturesCache = [];
  4573. texture._width = info.width;
  4574. texture._height = info.height;
  4575. texture.isReady = true;
  4576. }, null, null, true);
  4577. }
  4578. else {
  4579. cascadeLoad(rootUrl, scene, function (imgs) {
  4580. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4581. var height = width;
  4582. _this._workingCanvas.width = width;
  4583. _this._workingCanvas.height = height;
  4584. var faces = [
  4585. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4586. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4587. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4588. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4589. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4590. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4591. ];
  4592. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4593. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4594. for (var index = 0; index < faces.length; index++) {
  4595. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4596. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4597. }
  4598. if (!noMipmap) {
  4599. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4600. }
  4601. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4602. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4603. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4604. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4605. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4606. _this._activeTexturesCache = [];
  4607. texture._width = width;
  4608. texture._height = height;
  4609. texture.isReady = true;
  4610. }, extensions);
  4611. }
  4612. return texture;
  4613. };
  4614. Engine.prototype._releaseTexture = function (texture) {
  4615. var gl = this._gl;
  4616. if (texture._framebuffer) {
  4617. gl.deleteFramebuffer(texture._framebuffer);
  4618. }
  4619. if (texture._depthBuffer) {
  4620. gl.deleteRenderbuffer(texture._depthBuffer);
  4621. }
  4622. gl.deleteTexture(texture);
  4623. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4624. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4625. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4626. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4627. this._activeTexturesCache[channel] = null;
  4628. }
  4629. var index = this._loadedTexturesCache.indexOf(texture);
  4630. if (index !== -1) {
  4631. this._loadedTexturesCache.splice(index, 1);
  4632. }
  4633. };
  4634. Engine.prototype.bindSamplers = function (effect) {
  4635. this._gl.useProgram(effect.getProgram());
  4636. var samplers = effect.getSamplers();
  4637. for (var index = 0; index < samplers.length; index++) {
  4638. var uniform = effect.getUniform(samplers[index]);
  4639. this._gl.uniform1i(uniform, index);
  4640. }
  4641. this._currentEffect = null;
  4642. };
  4643. Engine.prototype._bindTexture = function (channel, texture) {
  4644. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4645. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4646. this._activeTexturesCache[channel] = null;
  4647. };
  4648. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4649. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4650. };
  4651. Engine.prototype.setTexture = function (channel, texture) {
  4652. if (channel < 0) {
  4653. return;
  4654. }
  4655. // Not ready?
  4656. if (!texture || !texture.isReady()) {
  4657. if (this._activeTexturesCache[channel] != null) {
  4658. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4659. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4660. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4661. this._activeTexturesCache[channel] = null;
  4662. }
  4663. return;
  4664. }
  4665. // Video
  4666. if (texture instanceof BABYLON.VideoTexture) {
  4667. if (texture.update()) {
  4668. this._activeTexturesCache[channel] = null;
  4669. }
  4670. }
  4671. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4672. texture.delayLoad();
  4673. return;
  4674. }
  4675. if (this._activeTexturesCache[channel] === texture) {
  4676. return;
  4677. }
  4678. this._activeTexturesCache[channel] = texture;
  4679. var internalTexture = texture.getInternalTexture();
  4680. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4681. if (internalTexture.isCube) {
  4682. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4683. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4684. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4685. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4686. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4687. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4688. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4689. }
  4690. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4691. }
  4692. else {
  4693. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4694. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4695. internalTexture._cachedWrapU = texture.wrapU;
  4696. switch (texture.wrapU) {
  4697. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4698. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4699. break;
  4700. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4701. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4702. break;
  4703. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4704. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4705. break;
  4706. }
  4707. }
  4708. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4709. internalTexture._cachedWrapV = texture.wrapV;
  4710. switch (texture.wrapV) {
  4711. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4712. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4713. break;
  4714. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4715. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4716. break;
  4717. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4718. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4719. break;
  4720. }
  4721. }
  4722. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4723. }
  4724. };
  4725. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4726. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4727. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4728. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4729. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4730. }
  4731. };
  4732. Engine.prototype.readPixels = function (x, y, width, height) {
  4733. var data = new Uint8Array(height * width * 4);
  4734. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4735. return data;
  4736. };
  4737. // Dispose
  4738. Engine.prototype.dispose = function () {
  4739. this.hideLoadingUI();
  4740. this.stopRenderLoop();
  4741. while (this.scenes.length) {
  4742. this.scenes[0].dispose();
  4743. }
  4744. // Release audio engine
  4745. Engine.audioEngine.dispose();
  4746. for (var name in this._compiledEffects) {
  4747. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4748. }
  4749. for (var i in this._vertexAttribArrays) {
  4750. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4751. continue;
  4752. }
  4753. this._gl.disableVertexAttribArray(i);
  4754. }
  4755. // Events
  4756. window.removeEventListener("blur", this._onBlur);
  4757. window.removeEventListener("focus", this._onFocus);
  4758. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4759. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4760. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4761. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4762. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4763. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4764. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4765. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4766. };
  4767. // Loading screen
  4768. Engine.prototype.displayLoadingUI = function () {
  4769. var _this = this;
  4770. this._loadingDiv = document.createElement("div");
  4771. this._loadingDiv.style.opacity = "0";
  4772. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4773. // Loading text
  4774. this._loadingTextDiv = document.createElement("div");
  4775. this._loadingTextDiv.style.position = "absolute";
  4776. this._loadingTextDiv.style.left = "0";
  4777. this._loadingTextDiv.style.top = "50%";
  4778. this._loadingTextDiv.style.marginTop = "80px";
  4779. this._loadingTextDiv.style.width = "100%";
  4780. this._loadingTextDiv.style.height = "20px";
  4781. this._loadingTextDiv.style.fontFamily = "Arial";
  4782. this._loadingTextDiv.style.fontSize = "14px";
  4783. this._loadingTextDiv.style.color = "white";
  4784. this._loadingTextDiv.style.textAlign = "center";
  4785. this._loadingTextDiv.innerHTML = "Loading";
  4786. this._loadingDiv.appendChild(this._loadingTextDiv);
  4787. // Loading img
  4788. var imgBack = new Image();
  4789. 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==";
  4790. imgBack.style.position = "absolute";
  4791. imgBack.style.left = "50%";
  4792. imgBack.style.top = "50%";
  4793. imgBack.style.marginLeft = "-50px";
  4794. imgBack.style.marginTop = "-50px";
  4795. imgBack.style.transition = "transform 1.0s ease";
  4796. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4797. var deg = 360;
  4798. var onTransitionEnd = function () {
  4799. deg += 360;
  4800. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4801. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4802. };
  4803. imgBack.addEventListener("transitionend", onTransitionEnd);
  4804. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4805. this._loadingDiv.appendChild(imgBack);
  4806. // front image
  4807. var imgFront = new Image();
  4808. 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=";
  4809. imgFront.style.position = "absolute";
  4810. imgFront.style.left = "50%";
  4811. imgFront.style.top = "50%";
  4812. imgFront.style.marginLeft = "-50px";
  4813. imgFront.style.marginTop = "-50px";
  4814. this._loadingDiv.appendChild(imgFront);
  4815. // Resize
  4816. this._resizeLoadingUI = function () {
  4817. var canvasRect = _this.getRenderingCanvasClientRect();
  4818. _this._loadingDiv.style.position = "absolute";
  4819. _this._loadingDiv.style.left = canvasRect.left + "px";
  4820. _this._loadingDiv.style.top = canvasRect.top + "px";
  4821. _this._loadingDiv.style.width = canvasRect.width + "px";
  4822. _this._loadingDiv.style.height = canvasRect.height + "px";
  4823. };
  4824. this._resizeLoadingUI();
  4825. window.addEventListener("resize", this._resizeLoadingUI);
  4826. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4827. document.body.appendChild(this._loadingDiv);
  4828. setTimeout(function () {
  4829. _this._loadingDiv.style.opacity = "1";
  4830. imgBack.style.transform = "rotateZ(360deg)";
  4831. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4832. }, 0);
  4833. };
  4834. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4835. set: function (text) {
  4836. if (!this._loadingDiv) {
  4837. return;
  4838. }
  4839. this._loadingTextDiv.innerHTML = text;
  4840. },
  4841. enumerable: true,
  4842. configurable: true
  4843. });
  4844. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4845. get: function () {
  4846. return this._loadingDivBackgroundColor;
  4847. },
  4848. set: function (color) {
  4849. this._loadingDivBackgroundColor = color;
  4850. if (!this._loadingDiv) {
  4851. return;
  4852. }
  4853. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4854. },
  4855. enumerable: true,
  4856. configurable: true
  4857. });
  4858. Engine.prototype.hideLoadingUI = function () {
  4859. var _this = this;
  4860. if (!this._loadingDiv) {
  4861. return;
  4862. }
  4863. var onTransitionEnd = function () {
  4864. if (!_this._loadingDiv) {
  4865. return;
  4866. }
  4867. document.body.removeChild(_this._loadingDiv);
  4868. window.removeEventListener("resize", _this._resizeLoadingUI);
  4869. _this._loadingDiv = null;
  4870. };
  4871. this._loadingDiv.style.opacity = "0";
  4872. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4873. };
  4874. // FPS
  4875. Engine.prototype.getFps = function () {
  4876. return this.fps;
  4877. };
  4878. Engine.prototype.getDeltaTime = function () {
  4879. return this.deltaTime;
  4880. };
  4881. Engine.prototype._measureFps = function () {
  4882. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4883. var length = this.previousFramesDuration.length;
  4884. if (length >= 2) {
  4885. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4886. }
  4887. if (length >= this.fpsRange) {
  4888. if (length > this.fpsRange) {
  4889. this.previousFramesDuration.splice(0, 1);
  4890. length = this.previousFramesDuration.length;
  4891. }
  4892. var sum = 0;
  4893. for (var id = 0; id < length - 1; id++) {
  4894. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4895. }
  4896. this.fps = 1000.0 / (sum / (length - 1));
  4897. }
  4898. };
  4899. // Statics
  4900. Engine.isSupported = function () {
  4901. try {
  4902. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4903. if (navigator.isCocoonJS) {
  4904. return true;
  4905. }
  4906. var tempcanvas = document.createElement("canvas");
  4907. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4908. return gl != null && !!window.WebGLRenderingContext;
  4909. }
  4910. catch (e) {
  4911. return false;
  4912. }
  4913. };
  4914. // Const statics
  4915. Engine._ALPHA_DISABLE = 0;
  4916. Engine._ALPHA_ADD = 1;
  4917. Engine._ALPHA_COMBINE = 2;
  4918. Engine._DELAYLOADSTATE_NONE = 0;
  4919. Engine._DELAYLOADSTATE_LOADED = 1;
  4920. Engine._DELAYLOADSTATE_LOADING = 2;
  4921. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4922. Engine._TEXTUREFORMAT_ALPHA = 0;
  4923. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4924. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4925. Engine._TEXTUREFORMAT_RGB = 4;
  4926. Engine._TEXTUREFORMAT_RGBA = 4;
  4927. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  4928. Engine._TEXTURETYPE_FLOAT = 1;
  4929. // Updatable statics so stick with vars here
  4930. Engine.Epsilon = 0.001;
  4931. Engine.CollisionsEpsilon = 0.001;
  4932. Engine.ShadersRepository = "Babylon/Shaders/";
  4933. return Engine;
  4934. })();
  4935. BABYLON.Engine = Engine;
  4936. })(BABYLON || (BABYLON = {}));
  4937. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  4938. (function (BABYLON) {
  4939. /**
  4940. * Node is the basic class for all scene objects (Mesh, Light Camera).
  4941. */
  4942. var Node = (function () {
  4943. /**
  4944. * @constructor
  4945. * @param {string} name - the name and id to be given to this node
  4946. * @param {BABYLON.Scene} the scene this node will be added to
  4947. */
  4948. function Node(name, scene) {
  4949. this.state = "";
  4950. this.animations = new Array();
  4951. this._childrenFlag = -1;
  4952. this._isEnabled = true;
  4953. this._isReady = true;
  4954. this._currentRenderId = -1;
  4955. this.name = name;
  4956. this.id = name;
  4957. this._scene = scene;
  4958. this._initCache();
  4959. }
  4960. Node.prototype.getScene = function () {
  4961. return this._scene;
  4962. };
  4963. Node.prototype.getEngine = function () {
  4964. return this._scene.getEngine();
  4965. };
  4966. // override it in derived class
  4967. Node.prototype.getWorldMatrix = function () {
  4968. return BABYLON.Matrix.Identity();
  4969. };
  4970. // override it in derived class if you add new variables to the cache
  4971. // and call the parent class method
  4972. Node.prototype._initCache = function () {
  4973. this._cache = {};
  4974. this._cache.parent = undefined;
  4975. };
  4976. Node.prototype.updateCache = function (force) {
  4977. if (!force && this.isSynchronized())
  4978. return;
  4979. this._cache.parent = this.parent;
  4980. this._updateCache();
  4981. };
  4982. // override it in derived class if you add new variables to the cache
  4983. // and call the parent class method if !ignoreParentClass
  4984. Node.prototype._updateCache = function (ignoreParentClass) {
  4985. };
  4986. // override it in derived class if you add new variables to the cache
  4987. Node.prototype._isSynchronized = function () {
  4988. return true;
  4989. };
  4990. Node.prototype.isSynchronizedWithParent = function () {
  4991. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4992. };
  4993. Node.prototype.isSynchronized = function (updateCache) {
  4994. var check = this.hasNewParent();
  4995. check = check || !this.isSynchronizedWithParent();
  4996. check = check || !this._isSynchronized();
  4997. if (updateCache)
  4998. this.updateCache(true);
  4999. return !check;
  5000. };
  5001. Node.prototype.hasNewParent = function (update) {
  5002. if (this._cache.parent === this.parent)
  5003. return false;
  5004. if (update)
  5005. this._cache.parent = this.parent;
  5006. return true;
  5007. };
  5008. /**
  5009. * Is this node ready to be used/rendered
  5010. * @return {boolean} is it ready
  5011. */
  5012. Node.prototype.isReady = function () {
  5013. return this._isReady;
  5014. };
  5015. /**
  5016. * Is this node enabled.
  5017. * If the node has a parent and is enabled, the parent will be inspected as well.
  5018. * @return {boolean} whether this node (and its parent) is enabled.
  5019. * @see setEnabled
  5020. */
  5021. Node.prototype.isEnabled = function () {
  5022. if (!this._isEnabled) {
  5023. return false;
  5024. }
  5025. if (this.parent) {
  5026. return this.parent.isEnabled();
  5027. }
  5028. return true;
  5029. };
  5030. /**
  5031. * Set the enabled state of this node.
  5032. * @param {boolean} value - the new enabled state
  5033. * @see isEnabled
  5034. */
  5035. Node.prototype.setEnabled = function (value) {
  5036. this._isEnabled = value;
  5037. };
  5038. /**
  5039. * Is this node a descendant of the given node.
  5040. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5041. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5042. * @see parent
  5043. */
  5044. Node.prototype.isDescendantOf = function (ancestor) {
  5045. if (this.parent) {
  5046. if (this.parent === ancestor) {
  5047. return true;
  5048. }
  5049. return this.parent.isDescendantOf(ancestor);
  5050. }
  5051. return false;
  5052. };
  5053. Node.prototype._getDescendants = function (list, results) {
  5054. for (var index = 0; index < list.length; index++) {
  5055. var item = list[index];
  5056. if (item.isDescendantOf(this)) {
  5057. results.push(item);
  5058. }
  5059. }
  5060. };
  5061. /**
  5062. * Will return all nodes that have this node as parent.
  5063. * @return {BABYLON.Node[]} all children nodes of all types.
  5064. */
  5065. Node.prototype.getDescendants = function () {
  5066. var results = [];
  5067. this._getDescendants(this._scene.meshes, results);
  5068. this._getDescendants(this._scene.lights, results);
  5069. this._getDescendants(this._scene.cameras, results);
  5070. return results;
  5071. };
  5072. Node.prototype._setReady = function (state) {
  5073. if (state == this._isReady) {
  5074. return;
  5075. }
  5076. if (!state) {
  5077. this._isReady = false;
  5078. return;
  5079. }
  5080. this._isReady = true;
  5081. if (this.onReady) {
  5082. this.onReady(this);
  5083. }
  5084. };
  5085. return Node;
  5086. })();
  5087. BABYLON.Node = Node;
  5088. })(BABYLON || (BABYLON = {}));
  5089. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5090. (function (BABYLON) {
  5091. var BoundingSphere = (function () {
  5092. function BoundingSphere(minimum, maximum) {
  5093. this.minimum = minimum;
  5094. this.maximum = maximum;
  5095. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5096. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5097. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5098. this.radius = distance * 0.5;
  5099. this.centerWorld = BABYLON.Vector3.Zero();
  5100. this._update(BABYLON.Matrix.Identity());
  5101. }
  5102. // Methods
  5103. BoundingSphere.prototype._update = function (world) {
  5104. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5105. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5106. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5107. };
  5108. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5109. for (var i = 0; i < 6; i++) {
  5110. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5111. return false;
  5112. }
  5113. return true;
  5114. };
  5115. BoundingSphere.prototype.intersectsPoint = function (point) {
  5116. var x = this.centerWorld.x - point.x;
  5117. var y = this.centerWorld.y - point.y;
  5118. var z = this.centerWorld.z - point.z;
  5119. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5120. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5121. return false;
  5122. return true;
  5123. };
  5124. // Statics
  5125. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5126. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5127. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5128. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5129. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5130. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5131. return false;
  5132. return true;
  5133. };
  5134. return BoundingSphere;
  5135. })();
  5136. BABYLON.BoundingSphere = BoundingSphere;
  5137. })(BABYLON || (BABYLON = {}));
  5138. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5139. (function (BABYLON) {
  5140. var BoundingBox = (function () {
  5141. function BoundingBox(minimum, maximum) {
  5142. this.minimum = minimum;
  5143. this.maximum = maximum;
  5144. this.vectors = new Array();
  5145. this.vectorsWorld = new Array();
  5146. // Bounding vectors
  5147. this.vectors.push(this.minimum.clone());
  5148. this.vectors.push(this.maximum.clone());
  5149. this.vectors.push(this.minimum.clone());
  5150. this.vectors[2].x = this.maximum.x;
  5151. this.vectors.push(this.minimum.clone());
  5152. this.vectors[3].y = this.maximum.y;
  5153. this.vectors.push(this.minimum.clone());
  5154. this.vectors[4].z = this.maximum.z;
  5155. this.vectors.push(this.maximum.clone());
  5156. this.vectors[5].z = this.minimum.z;
  5157. this.vectors.push(this.maximum.clone());
  5158. this.vectors[6].x = this.minimum.x;
  5159. this.vectors.push(this.maximum.clone());
  5160. this.vectors[7].y = this.minimum.y;
  5161. // OBB
  5162. this.center = this.maximum.add(this.minimum).scale(0.5);
  5163. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5164. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5165. for (var index = 0; index < this.vectors.length; index++) {
  5166. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5167. }
  5168. this.minimumWorld = BABYLON.Vector3.Zero();
  5169. this.maximumWorld = BABYLON.Vector3.Zero();
  5170. this._update(BABYLON.Matrix.Identity());
  5171. }
  5172. // Methods
  5173. BoundingBox.prototype.getWorldMatrix = function () {
  5174. return this._worldMatrix;
  5175. };
  5176. BoundingBox.prototype._update = function (world) {
  5177. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5178. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5179. for (var index = 0; index < this.vectors.length; index++) {
  5180. var v = this.vectorsWorld[index];
  5181. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5182. if (v.x < this.minimumWorld.x)
  5183. this.minimumWorld.x = v.x;
  5184. if (v.y < this.minimumWorld.y)
  5185. this.minimumWorld.y = v.y;
  5186. if (v.z < this.minimumWorld.z)
  5187. this.minimumWorld.z = v.z;
  5188. if (v.x > this.maximumWorld.x)
  5189. this.maximumWorld.x = v.x;
  5190. if (v.y > this.maximumWorld.y)
  5191. this.maximumWorld.y = v.y;
  5192. if (v.z > this.maximumWorld.z)
  5193. this.maximumWorld.z = v.z;
  5194. }
  5195. // OBB
  5196. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5197. this.center.scaleInPlace(0.5);
  5198. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5199. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5200. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5201. this._worldMatrix = world;
  5202. };
  5203. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5204. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5205. };
  5206. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5207. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5208. };
  5209. BoundingBox.prototype.intersectsPoint = function (point) {
  5210. var delta = BABYLON.Engine.Epsilon;
  5211. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5212. return false;
  5213. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5214. return false;
  5215. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5216. return false;
  5217. return true;
  5218. };
  5219. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5220. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5221. };
  5222. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5223. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5224. return false;
  5225. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5226. return false;
  5227. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5228. return false;
  5229. return true;
  5230. };
  5231. // Statics
  5232. BoundingBox.Intersects = function (box0, box1) {
  5233. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5234. return false;
  5235. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5236. return false;
  5237. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5238. return false;
  5239. return true;
  5240. };
  5241. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5242. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5243. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5244. return (num <= (sphereRadius * sphereRadius));
  5245. };
  5246. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5247. for (var p = 0; p < 6; p++) {
  5248. for (var i = 0; i < 8; i++) {
  5249. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5250. return false;
  5251. }
  5252. }
  5253. }
  5254. return true;
  5255. };
  5256. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5257. for (var p = 0; p < 6; p++) {
  5258. var inCount = 8;
  5259. for (var i = 0; i < 8; i++) {
  5260. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5261. --inCount;
  5262. }
  5263. else {
  5264. break;
  5265. }
  5266. }
  5267. if (inCount == 0)
  5268. return false;
  5269. }
  5270. return true;
  5271. };
  5272. return BoundingBox;
  5273. })();
  5274. BABYLON.BoundingBox = BoundingBox;
  5275. })(BABYLON || (BABYLON = {}));
  5276. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5277. (function (BABYLON) {
  5278. var computeBoxExtents = function (axis, box) {
  5279. var p = BABYLON.Vector3.Dot(box.center, axis);
  5280. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5281. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5282. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5283. var r = r0 + r1 + r2;
  5284. return {
  5285. min: p - r,
  5286. max: p + r
  5287. };
  5288. };
  5289. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5290. var axisOverlap = function (axis, box0, box1) {
  5291. var result0 = computeBoxExtents(axis, box0);
  5292. var result1 = computeBoxExtents(axis, box1);
  5293. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5294. };
  5295. var BoundingInfo = (function () {
  5296. function BoundingInfo(minimum, maximum) {
  5297. this.minimum = minimum;
  5298. this.maximum = maximum;
  5299. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5300. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5301. }
  5302. // Methods
  5303. BoundingInfo.prototype._update = function (world) {
  5304. this.boundingBox._update(world);
  5305. this.boundingSphere._update(world);
  5306. };
  5307. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5308. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5309. return false;
  5310. return this.boundingBox.isInFrustum(frustumPlanes);
  5311. };
  5312. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5313. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5314. };
  5315. BoundingInfo.prototype._checkCollision = function (collider) {
  5316. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5317. };
  5318. BoundingInfo.prototype.intersectsPoint = function (point) {
  5319. if (!this.boundingSphere.centerWorld) {
  5320. return false;
  5321. }
  5322. if (!this.boundingSphere.intersectsPoint(point)) {
  5323. return false;
  5324. }
  5325. if (!this.boundingBox.intersectsPoint(point)) {
  5326. return false;
  5327. }
  5328. return true;
  5329. };
  5330. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5331. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5332. return false;
  5333. }
  5334. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5335. return false;
  5336. }
  5337. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5338. return false;
  5339. }
  5340. if (!precise) {
  5341. return true;
  5342. }
  5343. var box0 = this.boundingBox;
  5344. var box1 = boundingInfo.boundingBox;
  5345. if (!axisOverlap(box0.directions[0], box0, box1))
  5346. return false;
  5347. if (!axisOverlap(box0.directions[1], box0, box1))
  5348. return false;
  5349. if (!axisOverlap(box0.directions[2], box0, box1))
  5350. return false;
  5351. if (!axisOverlap(box1.directions[0], box0, box1))
  5352. return false;
  5353. if (!axisOverlap(box1.directions[1], box0, box1))
  5354. return false;
  5355. if (!axisOverlap(box1.directions[2], box0, box1))
  5356. return false;
  5357. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5358. return false;
  5359. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5360. return false;
  5361. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5362. return false;
  5363. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5364. return false;
  5365. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5366. return false;
  5367. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5368. return false;
  5369. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5370. return false;
  5371. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5372. return false;
  5373. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5374. return false;
  5375. return true;
  5376. };
  5377. return BoundingInfo;
  5378. })();
  5379. BABYLON.BoundingInfo = BoundingInfo;
  5380. })(BABYLON || (BABYLON = {}));
  5381. //# sourceMappingURL=babylon.boundingInfo.js.map
  5382. var BABYLON;
  5383. (function (BABYLON) {
  5384. var Light = (function (_super) {
  5385. __extends(Light, _super);
  5386. function Light(name, scene) {
  5387. _super.call(this, name, scene);
  5388. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5389. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5390. this.intensity = 1.0;
  5391. this.range = Number.MAX_VALUE;
  5392. this.includedOnlyMeshes = new Array();
  5393. this.excludedMeshes = new Array();
  5394. this._excludedMeshesIds = new Array();
  5395. this._includedOnlyMeshesIds = new Array();
  5396. scene.lights.push(this);
  5397. }
  5398. Light.prototype.getShadowGenerator = function () {
  5399. return this._shadowGenerator;
  5400. };
  5401. Light.prototype.getAbsolutePosition = function () {
  5402. return BABYLON.Vector3.Zero();
  5403. };
  5404. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5405. };
  5406. Light.prototype._getWorldMatrix = function () {
  5407. return BABYLON.Matrix.Identity();
  5408. };
  5409. Light.prototype.canAffectMesh = function (mesh) {
  5410. if (!mesh) {
  5411. return true;
  5412. }
  5413. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5414. return false;
  5415. }
  5416. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5417. return false;
  5418. }
  5419. return true;
  5420. };
  5421. Light.prototype.getWorldMatrix = function () {
  5422. this._currentRenderId = this.getScene().getRenderId();
  5423. var worldMatrix = this._getWorldMatrix();
  5424. if (this.parent && this.parent.getWorldMatrix) {
  5425. if (!this._parentedWorldMatrix) {
  5426. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5427. }
  5428. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5429. return this._parentedWorldMatrix;
  5430. }
  5431. return worldMatrix;
  5432. };
  5433. Light.prototype.dispose = function () {
  5434. if (this._shadowGenerator) {
  5435. this._shadowGenerator.dispose();
  5436. this._shadowGenerator = null;
  5437. }
  5438. // Remove from scene
  5439. var index = this.getScene().lights.indexOf(this);
  5440. this.getScene().lights.splice(index, 1);
  5441. };
  5442. return Light;
  5443. })(BABYLON.Node);
  5444. BABYLON.Light = Light;
  5445. })(BABYLON || (BABYLON = {}));
  5446. //# sourceMappingURL=babylon.light.js.map
  5447. var BABYLON;
  5448. (function (BABYLON) {
  5449. var PointLight = (function (_super) {
  5450. __extends(PointLight, _super);
  5451. function PointLight(name, position, scene) {
  5452. _super.call(this, name, scene);
  5453. this.position = position;
  5454. }
  5455. PointLight.prototype.getAbsolutePosition = function () {
  5456. return this._transformedPosition ? this._transformedPosition : this.position;
  5457. };
  5458. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5459. if (this.parent && this.parent.getWorldMatrix) {
  5460. if (!this._transformedPosition) {
  5461. this._transformedPosition = BABYLON.Vector3.Zero();
  5462. }
  5463. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5464. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5465. return;
  5466. }
  5467. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5468. };
  5469. PointLight.prototype.getShadowGenerator = function () {
  5470. return null;
  5471. };
  5472. PointLight.prototype._getWorldMatrix = function () {
  5473. if (!this._worldMatrix) {
  5474. this._worldMatrix = BABYLON.Matrix.Identity();
  5475. }
  5476. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5477. return this._worldMatrix;
  5478. };
  5479. return PointLight;
  5480. })(BABYLON.Light);
  5481. BABYLON.PointLight = PointLight;
  5482. })(BABYLON || (BABYLON = {}));
  5483. //# sourceMappingURL=babylon.pointLight.js.map
  5484. var BABYLON;
  5485. (function (BABYLON) {
  5486. var SpotLight = (function (_super) {
  5487. __extends(SpotLight, _super);
  5488. function SpotLight(name, position, direction, angle, exponent, scene) {
  5489. _super.call(this, name, scene);
  5490. this.position = position;
  5491. this.direction = direction;
  5492. this.angle = angle;
  5493. this.exponent = exponent;
  5494. }
  5495. SpotLight.prototype.getAbsolutePosition = function () {
  5496. return this.transformedPosition ? this.transformedPosition : this.position;
  5497. };
  5498. SpotLight.prototype.setDirectionToTarget = function (target) {
  5499. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5500. return this.direction;
  5501. };
  5502. SpotLight.prototype.computeTransformedPosition = function () {
  5503. if (this.parent && this.parent.getWorldMatrix) {
  5504. if (!this.transformedPosition) {
  5505. this.transformedPosition = BABYLON.Vector3.Zero();
  5506. }
  5507. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5508. return true;
  5509. }
  5510. return false;
  5511. };
  5512. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5513. var normalizeDirection;
  5514. if (this.parent && this.parent.getWorldMatrix) {
  5515. if (!this._transformedDirection) {
  5516. this._transformedDirection = BABYLON.Vector3.Zero();
  5517. }
  5518. this.computeTransformedPosition();
  5519. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5520. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5521. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5522. }
  5523. else {
  5524. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5525. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5526. }
  5527. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5528. };
  5529. SpotLight.prototype._getWorldMatrix = function () {
  5530. if (!this._worldMatrix) {
  5531. this._worldMatrix = BABYLON.Matrix.Identity();
  5532. }
  5533. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5534. return this._worldMatrix;
  5535. };
  5536. return SpotLight;
  5537. })(BABYLON.Light);
  5538. BABYLON.SpotLight = SpotLight;
  5539. })(BABYLON || (BABYLON = {}));
  5540. //# sourceMappingURL=babylon.spotLight.js.map
  5541. var BABYLON;
  5542. (function (BABYLON) {
  5543. var DirectionalLight = (function (_super) {
  5544. __extends(DirectionalLight, _super);
  5545. function DirectionalLight(name, direction, scene) {
  5546. _super.call(this, name, scene);
  5547. this.direction = direction;
  5548. this.position = direction.scale(-1);
  5549. }
  5550. DirectionalLight.prototype.getAbsolutePosition = function () {
  5551. return this.transformedPosition ? this.transformedPosition : this.position;
  5552. };
  5553. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5554. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5555. return this.direction;
  5556. };
  5557. DirectionalLight.prototype.computeTransformedPosition = function () {
  5558. if (this.parent && this.parent.getWorldMatrix) {
  5559. if (!this.transformedPosition) {
  5560. this.transformedPosition = BABYLON.Vector3.Zero();
  5561. }
  5562. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5563. return true;
  5564. }
  5565. return false;
  5566. };
  5567. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5568. if (this.parent && this.parent.getWorldMatrix) {
  5569. if (!this._transformedDirection) {
  5570. this._transformedDirection = BABYLON.Vector3.Zero();
  5571. }
  5572. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5573. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5574. return;
  5575. }
  5576. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5577. };
  5578. DirectionalLight.prototype._getWorldMatrix = function () {
  5579. if (!this._worldMatrix) {
  5580. this._worldMatrix = BABYLON.Matrix.Identity();
  5581. }
  5582. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5583. return this._worldMatrix;
  5584. };
  5585. return DirectionalLight;
  5586. })(BABYLON.Light);
  5587. BABYLON.DirectionalLight = DirectionalLight;
  5588. })(BABYLON || (BABYLON = {}));
  5589. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5590. (function (BABYLON) {
  5591. var ShadowGenerator = (function () {
  5592. function ShadowGenerator(mapSize, light) {
  5593. var _this = this;
  5594. // Members
  5595. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5596. this._darkness = 0;
  5597. this._transparencyShadow = false;
  5598. this._viewMatrix = BABYLON.Matrix.Zero();
  5599. this._projectionMatrix = BABYLON.Matrix.Zero();
  5600. this._transformMatrix = BABYLON.Matrix.Zero();
  5601. this._worldViewProjection = BABYLON.Matrix.Zero();
  5602. this._light = light;
  5603. this._scene = light.getScene();
  5604. light._shadowGenerator = this;
  5605. // Render target
  5606. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5607. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5608. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5609. this._shadowMap.renderParticles = false;
  5610. // Custom render function
  5611. var renderSubMesh = function (subMesh) {
  5612. var mesh = subMesh.getRenderingMesh();
  5613. var scene = _this._scene;
  5614. var engine = scene.getEngine();
  5615. // Culling
  5616. engine.setState(subMesh.getMaterial().backFaceCulling);
  5617. // Managing instances
  5618. var batch = mesh._getInstancesRenderList(subMesh._id);
  5619. if (batch.mustReturn) {
  5620. return;
  5621. }
  5622. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5623. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5624. engine.enableEffect(_this._effect);
  5625. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5626. var material = subMesh.getMaterial();
  5627. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5628. // Alpha test
  5629. if (material && material.needAlphaTesting()) {
  5630. var alphaTexture = material.getAlphaTestTexture();
  5631. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5632. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5633. }
  5634. // Bones
  5635. if (mesh.useBones) {
  5636. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5637. }
  5638. // Draw
  5639. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  5640. }
  5641. else {
  5642. // Need to reset refresh rate of the shadowMap
  5643. _this._shadowMap.resetRefreshCounter();
  5644. }
  5645. };
  5646. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5647. var index;
  5648. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5649. renderSubMesh(opaqueSubMeshes.data[index]);
  5650. }
  5651. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5652. renderSubMesh(alphaTestSubMeshes.data[index]);
  5653. }
  5654. if (_this._transparencyShadow) {
  5655. for (index = 0; index < transparentSubMeshes.length; index++) {
  5656. renderSubMesh(transparentSubMeshes.data[index]);
  5657. }
  5658. }
  5659. };
  5660. }
  5661. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5662. // Static
  5663. get: function () {
  5664. return ShadowGenerator._FILTER_NONE;
  5665. },
  5666. enumerable: true,
  5667. configurable: true
  5668. });
  5669. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5670. get: function () {
  5671. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5672. },
  5673. enumerable: true,
  5674. configurable: true
  5675. });
  5676. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5677. get: function () {
  5678. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5679. },
  5680. enumerable: true,
  5681. configurable: true
  5682. });
  5683. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5684. get: function () {
  5685. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5686. },
  5687. set: function (value) {
  5688. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5689. },
  5690. enumerable: true,
  5691. configurable: true
  5692. });
  5693. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5694. get: function () {
  5695. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5696. },
  5697. set: function (value) {
  5698. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5699. },
  5700. enumerable: true,
  5701. configurable: true
  5702. });
  5703. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5704. var defines = [];
  5705. if (this.useVarianceShadowMap) {
  5706. defines.push("#define VSM");
  5707. }
  5708. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5709. var mesh = subMesh.getMesh();
  5710. var material = subMesh.getMaterial();
  5711. // Alpha test
  5712. if (material && material.needAlphaTesting()) {
  5713. defines.push("#define ALPHATEST");
  5714. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5715. attribs.push(BABYLON.VertexBuffer.UVKind);
  5716. defines.push("#define UV1");
  5717. }
  5718. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5719. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5720. defines.push("#define UV2");
  5721. }
  5722. }
  5723. // Bones
  5724. if (mesh.useBones) {
  5725. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5726. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5727. defines.push("#define BONES");
  5728. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5729. }
  5730. // Instances
  5731. if (useInstances) {
  5732. defines.push("#define INSTANCES");
  5733. attribs.push("world0");
  5734. attribs.push("world1");
  5735. attribs.push("world2");
  5736. attribs.push("world3");
  5737. }
  5738. // Get correct effect
  5739. var join = defines.join("\n");
  5740. if (this._cachedDefines !== join) {
  5741. this._cachedDefines = join;
  5742. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5743. }
  5744. return this._effect.isReady();
  5745. };
  5746. ShadowGenerator.prototype.getShadowMap = function () {
  5747. return this._shadowMap;
  5748. };
  5749. ShadowGenerator.prototype.getLight = function () {
  5750. return this._light;
  5751. };
  5752. // Methods
  5753. ShadowGenerator.prototype.getTransformMatrix = function () {
  5754. var lightPosition = this._light.position;
  5755. var lightDirection = this._light.direction;
  5756. if (this._light.computeTransformedPosition()) {
  5757. lightPosition = this._light.transformedPosition;
  5758. }
  5759. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5760. this._cachedPosition = lightPosition.clone();
  5761. this._cachedDirection = lightDirection.clone();
  5762. var activeCamera = this._scene.activeCamera;
  5763. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5764. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5765. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5766. }
  5767. return this._transformMatrix;
  5768. };
  5769. ShadowGenerator.prototype.getDarkness = function () {
  5770. return this._darkness;
  5771. };
  5772. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5773. if (darkness >= 1.0)
  5774. this._darkness = 1.0;
  5775. else if (darkness <= 0.0)
  5776. this._darkness = 0.0;
  5777. else
  5778. this._darkness = darkness;
  5779. };
  5780. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5781. this._transparencyShadow = hasShadow;
  5782. };
  5783. ShadowGenerator.prototype.dispose = function () {
  5784. this._shadowMap.dispose();
  5785. };
  5786. ShadowGenerator._FILTER_NONE = 0;
  5787. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5788. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5789. return ShadowGenerator;
  5790. })();
  5791. BABYLON.ShadowGenerator = ShadowGenerator;
  5792. })(BABYLON || (BABYLON = {}));
  5793. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5794. var BABYLON;
  5795. (function (BABYLON) {
  5796. var HemisphericLight = (function (_super) {
  5797. __extends(HemisphericLight, _super);
  5798. function HemisphericLight(name, direction, scene) {
  5799. _super.call(this, name, scene);
  5800. this.direction = direction;
  5801. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5802. }
  5803. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5804. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5805. return this.direction;
  5806. };
  5807. HemisphericLight.prototype.getShadowGenerator = function () {
  5808. return null;
  5809. };
  5810. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5811. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5812. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5813. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5814. };
  5815. HemisphericLight.prototype._getWorldMatrix = function () {
  5816. if (!this._worldMatrix) {
  5817. this._worldMatrix = BABYLON.Matrix.Identity();
  5818. }
  5819. return this._worldMatrix;
  5820. };
  5821. return HemisphericLight;
  5822. })(BABYLON.Light);
  5823. BABYLON.HemisphericLight = HemisphericLight;
  5824. })(BABYLON || (BABYLON = {}));
  5825. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  5826. (function (BABYLON) {
  5827. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5828. if (boxMin.x > sphereCenter.x + sphereRadius)
  5829. return false;
  5830. if (sphereCenter.x - sphereRadius > boxMax.x)
  5831. return false;
  5832. if (boxMin.y > sphereCenter.y + sphereRadius)
  5833. return false;
  5834. if (sphereCenter.y - sphereRadius > boxMax.y)
  5835. return false;
  5836. if (boxMin.z > sphereCenter.z + sphereRadius)
  5837. return false;
  5838. if (sphereCenter.z - sphereRadius > boxMax.z)
  5839. return false;
  5840. return true;
  5841. };
  5842. var getLowestRoot = function (a, b, c, maxR) {
  5843. var determinant = b * b - 4.0 * a * c;
  5844. var result = { root: 0, found: false };
  5845. if (determinant < 0)
  5846. return result;
  5847. var sqrtD = Math.sqrt(determinant);
  5848. var r1 = (-b - sqrtD) / (2.0 * a);
  5849. var r2 = (-b + sqrtD) / (2.0 * a);
  5850. if (r1 > r2) {
  5851. var temp = r2;
  5852. r2 = r1;
  5853. r1 = temp;
  5854. }
  5855. if (r1 > 0 && r1 < maxR) {
  5856. result.root = r1;
  5857. result.found = true;
  5858. return result;
  5859. }
  5860. if (r2 > 0 && r2 < maxR) {
  5861. result.root = r2;
  5862. result.found = true;
  5863. return result;
  5864. }
  5865. return result;
  5866. };
  5867. var Collider = (function () {
  5868. function Collider() {
  5869. this.radius = new BABYLON.Vector3(1, 1, 1);
  5870. this.retry = 0;
  5871. this.basePointWorld = BABYLON.Vector3.Zero();
  5872. this.velocityWorld = BABYLON.Vector3.Zero();
  5873. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5874. this._collisionPoint = BABYLON.Vector3.Zero();
  5875. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5876. this._tempVector = BABYLON.Vector3.Zero();
  5877. this._tempVector2 = BABYLON.Vector3.Zero();
  5878. this._tempVector3 = BABYLON.Vector3.Zero();
  5879. this._tempVector4 = BABYLON.Vector3.Zero();
  5880. this._edge = BABYLON.Vector3.Zero();
  5881. this._baseToVertex = BABYLON.Vector3.Zero();
  5882. this._destinationPoint = BABYLON.Vector3.Zero();
  5883. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5884. this._displacementVector = BABYLON.Vector3.Zero();
  5885. }
  5886. // Methods
  5887. Collider.prototype._initialize = function (source, dir, e) {
  5888. this.velocity = dir;
  5889. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5890. this.basePoint = source;
  5891. source.multiplyToRef(this.radius, this.basePointWorld);
  5892. dir.multiplyToRef(this.radius, this.velocityWorld);
  5893. this.velocityWorldLength = this.velocityWorld.length();
  5894. this.epsilon = e;
  5895. this.collisionFound = false;
  5896. };
  5897. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5898. pa.subtractToRef(point, this._tempVector);
  5899. pb.subtractToRef(point, this._tempVector2);
  5900. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5901. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5902. if (d < 0)
  5903. return false;
  5904. pc.subtractToRef(point, this._tempVector3);
  5905. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5906. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5907. if (d < 0)
  5908. return false;
  5909. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5910. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5911. return d >= 0;
  5912. };
  5913. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5914. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5915. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5916. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5917. return false;
  5918. }
  5919. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5920. return false;
  5921. return true;
  5922. };
  5923. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5924. var t0;
  5925. var embeddedInPlane = false;
  5926. if (!subMesh._trianglePlanes) {
  5927. subMesh._trianglePlanes = [];
  5928. }
  5929. if (!subMesh._trianglePlanes[faceIndex]) {
  5930. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5931. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5932. }
  5933. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5934. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5935. return;
  5936. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5937. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5938. if (normalDotVelocity == 0) {
  5939. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5940. return;
  5941. embeddedInPlane = true;
  5942. t0 = 0;
  5943. }
  5944. else {
  5945. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5946. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5947. if (t0 > t1) {
  5948. var temp = t1;
  5949. t1 = t0;
  5950. t0 = temp;
  5951. }
  5952. if (t0 > 1.0 || t1 < 0.0)
  5953. return;
  5954. if (t0 < 0)
  5955. t0 = 0;
  5956. if (t0 > 1.0)
  5957. t0 = 1.0;
  5958. }
  5959. this._collisionPoint.copyFromFloats(0, 0, 0);
  5960. var found = false;
  5961. var t = 1.0;
  5962. if (!embeddedInPlane) {
  5963. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5964. this.velocity.scaleToRef(t0, this._tempVector);
  5965. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5966. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5967. found = true;
  5968. t = t0;
  5969. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5970. }
  5971. }
  5972. if (!found) {
  5973. var velocitySquaredLength = this.velocity.lengthSquared();
  5974. var a = velocitySquaredLength;
  5975. this.basePoint.subtractToRef(p1, this._tempVector);
  5976. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5977. var c = this._tempVector.lengthSquared() - 1.0;
  5978. var lowestRoot = getLowestRoot(a, b, c, t);
  5979. if (lowestRoot.found) {
  5980. t = lowestRoot.root;
  5981. found = true;
  5982. this._collisionPoint.copyFrom(p1);
  5983. }
  5984. this.basePoint.subtractToRef(p2, this._tempVector);
  5985. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5986. c = this._tempVector.lengthSquared() - 1.0;
  5987. lowestRoot = getLowestRoot(a, b, c, t);
  5988. if (lowestRoot.found) {
  5989. t = lowestRoot.root;
  5990. found = true;
  5991. this._collisionPoint.copyFrom(p2);
  5992. }
  5993. this.basePoint.subtractToRef(p3, this._tempVector);
  5994. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5995. c = this._tempVector.lengthSquared() - 1.0;
  5996. lowestRoot = getLowestRoot(a, b, c, t);
  5997. if (lowestRoot.found) {
  5998. t = lowestRoot.root;
  5999. found = true;
  6000. this._collisionPoint.copyFrom(p3);
  6001. }
  6002. p2.subtractToRef(p1, this._edge);
  6003. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6004. var edgeSquaredLength = this._edge.lengthSquared();
  6005. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6006. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6007. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6008. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6009. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6010. lowestRoot = getLowestRoot(a, b, c, t);
  6011. if (lowestRoot.found) {
  6012. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6013. if (f >= 0.0 && f <= 1.0) {
  6014. t = lowestRoot.root;
  6015. found = true;
  6016. this._edge.scaleInPlace(f);
  6017. p1.addToRef(this._edge, this._collisionPoint);
  6018. }
  6019. }
  6020. p3.subtractToRef(p2, this._edge);
  6021. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6022. edgeSquaredLength = this._edge.lengthSquared();
  6023. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6024. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6025. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6026. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6027. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6028. lowestRoot = getLowestRoot(a, b, c, t);
  6029. if (lowestRoot.found) {
  6030. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6031. if (f >= 0.0 && f <= 1.0) {
  6032. t = lowestRoot.root;
  6033. found = true;
  6034. this._edge.scaleInPlace(f);
  6035. p2.addToRef(this._edge, this._collisionPoint);
  6036. }
  6037. }
  6038. p1.subtractToRef(p3, this._edge);
  6039. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6040. edgeSquaredLength = this._edge.lengthSquared();
  6041. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6042. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6043. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6044. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6045. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6046. lowestRoot = getLowestRoot(a, b, c, t);
  6047. if (lowestRoot.found) {
  6048. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6049. if (f >= 0.0 && f <= 1.0) {
  6050. t = lowestRoot.root;
  6051. found = true;
  6052. this._edge.scaleInPlace(f);
  6053. p3.addToRef(this._edge, this._collisionPoint);
  6054. }
  6055. }
  6056. }
  6057. if (found) {
  6058. var distToCollision = t * this.velocity.length();
  6059. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6060. if (!this.intersectionPoint) {
  6061. this.intersectionPoint = this._collisionPoint.clone();
  6062. }
  6063. else {
  6064. this.intersectionPoint.copyFrom(this._collisionPoint);
  6065. }
  6066. this.nearestDistance = distToCollision;
  6067. this.collisionFound = true;
  6068. this.collidedMesh = subMesh.getMesh();
  6069. }
  6070. }
  6071. };
  6072. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6073. for (var i = indexStart; i < indexEnd; i += 3) {
  6074. var p1 = pts[indices[i] - decal];
  6075. var p2 = pts[indices[i + 1] - decal];
  6076. var p3 = pts[indices[i + 2] - decal];
  6077. this._testTriangle(i, subMesh, p3, p2, p1);
  6078. }
  6079. };
  6080. Collider.prototype._getResponse = function (pos, vel) {
  6081. pos.addToRef(vel, this._destinationPoint);
  6082. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6083. this.basePoint.addToRef(vel, pos);
  6084. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6085. this._slidePlaneNormal.normalize();
  6086. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6087. pos.addInPlace(this._displacementVector);
  6088. this.intersectionPoint.addInPlace(this._displacementVector);
  6089. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6090. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6091. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6092. };
  6093. return Collider;
  6094. })();
  6095. BABYLON.Collider = Collider;
  6096. })(BABYLON || (BABYLON = {}));
  6097. //# sourceMappingURL=babylon.collider.js.map
  6098. var BABYLON;
  6099. (function (BABYLON) {
  6100. var Camera = (function (_super) {
  6101. __extends(Camera, _super);
  6102. function Camera(name, position, scene) {
  6103. _super.call(this, name, scene);
  6104. this.position = position;
  6105. // Members
  6106. this.upVector = BABYLON.Vector3.Up();
  6107. this.orthoLeft = null;
  6108. this.orthoRight = null;
  6109. this.orthoBottom = null;
  6110. this.orthoTop = null;
  6111. this.fov = 0.8;
  6112. this.minZ = 1.0;
  6113. this.maxZ = 10000.0;
  6114. this.inertia = 0.9;
  6115. this.mode = Camera.PERSPECTIVE_CAMERA;
  6116. this.isIntermediate = false;
  6117. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6118. this.subCameras = [];
  6119. this.layerMask = 0xFFFFFFFF;
  6120. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6121. this._projectionMatrix = new BABYLON.Matrix();
  6122. this._postProcesses = new Array();
  6123. this._postProcessesTakenIndices = [];
  6124. scene.cameras.push(this);
  6125. if (!scene.activeCamera) {
  6126. scene.activeCamera = this;
  6127. }
  6128. }
  6129. //Cache
  6130. Camera.prototype._initCache = function () {
  6131. _super.prototype._initCache.call(this);
  6132. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6133. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6134. this._cache.mode = undefined;
  6135. this._cache.minZ = undefined;
  6136. this._cache.maxZ = undefined;
  6137. this._cache.fov = undefined;
  6138. this._cache.aspectRatio = undefined;
  6139. this._cache.orthoLeft = undefined;
  6140. this._cache.orthoRight = undefined;
  6141. this._cache.orthoBottom = undefined;
  6142. this._cache.orthoTop = undefined;
  6143. this._cache.renderWidth = undefined;
  6144. this._cache.renderHeight = undefined;
  6145. };
  6146. Camera.prototype._updateCache = function (ignoreParentClass) {
  6147. if (!ignoreParentClass) {
  6148. _super.prototype._updateCache.call(this);
  6149. }
  6150. var engine = this.getEngine();
  6151. this._cache.position.copyFrom(this.position);
  6152. this._cache.upVector.copyFrom(this.upVector);
  6153. this._cache.mode = this.mode;
  6154. this._cache.minZ = this.minZ;
  6155. this._cache.maxZ = this.maxZ;
  6156. this._cache.fov = this.fov;
  6157. this._cache.aspectRatio = engine.getAspectRatio(this);
  6158. this._cache.orthoLeft = this.orthoLeft;
  6159. this._cache.orthoRight = this.orthoRight;
  6160. this._cache.orthoBottom = this.orthoBottom;
  6161. this._cache.orthoTop = this.orthoTop;
  6162. this._cache.renderWidth = engine.getRenderWidth();
  6163. this._cache.renderHeight = engine.getRenderHeight();
  6164. };
  6165. Camera.prototype._updateFromScene = function () {
  6166. this.updateCache();
  6167. this._update();
  6168. };
  6169. // Synchronized
  6170. Camera.prototype._isSynchronized = function () {
  6171. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6172. };
  6173. Camera.prototype._isSynchronizedViewMatrix = function () {
  6174. if (!_super.prototype._isSynchronized.call(this))
  6175. return false;
  6176. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6177. };
  6178. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6179. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6180. if (!check) {
  6181. return false;
  6182. }
  6183. var engine = this.getEngine();
  6184. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6185. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6186. }
  6187. else {
  6188. 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();
  6189. }
  6190. return check;
  6191. };
  6192. // Controls
  6193. Camera.prototype.attachControl = function (element) {
  6194. };
  6195. Camera.prototype.detachControl = function (element) {
  6196. };
  6197. Camera.prototype._update = function () {
  6198. };
  6199. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6200. if (insertAt === void 0) { insertAt = null; }
  6201. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6202. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6203. return 0;
  6204. }
  6205. if (insertAt == null || insertAt < 0) {
  6206. this._postProcesses.push(postProcess);
  6207. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6208. return this._postProcesses.length - 1;
  6209. }
  6210. var add = 0;
  6211. if (this._postProcesses[insertAt]) {
  6212. var start = this._postProcesses.length - 1;
  6213. for (var i = start; i >= insertAt + 1; --i) {
  6214. this._postProcesses[i + 1] = this._postProcesses[i];
  6215. }
  6216. add = 1;
  6217. }
  6218. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6219. if (this._postProcessesTakenIndices[i] < insertAt) {
  6220. continue;
  6221. }
  6222. start = this._postProcessesTakenIndices.length - 1;
  6223. for (var j = start; j >= i; --j) {
  6224. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6225. }
  6226. this._postProcessesTakenIndices[i] = insertAt;
  6227. break;
  6228. }
  6229. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6230. this._postProcessesTakenIndices.push(insertAt);
  6231. }
  6232. var result = insertAt + add;
  6233. this._postProcesses[result] = postProcess;
  6234. return result;
  6235. };
  6236. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6237. if (atIndices === void 0) { atIndices = null; }
  6238. var result = [];
  6239. if (!atIndices) {
  6240. var length = this._postProcesses.length;
  6241. for (var i = 0; i < length; i++) {
  6242. if (this._postProcesses[i] !== postProcess) {
  6243. continue;
  6244. }
  6245. delete this._postProcesses[i];
  6246. var index = this._postProcessesTakenIndices.indexOf(i);
  6247. this._postProcessesTakenIndices.splice(index, 1);
  6248. }
  6249. }
  6250. else {
  6251. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6252. for (i = 0; i < atIndices.length; i++) {
  6253. var foundPostProcess = this._postProcesses[atIndices[i]];
  6254. if (foundPostProcess !== postProcess) {
  6255. result.push(i);
  6256. continue;
  6257. }
  6258. delete this._postProcesses[atIndices[i]];
  6259. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6260. this._postProcessesTakenIndices.splice(index, 1);
  6261. }
  6262. }
  6263. return result;
  6264. };
  6265. Camera.prototype.getWorldMatrix = function () {
  6266. if (!this._worldMatrix) {
  6267. this._worldMatrix = BABYLON.Matrix.Identity();
  6268. }
  6269. var viewMatrix = this.getViewMatrix();
  6270. viewMatrix.invertToRef(this._worldMatrix);
  6271. return this._worldMatrix;
  6272. };
  6273. Camera.prototype._getViewMatrix = function () {
  6274. return BABYLON.Matrix.Identity();
  6275. };
  6276. Camera.prototype.getViewMatrix = function () {
  6277. this._computedViewMatrix = this._computeViewMatrix();
  6278. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6279. return this._computedViewMatrix;
  6280. }
  6281. if (!this._worldMatrix) {
  6282. this._worldMatrix = BABYLON.Matrix.Identity();
  6283. }
  6284. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6285. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6286. this._computedViewMatrix.invert();
  6287. this._currentRenderId = this.getScene().getRenderId();
  6288. return this._computedViewMatrix;
  6289. };
  6290. Camera.prototype._computeViewMatrix = function (force) {
  6291. if (!force && this._isSynchronizedViewMatrix()) {
  6292. return this._computedViewMatrix;
  6293. }
  6294. this._computedViewMatrix = this._getViewMatrix();
  6295. if (!this.parent || !this.parent.getWorldMatrix) {
  6296. this._currentRenderId = this.getScene().getRenderId();
  6297. }
  6298. return this._computedViewMatrix;
  6299. };
  6300. Camera.prototype.getProjectionMatrix = function (force) {
  6301. if (!force && this._isSynchronizedProjectionMatrix()) {
  6302. return this._projectionMatrix;
  6303. }
  6304. var engine = this.getEngine();
  6305. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6306. if (this.minZ <= 0) {
  6307. this.minZ = 0.1;
  6308. }
  6309. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  6310. return this._projectionMatrix;
  6311. }
  6312. var halfWidth = engine.getRenderWidth() / 2.0;
  6313. var halfHeight = engine.getRenderHeight() / 2.0;
  6314. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6315. return this._projectionMatrix;
  6316. };
  6317. Camera.prototype.dispose = function () {
  6318. // Remove from scene
  6319. var index = this.getScene().cameras.indexOf(this);
  6320. this.getScene().cameras.splice(index, 1);
  6321. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6322. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6323. }
  6324. };
  6325. // Statics
  6326. Camera.PERSPECTIVE_CAMERA = 0;
  6327. Camera.ORTHOGRAPHIC_CAMERA = 1;
  6328. return Camera;
  6329. })(BABYLON.Node);
  6330. BABYLON.Camera = Camera;
  6331. })(BABYLON || (BABYLON = {}));
  6332. //# sourceMappingURL=babylon.camera.js.map
  6333. var BABYLON;
  6334. (function (BABYLON) {
  6335. var TargetCamera = (function (_super) {
  6336. __extends(TargetCamera, _super);
  6337. function TargetCamera(name, position, scene) {
  6338. _super.call(this, name, position, scene);
  6339. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6340. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6341. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6342. this.speed = 2.0;
  6343. this.noRotationConstraint = false;
  6344. this.lockedTarget = null;
  6345. this._currentTarget = BABYLON.Vector3.Zero();
  6346. this._viewMatrix = BABYLON.Matrix.Zero();
  6347. this._camMatrix = BABYLON.Matrix.Zero();
  6348. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6349. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6350. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6351. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6352. this._lookAtTemp = BABYLON.Matrix.Zero();
  6353. this._tempMatrix = BABYLON.Matrix.Zero();
  6354. }
  6355. TargetCamera.prototype._getLockedTargetPosition = function () {
  6356. if (!this.lockedTarget) {
  6357. return null;
  6358. }
  6359. return this.lockedTarget.position || this.lockedTarget;
  6360. };
  6361. // Cache
  6362. TargetCamera.prototype._initCache = function () {
  6363. _super.prototype._initCache.call(this);
  6364. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6365. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6366. };
  6367. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6368. if (!ignoreParentClass) {
  6369. _super.prototype._updateCache.call(this);
  6370. }
  6371. var lockedTargetPosition = this._getLockedTargetPosition();
  6372. if (!lockedTargetPosition) {
  6373. this._cache.lockedTarget = null;
  6374. }
  6375. else {
  6376. if (!this._cache.lockedTarget) {
  6377. this._cache.lockedTarget = lockedTargetPosition.clone();
  6378. }
  6379. else {
  6380. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6381. }
  6382. }
  6383. this._cache.rotation.copyFrom(this.rotation);
  6384. };
  6385. // Synchronized
  6386. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6387. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6388. return false;
  6389. }
  6390. var lockedTargetPosition = this._getLockedTargetPosition();
  6391. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6392. };
  6393. // Methods
  6394. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6395. var engine = this.getEngine();
  6396. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6397. };
  6398. // Target
  6399. TargetCamera.prototype.setTarget = function (target) {
  6400. this.upVector.normalize();
  6401. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6402. this._camMatrix.invert();
  6403. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6404. var vDir = target.subtract(this.position);
  6405. if (vDir.x >= 0.0) {
  6406. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6407. }
  6408. else {
  6409. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6410. }
  6411. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6412. if (isNaN(this.rotation.x)) {
  6413. this.rotation.x = 0;
  6414. }
  6415. if (isNaN(this.rotation.y)) {
  6416. this.rotation.y = 0;
  6417. }
  6418. if (isNaN(this.rotation.z)) {
  6419. this.rotation.z = 0;
  6420. }
  6421. };
  6422. TargetCamera.prototype.getTarget = function () {
  6423. return this._currentTarget;
  6424. };
  6425. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6426. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6427. };
  6428. TargetCamera.prototype._updatePosition = function () {
  6429. this.position.addInPlace(this.cameraDirection);
  6430. };
  6431. TargetCamera.prototype._update = function () {
  6432. var needToMove = this._decideIfNeedsToMove();
  6433. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6434. // Move
  6435. if (needToMove) {
  6436. this._updatePosition();
  6437. }
  6438. // Rotate
  6439. if (needToRotate) {
  6440. this.rotation.x += this.cameraRotation.x;
  6441. this.rotation.y += this.cameraRotation.y;
  6442. if (!this.noRotationConstraint) {
  6443. var limit = (Math.PI / 2) * 0.95;
  6444. if (this.rotation.x > limit)
  6445. this.rotation.x = limit;
  6446. if (this.rotation.x < -limit)
  6447. this.rotation.x = -limit;
  6448. }
  6449. }
  6450. // Inertia
  6451. if (needToMove) {
  6452. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6453. this.cameraDirection.x = 0;
  6454. }
  6455. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6456. this.cameraDirection.y = 0;
  6457. }
  6458. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6459. this.cameraDirection.z = 0;
  6460. }
  6461. this.cameraDirection.scaleInPlace(this.inertia);
  6462. }
  6463. if (needToRotate) {
  6464. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6465. this.cameraRotation.x = 0;
  6466. }
  6467. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6468. this.cameraRotation.y = 0;
  6469. }
  6470. this.cameraRotation.scaleInPlace(this.inertia);
  6471. }
  6472. };
  6473. TargetCamera.prototype._getViewMatrix = function () {
  6474. if (!this.lockedTarget) {
  6475. // Compute
  6476. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6477. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6478. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6479. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6480. this._lookAtTemp.invert();
  6481. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6482. }
  6483. else {
  6484. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6485. }
  6486. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6487. // Computing target and final matrix
  6488. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6489. }
  6490. else {
  6491. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6492. }
  6493. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6494. return this._viewMatrix;
  6495. };
  6496. return TargetCamera;
  6497. })(BABYLON.Camera);
  6498. BABYLON.TargetCamera = TargetCamera;
  6499. })(BABYLON || (BABYLON = {}));
  6500. //# sourceMappingURL=babylon.targetCamera.js.map
  6501. var BABYLON;
  6502. (function (BABYLON) {
  6503. var FollowCamera = (function (_super) {
  6504. __extends(FollowCamera, _super);
  6505. function FollowCamera(name, position, scene) {
  6506. _super.call(this, name, position, scene);
  6507. this.radius = 12;
  6508. this.rotationOffset = 0;
  6509. this.heightOffset = 4;
  6510. this.cameraAcceleration = 0.05;
  6511. this.maxCameraSpeed = 20;
  6512. }
  6513. FollowCamera.prototype.getRadians = function (degrees) {
  6514. return degrees * Math.PI / 180;
  6515. };
  6516. FollowCamera.prototype.follow = function (cameraTarget) {
  6517. if (!cameraTarget)
  6518. return;
  6519. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6520. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6521. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6522. var dx = targetX - this.position.x;
  6523. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6524. var dz = (targetZ) - this.position.z;
  6525. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6526. var vy = dy * this.cameraAcceleration;
  6527. var vz = dz * this.cameraAcceleration * 2;
  6528. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6529. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6530. }
  6531. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6532. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6533. }
  6534. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6535. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6536. }
  6537. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6538. this.setTarget(cameraTarget.position);
  6539. };
  6540. FollowCamera.prototype._update = function () {
  6541. _super.prototype._update.call(this);
  6542. this.follow(this.target);
  6543. };
  6544. return FollowCamera;
  6545. })(BABYLON.TargetCamera);
  6546. BABYLON.FollowCamera = FollowCamera;
  6547. })(BABYLON || (BABYLON = {}));
  6548. //# sourceMappingURL=babylon.followCamera.js.map
  6549. var BABYLON;
  6550. (function (BABYLON) {
  6551. var FreeCamera = (function (_super) {
  6552. __extends(FreeCamera, _super);
  6553. function FreeCamera(name, position, scene) {
  6554. _super.call(this, name, position, scene);
  6555. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6556. this.keysUp = [38];
  6557. this.keysDown = [40];
  6558. this.keysLeft = [37];
  6559. this.keysRight = [39];
  6560. this.checkCollisions = false;
  6561. this.applyGravity = false;
  6562. this.angularSensibility = 2000.0;
  6563. this._keys = [];
  6564. this._collider = new BABYLON.Collider();
  6565. this._needMoveForGravity = true;
  6566. this._oldPosition = BABYLON.Vector3.Zero();
  6567. this._diffPosition = BABYLON.Vector3.Zero();
  6568. this._newPosition = BABYLON.Vector3.Zero();
  6569. }
  6570. // Controls
  6571. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6572. var _this = this;
  6573. var previousPosition;
  6574. var engine = this.getEngine();
  6575. if (this._attachedElement) {
  6576. return;
  6577. }
  6578. this._attachedElement = element;
  6579. if (this._onMouseDown === undefined) {
  6580. this._onMouseDown = function (evt) {
  6581. previousPosition = {
  6582. x: evt.clientX,
  6583. y: evt.clientY
  6584. };
  6585. if (!noPreventDefault) {
  6586. evt.preventDefault();
  6587. }
  6588. };
  6589. this._onMouseUp = function (evt) {
  6590. previousPosition = null;
  6591. if (!noPreventDefault) {
  6592. evt.preventDefault();
  6593. }
  6594. };
  6595. this._onMouseOut = function (evt) {
  6596. previousPosition = null;
  6597. _this._keys = [];
  6598. if (!noPreventDefault) {
  6599. evt.preventDefault();
  6600. }
  6601. };
  6602. this._onMouseMove = function (evt) {
  6603. if (!previousPosition && !engine.isPointerLock) {
  6604. return;
  6605. }
  6606. var offsetX;
  6607. var offsetY;
  6608. if (!engine.isPointerLock) {
  6609. offsetX = evt.clientX - previousPosition.x;
  6610. offsetY = evt.clientY - previousPosition.y;
  6611. }
  6612. else {
  6613. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6614. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6615. }
  6616. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6617. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6618. previousPosition = {
  6619. x: evt.clientX,
  6620. y: evt.clientY
  6621. };
  6622. if (!noPreventDefault) {
  6623. evt.preventDefault();
  6624. }
  6625. };
  6626. this._onKeyDown = function (evt) {
  6627. 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) {
  6628. var index = _this._keys.indexOf(evt.keyCode);
  6629. if (index === -1) {
  6630. _this._keys.push(evt.keyCode);
  6631. }
  6632. if (!noPreventDefault) {
  6633. evt.preventDefault();
  6634. }
  6635. }
  6636. };
  6637. this._onKeyUp = function (evt) {
  6638. 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) {
  6639. var index = _this._keys.indexOf(evt.keyCode);
  6640. if (index >= 0) {
  6641. _this._keys.splice(index, 1);
  6642. }
  6643. if (!noPreventDefault) {
  6644. evt.preventDefault();
  6645. }
  6646. }
  6647. };
  6648. this._onLostFocus = function () {
  6649. _this._keys = [];
  6650. };
  6651. this._reset = function () {
  6652. _this._keys = [];
  6653. previousPosition = null;
  6654. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6655. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6656. };
  6657. }
  6658. element.addEventListener("mousedown", this._onMouseDown, false);
  6659. element.addEventListener("mouseup", this._onMouseUp, false);
  6660. element.addEventListener("mouseout", this._onMouseOut, false);
  6661. element.addEventListener("mousemove", this._onMouseMove, false);
  6662. BABYLON.Tools.RegisterTopRootEvents([
  6663. { name: "keydown", handler: this._onKeyDown },
  6664. { name: "keyup", handler: this._onKeyUp },
  6665. { name: "blur", handler: this._onLostFocus }
  6666. ]);
  6667. };
  6668. FreeCamera.prototype.detachControl = function (element) {
  6669. if (this._attachedElement != element) {
  6670. return;
  6671. }
  6672. element.removeEventListener("mousedown", this._onMouseDown);
  6673. element.removeEventListener("mouseup", this._onMouseUp);
  6674. element.removeEventListener("mouseout", this._onMouseOut);
  6675. element.removeEventListener("mousemove", this._onMouseMove);
  6676. BABYLON.Tools.UnregisterTopRootEvents([
  6677. { name: "keydown", handler: this._onKeyDown },
  6678. { name: "keyup", handler: this._onKeyUp },
  6679. { name: "blur", handler: this._onLostFocus }
  6680. ]);
  6681. this._attachedElement = null;
  6682. if (this._reset) {
  6683. this._reset();
  6684. }
  6685. };
  6686. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6687. var globalPosition;
  6688. if (this.parent) {
  6689. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6690. }
  6691. else {
  6692. globalPosition = this.position;
  6693. }
  6694. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6695. this._collider.radius = this.ellipsoid;
  6696. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6697. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6698. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6699. this.position.addInPlace(this._diffPosition);
  6700. if (this.onCollide) {
  6701. this.onCollide(this._collider.collidedMesh);
  6702. }
  6703. }
  6704. };
  6705. FreeCamera.prototype._checkInputs = function () {
  6706. if (!this._localDirection) {
  6707. this._localDirection = BABYLON.Vector3.Zero();
  6708. this._transformedDirection = BABYLON.Vector3.Zero();
  6709. }
  6710. for (var index = 0; index < this._keys.length; index++) {
  6711. var keyCode = this._keys[index];
  6712. var speed = this._computeLocalCameraSpeed();
  6713. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6714. this._localDirection.copyFromFloats(-speed, 0, 0);
  6715. }
  6716. else if (this.keysUp.indexOf(keyCode) !== -1) {
  6717. this._localDirection.copyFromFloats(0, 0, speed);
  6718. }
  6719. else if (this.keysRight.indexOf(keyCode) !== -1) {
  6720. this._localDirection.copyFromFloats(speed, 0, 0);
  6721. }
  6722. else if (this.keysDown.indexOf(keyCode) !== -1) {
  6723. this._localDirection.copyFromFloats(0, 0, -speed);
  6724. }
  6725. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6726. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6727. this.cameraDirection.addInPlace(this._transformedDirection);
  6728. }
  6729. };
  6730. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6731. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6732. };
  6733. FreeCamera.prototype._updatePosition = function () {
  6734. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6735. this._collideWithWorld(this.cameraDirection);
  6736. if (this.applyGravity) {
  6737. var oldPosition = this.position;
  6738. this._collideWithWorld(this.getScene().gravity);
  6739. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6740. }
  6741. }
  6742. else {
  6743. this.position.addInPlace(this.cameraDirection);
  6744. }
  6745. };
  6746. FreeCamera.prototype._update = function () {
  6747. this._checkInputs();
  6748. _super.prototype._update.call(this);
  6749. };
  6750. return FreeCamera;
  6751. })(BABYLON.TargetCamera);
  6752. BABYLON.FreeCamera = FreeCamera;
  6753. })(BABYLON || (BABYLON = {}));
  6754. //# sourceMappingURL=babylon.freeCamera.js.map
  6755. var BABYLON;
  6756. (function (BABYLON) {
  6757. // We're mainly based on the logic defined into the FreeCamera code
  6758. var TouchCamera = (function (_super) {
  6759. __extends(TouchCamera, _super);
  6760. function TouchCamera(name, position, scene) {
  6761. _super.call(this, name, position, scene);
  6762. this._offsetX = null;
  6763. this._offsetY = null;
  6764. this._pointerCount = 0;
  6765. this._pointerPressed = [];
  6766. this.angularSensibility = 200000.0;
  6767. this.moveSensibility = 500.0;
  6768. }
  6769. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6770. var _this = this;
  6771. var previousPosition;
  6772. if (this._attachedCanvas) {
  6773. return;
  6774. }
  6775. this._attachedCanvas = canvas;
  6776. if (this._onPointerDown === undefined) {
  6777. this._onPointerDown = function (evt) {
  6778. if (!noPreventDefault) {
  6779. evt.preventDefault();
  6780. }
  6781. _this._pointerPressed.push(evt.pointerId);
  6782. if (_this._pointerPressed.length !== 1) {
  6783. return;
  6784. }
  6785. previousPosition = {
  6786. x: evt.clientX,
  6787. y: evt.clientY
  6788. };
  6789. };
  6790. this._onPointerUp = function (evt) {
  6791. if (!noPreventDefault) {
  6792. evt.preventDefault();
  6793. }
  6794. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6795. if (index === -1) {
  6796. return;
  6797. }
  6798. _this._pointerPressed.splice(index, 1);
  6799. if (index != 0) {
  6800. return;
  6801. }
  6802. previousPosition = null;
  6803. _this._offsetX = null;
  6804. _this._offsetY = null;
  6805. };
  6806. this._onPointerMove = function (evt) {
  6807. if (!noPreventDefault) {
  6808. evt.preventDefault();
  6809. }
  6810. if (!previousPosition) {
  6811. return;
  6812. }
  6813. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6814. if (index != 0) {
  6815. return;
  6816. }
  6817. _this._offsetX = evt.clientX - previousPosition.x;
  6818. _this._offsetY = -(evt.clientY - previousPosition.y);
  6819. };
  6820. this._onLostFocus = function () {
  6821. _this._offsetX = null;
  6822. _this._offsetY = null;
  6823. };
  6824. }
  6825. canvas.addEventListener("pointerdown", this._onPointerDown);
  6826. canvas.addEventListener("pointerup", this._onPointerUp);
  6827. canvas.addEventListener("pointerout", this._onPointerUp);
  6828. canvas.addEventListener("pointermove", this._onPointerMove);
  6829. BABYLON.Tools.RegisterTopRootEvents([
  6830. { name: "blur", handler: this._onLostFocus }
  6831. ]);
  6832. };
  6833. TouchCamera.prototype.detachControl = function (canvas) {
  6834. if (this._attachedCanvas != canvas) {
  6835. return;
  6836. }
  6837. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6838. canvas.removeEventListener("pointerup", this._onPointerUp);
  6839. canvas.removeEventListener("pointerout", this._onPointerUp);
  6840. canvas.removeEventListener("pointermove", this._onPointerMove);
  6841. BABYLON.Tools.UnregisterTopRootEvents([
  6842. { name: "blur", handler: this._onLostFocus }
  6843. ]);
  6844. this._attachedCanvas = null;
  6845. };
  6846. TouchCamera.prototype._checkInputs = function () {
  6847. if (!this._offsetX) {
  6848. return;
  6849. }
  6850. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6851. if (this._pointerPressed.length > 1) {
  6852. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6853. }
  6854. else {
  6855. var speed = this._computeLocalCameraSpeed();
  6856. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6857. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6858. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6859. }
  6860. };
  6861. return TouchCamera;
  6862. })(BABYLON.FreeCamera);
  6863. BABYLON.TouchCamera = TouchCamera;
  6864. })(BABYLON || (BABYLON = {}));
  6865. //# sourceMappingURL=babylon.touchCamera.js.map
  6866. var BABYLON;
  6867. (function (BABYLON) {
  6868. // We're mainly based on the logic defined into the FreeCamera code
  6869. var DeviceOrientationCamera = (function (_super) {
  6870. __extends(DeviceOrientationCamera, _super);
  6871. function DeviceOrientationCamera(name, position, scene) {
  6872. var _this = this;
  6873. _super.call(this, name, position, scene);
  6874. this._offsetX = null;
  6875. this._offsetY = null;
  6876. this._orientationGamma = 0;
  6877. this._orientationBeta = 0;
  6878. this._initialOrientationGamma = 0;
  6879. this._initialOrientationBeta = 0;
  6880. this.angularSensibility = 10000.0;
  6881. this.moveSensibility = 50.0;
  6882. window.addEventListener("resize", function () {
  6883. _this._initialOrientationGamma = null;
  6884. }, false);
  6885. }
  6886. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6887. var _this = this;
  6888. if (this._attachedCanvas) {
  6889. return;
  6890. }
  6891. this._attachedCanvas = canvas;
  6892. if (!this._orientationChanged) {
  6893. this._orientationChanged = function (evt) {
  6894. if (!_this._initialOrientationGamma) {
  6895. _this._initialOrientationGamma = evt.gamma;
  6896. _this._initialOrientationBeta = evt.beta;
  6897. }
  6898. _this._orientationGamma = evt.gamma;
  6899. _this._orientationBeta = evt.beta;
  6900. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6901. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6902. };
  6903. }
  6904. window.addEventListener("deviceorientation", this._orientationChanged);
  6905. };
  6906. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6907. if (this._attachedCanvas != canvas) {
  6908. return;
  6909. }
  6910. window.removeEventListener("deviceorientation", this._orientationChanged);
  6911. this._attachedCanvas = null;
  6912. this._orientationGamma = 0;
  6913. this._orientationBeta = 0;
  6914. this._initialOrientationGamma = 0;
  6915. this._initialOrientationBeta = 0;
  6916. };
  6917. DeviceOrientationCamera.prototype._checkInputs = function () {
  6918. if (!this._offsetX) {
  6919. return;
  6920. }
  6921. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6922. var speed = this._computeLocalCameraSpeed();
  6923. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6924. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6925. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6926. };
  6927. return DeviceOrientationCamera;
  6928. })(BABYLON.FreeCamera);
  6929. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6930. })(BABYLON || (BABYLON = {}));
  6931. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6932. var BABYLON;
  6933. (function (BABYLON) {
  6934. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6935. var ArcRotateCamera = (function (_super) {
  6936. __extends(ArcRotateCamera, _super);
  6937. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6938. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6939. this.alpha = alpha;
  6940. this.beta = beta;
  6941. this.radius = radius;
  6942. this.target = target;
  6943. this.inertialAlphaOffset = 0;
  6944. this.inertialBetaOffset = 0;
  6945. this.inertialRadiusOffset = 0;
  6946. this.lowerAlphaLimit = null;
  6947. this.upperAlphaLimit = null;
  6948. this.lowerBetaLimit = 0.01;
  6949. this.upperBetaLimit = Math.PI;
  6950. this.lowerRadiusLimit = null;
  6951. this.upperRadiusLimit = null;
  6952. this.angularSensibility = 1000.0;
  6953. this.wheelPrecision = 3.0;
  6954. this.keysUp = [38];
  6955. this.keysDown = [40];
  6956. this.keysLeft = [37];
  6957. this.keysRight = [39];
  6958. this.zoomOnFactor = 1;
  6959. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6960. this._keys = [];
  6961. this._viewMatrix = new BABYLON.Matrix();
  6962. this.checkCollisions = false;
  6963. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6964. this._collider = new BABYLON.Collider();
  6965. this._previousPosition = BABYLON.Vector3.Zero();
  6966. this._collisionVelocity = BABYLON.Vector3.Zero();
  6967. this._newPosition = BABYLON.Vector3.Zero();
  6968. // Pinch
  6969. // value for pinch step scaling
  6970. // set to 20 by default
  6971. this.pinchPrecision = 20;
  6972. this.getViewMatrix();
  6973. }
  6974. ArcRotateCamera.prototype._getTargetPosition = function () {
  6975. return this.target.position || this.target;
  6976. };
  6977. // Cache
  6978. ArcRotateCamera.prototype._initCache = function () {
  6979. _super.prototype._initCache.call(this);
  6980. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6981. this._cache.alpha = undefined;
  6982. this._cache.beta = undefined;
  6983. this._cache.radius = undefined;
  6984. this._cache.targetScreenOffset = undefined;
  6985. };
  6986. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6987. if (!ignoreParentClass) {
  6988. _super.prototype._updateCache.call(this);
  6989. }
  6990. this._cache.target.copyFrom(this._getTargetPosition());
  6991. this._cache.alpha = this.alpha;
  6992. this._cache.beta = this.beta;
  6993. this._cache.radius = this.radius;
  6994. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6995. };
  6996. // Synchronized
  6997. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6998. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6999. return false;
  7000. 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);
  7001. };
  7002. // Methods
  7003. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7004. var _this = this;
  7005. var previousPosition;
  7006. var pointerId;
  7007. // to know if pinch started
  7008. var pinchStarted = false;
  7009. // two pinch point on X
  7010. // that will use for find if user action is pinch open or pinch close
  7011. var pinchPointX1, pinchPointX2;
  7012. if (this._attachedElement) {
  7013. return;
  7014. }
  7015. this._attachedElement = element;
  7016. var engine = this.getEngine();
  7017. if (this._onPointerDown === undefined) {
  7018. this._onPointerDown = function (evt) {
  7019. if (pointerId) {
  7020. return;
  7021. }
  7022. pointerId = evt.pointerId;
  7023. previousPosition = {
  7024. x: evt.clientX,
  7025. y: evt.clientY
  7026. };
  7027. if (!noPreventDefault) {
  7028. evt.preventDefault();
  7029. }
  7030. };
  7031. this._onPointerUp = function (evt) {
  7032. previousPosition = null;
  7033. pointerId = null;
  7034. if (!noPreventDefault) {
  7035. evt.preventDefault();
  7036. }
  7037. };
  7038. this._onPointerMove = function (evt) {
  7039. if (!previousPosition) {
  7040. return;
  7041. }
  7042. if (pointerId !== evt.pointerId) {
  7043. return;
  7044. }
  7045. // return pinch is started
  7046. if (pinchStarted) {
  7047. return;
  7048. }
  7049. var offsetX = evt.clientX - previousPosition.x;
  7050. var offsetY = evt.clientY - previousPosition.y;
  7051. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7052. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7053. previousPosition = {
  7054. x: evt.clientX,
  7055. y: evt.clientY
  7056. };
  7057. if (!noPreventDefault) {
  7058. evt.preventDefault();
  7059. }
  7060. };
  7061. this._onMouseMove = function (evt) {
  7062. if (!engine.isPointerLock) {
  7063. return;
  7064. }
  7065. // return pinch is started
  7066. if (pinchStarted) {
  7067. return;
  7068. }
  7069. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7070. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7071. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7072. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7073. if (!noPreventDefault) {
  7074. evt.preventDefault();
  7075. }
  7076. };
  7077. this._wheel = function (event) {
  7078. var delta = 0;
  7079. if (event.wheelDelta) {
  7080. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7081. }
  7082. else if (event.detail) {
  7083. delta = -event.detail / _this.wheelPrecision;
  7084. }
  7085. if (delta)
  7086. _this.inertialRadiusOffset += delta;
  7087. if (event.preventDefault) {
  7088. if (!noPreventDefault) {
  7089. event.preventDefault();
  7090. }
  7091. }
  7092. };
  7093. this._onKeyDown = function (evt) {
  7094. 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) {
  7095. var index = _this._keys.indexOf(evt.keyCode);
  7096. if (index === -1) {
  7097. _this._keys.push(evt.keyCode);
  7098. }
  7099. if (evt.preventDefault) {
  7100. if (!noPreventDefault) {
  7101. evt.preventDefault();
  7102. }
  7103. }
  7104. }
  7105. };
  7106. this._onKeyUp = function (evt) {
  7107. 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) {
  7108. var index = _this._keys.indexOf(evt.keyCode);
  7109. if (index >= 0) {
  7110. _this._keys.splice(index, 1);
  7111. }
  7112. if (evt.preventDefault) {
  7113. if (!noPreventDefault) {
  7114. evt.preventDefault();
  7115. }
  7116. }
  7117. }
  7118. };
  7119. this._onLostFocus = function () {
  7120. _this._keys = [];
  7121. pointerId = null;
  7122. };
  7123. this._onGestureStart = function (e) {
  7124. if (window.MSGesture === undefined) {
  7125. return;
  7126. }
  7127. if (!_this._MSGestureHandler) {
  7128. _this._MSGestureHandler = new MSGesture();
  7129. _this._MSGestureHandler.target = element;
  7130. }
  7131. _this._MSGestureHandler.addPointer(e.pointerId);
  7132. };
  7133. this._onGesture = function (e) {
  7134. _this.radius *= e.scale;
  7135. if (e.preventDefault) {
  7136. if (!noPreventDefault) {
  7137. e.stopPropagation();
  7138. e.preventDefault();
  7139. }
  7140. }
  7141. };
  7142. this._reset = function () {
  7143. _this._keys = [];
  7144. _this.inertialAlphaOffset = 0;
  7145. _this.inertialBetaOffset = 0;
  7146. _this.inertialRadiusOffset = 0;
  7147. previousPosition = null;
  7148. pointerId = null;
  7149. };
  7150. this._touchStart = function (event) {
  7151. if (event.touches.length === 2) {
  7152. //-- start pinch if two fingers on the screen
  7153. pinchStarted = true;
  7154. _this._pinchStart(event);
  7155. }
  7156. };
  7157. this._touchMove = function (event) {
  7158. if (pinchStarted) {
  7159. //-- make scaling
  7160. _this._pinchMove(event);
  7161. }
  7162. };
  7163. this._touchEnd = function (event) {
  7164. if (pinchStarted) {
  7165. //-- end of pinch
  7166. _this._pinchEnd(event);
  7167. }
  7168. };
  7169. this._pinchStart = function (event) {
  7170. // save origin touch point
  7171. pinchPointX1 = event.touches[0].clientX;
  7172. pinchPointX2 = event.touches[1].clientX;
  7173. // block the camera
  7174. // if not it rotate around target during pinch
  7175. pinchStarted = true;
  7176. };
  7177. this._pinchMove = function (event) {
  7178. // variable for new camera's radius
  7179. var delta = 0;
  7180. // variables to know if pinch open or pinch close
  7181. var direction = 1;
  7182. var distanceXOrigine, distanceXNow;
  7183. if (event.touches.length !== 2)
  7184. return;
  7185. // calculate absolute distances of the two fingers
  7186. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7187. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7188. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7189. if (distanceXNow < distanceXOrigine) {
  7190. direction = -1;
  7191. }
  7192. // calculate new radius
  7193. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7194. // set new radius
  7195. _this.inertialRadiusOffset -= delta;
  7196. // save origin touch point
  7197. pinchPointX1 = event.touches[0].clientX;
  7198. pinchPointX2 = event.touches[1].clientX;
  7199. };
  7200. this._pinchEnd = function (event) {
  7201. // cancel pinch and deblock camera rotation
  7202. pinchStarted = false;
  7203. };
  7204. }
  7205. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7206. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7207. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7208. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7209. element.addEventListener("mousemove", this._onMouseMove, false);
  7210. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7211. element.addEventListener("MSGestureChange", this._onGesture, false);
  7212. element.addEventListener('mousewheel', this._wheel, false);
  7213. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7214. // pinch
  7215. element.addEventListener('touchstart', this._touchStart, false);
  7216. element.addEventListener('touchmove', this._touchMove, false);
  7217. element.addEventListener('touchend', this._touchEnd, false);
  7218. BABYLON.Tools.RegisterTopRootEvents([
  7219. { name: "keydown", handler: this._onKeyDown },
  7220. { name: "keyup", handler: this._onKeyUp },
  7221. { name: "blur", handler: this._onLostFocus }
  7222. ]);
  7223. };
  7224. ArcRotateCamera.prototype.detachControl = function (element) {
  7225. if (this._attachedElement != element) {
  7226. return;
  7227. }
  7228. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7229. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7230. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7231. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7232. element.removeEventListener("mousemove", this._onMouseMove);
  7233. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7234. element.removeEventListener("MSGestureChange", this._onGesture);
  7235. element.removeEventListener('mousewheel', this._wheel);
  7236. element.removeEventListener('DOMMouseScroll', this._wheel);
  7237. // pinch
  7238. element.removeEventListener('touchstart', this._touchStart);
  7239. element.removeEventListener('touchmove', this._touchMove);
  7240. element.removeEventListener('touchend', this._touchEnd);
  7241. BABYLON.Tools.UnregisterTopRootEvents([
  7242. { name: "keydown", handler: this._onKeyDown },
  7243. { name: "keyup", handler: this._onKeyUp },
  7244. { name: "blur", handler: this._onLostFocus }
  7245. ]);
  7246. this._MSGestureHandler = null;
  7247. this._attachedElement = null;
  7248. if (this._reset) {
  7249. this._reset();
  7250. }
  7251. };
  7252. ArcRotateCamera.prototype._update = function () {
  7253. for (var index = 0; index < this._keys.length; index++) {
  7254. var keyCode = this._keys[index];
  7255. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7256. this.inertialAlphaOffset -= 0.01;
  7257. }
  7258. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7259. this.inertialBetaOffset -= 0.01;
  7260. }
  7261. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7262. this.inertialAlphaOffset += 0.01;
  7263. }
  7264. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7265. this.inertialBetaOffset += 0.01;
  7266. }
  7267. }
  7268. // Inertia
  7269. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7270. this.alpha += this.inertialAlphaOffset;
  7271. this.beta += this.inertialBetaOffset;
  7272. this.radius -= this.inertialRadiusOffset;
  7273. this.inertialAlphaOffset *= this.inertia;
  7274. this.inertialBetaOffset *= this.inertia;
  7275. this.inertialRadiusOffset *= this.inertia;
  7276. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7277. this.inertialAlphaOffset = 0;
  7278. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7279. this.inertialBetaOffset = 0;
  7280. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7281. this.inertialRadiusOffset = 0;
  7282. }
  7283. // Limits
  7284. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7285. this.alpha = this.lowerAlphaLimit;
  7286. }
  7287. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7288. this.alpha = this.upperAlphaLimit;
  7289. }
  7290. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7291. this.beta = this.lowerBetaLimit;
  7292. }
  7293. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7294. this.beta = this.upperBetaLimit;
  7295. }
  7296. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7297. this.radius = this.lowerRadiusLimit;
  7298. }
  7299. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7300. this.radius = this.upperRadiusLimit;
  7301. }
  7302. };
  7303. ArcRotateCamera.prototype.setPosition = function (position) {
  7304. var radiusv3 = position.subtract(this._getTargetPosition());
  7305. this.radius = radiusv3.length();
  7306. // Alpha
  7307. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7308. if (radiusv3.z < 0) {
  7309. this.alpha = 2 * Math.PI - this.alpha;
  7310. }
  7311. // Beta
  7312. this.beta = Math.acos(radiusv3.y / this.radius);
  7313. };
  7314. ArcRotateCamera.prototype._getViewMatrix = function () {
  7315. // Compute
  7316. var cosa = Math.cos(this.alpha);
  7317. var sina = Math.sin(this.alpha);
  7318. var cosb = Math.cos(this.beta);
  7319. var sinb = Math.sin(this.beta);
  7320. var target = this._getTargetPosition();
  7321. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7322. if (this.checkCollisions) {
  7323. this._collider.radius = this.collisionRadius;
  7324. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7325. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7326. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7327. this.position.copyFrom(this._previousPosition);
  7328. this.alpha = this._previousAlpha;
  7329. this.beta = this._previousBeta;
  7330. this.radius = this._previousRadius;
  7331. if (this.onCollide) {
  7332. this.onCollide(this._collider.collidedMesh);
  7333. }
  7334. }
  7335. }
  7336. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7337. this._previousAlpha = this.alpha;
  7338. this._previousBeta = this.beta;
  7339. this._previousRadius = this.radius;
  7340. this._previousPosition.copyFrom(this.position);
  7341. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7342. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7343. return this._viewMatrix;
  7344. };
  7345. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7346. meshes = meshes || this.getScene().meshes;
  7347. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7348. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7349. this.radius = distance * this.zoomOnFactor;
  7350. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7351. };
  7352. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7353. var meshesOrMinMaxVector;
  7354. var distance;
  7355. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7356. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7357. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7358. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7359. }
  7360. else {
  7361. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7362. distance = meshesOrMinMaxVectorAndDistance.distance;
  7363. }
  7364. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7365. this.maxZ = distance * 2;
  7366. };
  7367. return ArcRotateCamera;
  7368. })(BABYLON.Camera);
  7369. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7370. })(BABYLON || (BABYLON = {}));
  7371. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7372. (function (BABYLON) {
  7373. /**
  7374. * Represents a scene to be rendered by the engine.
  7375. * @see http://doc.babylonjs.com/page.php?p=21911
  7376. */
  7377. var Scene = (function () {
  7378. /**
  7379. * @constructor
  7380. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7381. */
  7382. function Scene(engine) {
  7383. // Members
  7384. this.autoClear = true;
  7385. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7386. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7387. this.forceWireframe = false;
  7388. this.forcePointsCloud = false;
  7389. this.forceShowBoundingBoxes = false;
  7390. this.animationsEnabled = true;
  7391. 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
  7392. // Fog
  7393. /**
  7394. * is fog enabled on this scene.
  7395. * @type {boolean}
  7396. */
  7397. this.fogEnabled = true;
  7398. this.fogMode = Scene.FOGMODE_NONE;
  7399. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7400. this.fogDensity = 0.1;
  7401. this.fogStart = 0;
  7402. this.fogEnd = 1000.0;
  7403. // Lights
  7404. /**
  7405. * is shadow enabled on this scene.
  7406. * @type {boolean}
  7407. */
  7408. this.shadowsEnabled = true;
  7409. /**
  7410. * is light enabled on this scene.
  7411. * @type {boolean}
  7412. */
  7413. this.lightsEnabled = true;
  7414. /**
  7415. * All of the lights added to this scene.
  7416. * @see BABYLON.Light
  7417. * @type {BABYLON.Light[]}
  7418. */
  7419. this.lights = new Array();
  7420. // Cameras
  7421. /**
  7422. * All of the cameras added to this scene.
  7423. * @see BABYLON.Camera
  7424. * @type {BABYLON.Camera[]}
  7425. */
  7426. this.cameras = new Array();
  7427. this.activeCameras = new Array();
  7428. // Meshes
  7429. /**
  7430. * All of the (abstract) meshes added to this scene.
  7431. * @see BABYLON.AbstractMesh
  7432. * @type {BABYLON.AbstractMesh[]}
  7433. */
  7434. this.meshes = new Array();
  7435. // Geometries
  7436. this._geometries = new Array();
  7437. this.materials = new Array();
  7438. this.multiMaterials = new Array();
  7439. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7440. // Textures
  7441. this.texturesEnabled = true;
  7442. this.textures = new Array();
  7443. // Particles
  7444. this.particlesEnabled = true;
  7445. this.particleSystems = new Array();
  7446. // Sprites
  7447. this.spriteManagers = new Array();
  7448. // Layers
  7449. this.layers = new Array();
  7450. // Skeletons
  7451. this.skeletonsEnabled = true;
  7452. this.skeletons = new Array();
  7453. // Lens flares
  7454. this.lensFlaresEnabled = true;
  7455. this.lensFlareSystems = new Array();
  7456. // Collisions
  7457. this.collisionsEnabled = true;
  7458. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7459. // Postprocesses
  7460. this.postProcessesEnabled = true;
  7461. // Customs render targets
  7462. this.renderTargetsEnabled = true;
  7463. this.customRenderTargets = new Array();
  7464. // Imported meshes
  7465. this.importedMeshesFiles = new Array();
  7466. this._actionManagers = new Array();
  7467. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7468. // Procedural textures
  7469. this.proceduralTexturesEnabled = true;
  7470. this._proceduralTextures = new Array();
  7471. this.soundTracks = new Array();
  7472. this._totalVertices = 0;
  7473. this._activeVertices = 0;
  7474. this._activeParticles = 0;
  7475. this._lastFrameDuration = 0;
  7476. this._evaluateActiveMeshesDuration = 0;
  7477. this._renderTargetsDuration = 0;
  7478. this._particlesDuration = 0;
  7479. this._renderDuration = 0;
  7480. this._spritesDuration = 0;
  7481. this._animationRatio = 0;
  7482. this._renderId = 0;
  7483. this._executeWhenReadyTimeoutId = -1;
  7484. this._toBeDisposed = new BABYLON.SmartArray(256);
  7485. this._onReadyCallbacks = new Array();
  7486. this._pendingData = []; //ANY
  7487. this._onBeforeRenderCallbacks = new Array();
  7488. this._onAfterRenderCallbacks = new Array();
  7489. this._activeMeshes = new BABYLON.SmartArray(256);
  7490. this._processedMaterials = new BABYLON.SmartArray(256);
  7491. this._renderTargets = new BABYLON.SmartArray(256);
  7492. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7493. this._activeSkeletons = new BABYLON.SmartArray(32);
  7494. this._activeBones = 0;
  7495. this._activeAnimatables = new Array();
  7496. this._transformMatrix = BABYLON.Matrix.Zero();
  7497. this._scaledPosition = BABYLON.Vector3.Zero();
  7498. this._scaledVelocity = BABYLON.Vector3.Zero();
  7499. this._engine = engine;
  7500. engine.scenes.push(this);
  7501. this._renderingManager = new BABYLON.RenderingManager(this);
  7502. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7503. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7504. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7505. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7506. this.attachControl();
  7507. this._debugLayer = new BABYLON.DebugLayer(this);
  7508. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7509. }
  7510. Object.defineProperty(Scene.prototype, "debugLayer", {
  7511. // Properties
  7512. get: function () {
  7513. return this._debugLayer;
  7514. },
  7515. enumerable: true,
  7516. configurable: true
  7517. });
  7518. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7519. /**
  7520. * The mesh that is currently under the pointer.
  7521. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  7522. */
  7523. get: function () {
  7524. return this._meshUnderPointer;
  7525. },
  7526. enumerable: true,
  7527. configurable: true
  7528. });
  7529. Object.defineProperty(Scene.prototype, "pointerX", {
  7530. /**
  7531. * Current on-screen X position of the pointer
  7532. * @return {number} X position of the pointer
  7533. */
  7534. get: function () {
  7535. return this._pointerX;
  7536. },
  7537. enumerable: true,
  7538. configurable: true
  7539. });
  7540. Object.defineProperty(Scene.prototype, "pointerY", {
  7541. /**
  7542. * Current on-screen Y position of the pointer
  7543. * @return {number} Y position of the pointer
  7544. */
  7545. get: function () {
  7546. return this._pointerY;
  7547. },
  7548. enumerable: true,
  7549. configurable: true
  7550. });
  7551. Scene.prototype.getCachedMaterial = function () {
  7552. return this._cachedMaterial;
  7553. };
  7554. Scene.prototype.getBoundingBoxRenderer = function () {
  7555. return this._boundingBoxRenderer;
  7556. };
  7557. Scene.prototype.getOutlineRenderer = function () {
  7558. return this._outlineRenderer;
  7559. };
  7560. Scene.prototype.getEngine = function () {
  7561. return this._engine;
  7562. };
  7563. Scene.prototype.getTotalVertices = function () {
  7564. return this._totalVertices;
  7565. };
  7566. Scene.prototype.getActiveVertices = function () {
  7567. return this._activeVertices;
  7568. };
  7569. Scene.prototype.getActiveParticles = function () {
  7570. return this._activeParticles;
  7571. };
  7572. Scene.prototype.getActiveBones = function () {
  7573. return this._activeBones;
  7574. };
  7575. // Stats
  7576. Scene.prototype.getLastFrameDuration = function () {
  7577. return this._lastFrameDuration;
  7578. };
  7579. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7580. return this._evaluateActiveMeshesDuration;
  7581. };
  7582. Scene.prototype.getActiveMeshes = function () {
  7583. return this._activeMeshes;
  7584. };
  7585. Scene.prototype.getRenderTargetsDuration = function () {
  7586. return this._renderTargetsDuration;
  7587. };
  7588. Scene.prototype.getRenderDuration = function () {
  7589. return this._renderDuration;
  7590. };
  7591. Scene.prototype.getParticlesDuration = function () {
  7592. return this._particlesDuration;
  7593. };
  7594. Scene.prototype.getSpritesDuration = function () {
  7595. return this._spritesDuration;
  7596. };
  7597. Scene.prototype.getAnimationRatio = function () {
  7598. return this._animationRatio;
  7599. };
  7600. Scene.prototype.getRenderId = function () {
  7601. return this._renderId;
  7602. };
  7603. Scene.prototype.incrementRenderId = function () {
  7604. this._renderId++;
  7605. };
  7606. Scene.prototype._updatePointerPosition = function (evt) {
  7607. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7608. this._pointerX = evt.clientX - canvasRect.left;
  7609. this._pointerY = evt.clientY - canvasRect.top;
  7610. if (this.cameraToUseForPointers) {
  7611. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7612. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7613. }
  7614. };
  7615. // Pointers handling
  7616. Scene.prototype.attachControl = function () {
  7617. var _this = this;
  7618. this._onPointerMove = function (evt) {
  7619. var canvas = _this._engine.getRenderingCanvas();
  7620. _this._updatePointerPosition(evt);
  7621. 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);
  7622. if (pickResult.hit) {
  7623. _this._meshUnderPointer = pickResult.pickedMesh;
  7624. _this.setPointerOverMesh(pickResult.pickedMesh);
  7625. canvas.style.cursor = "pointer";
  7626. }
  7627. else {
  7628. _this.setPointerOverMesh(null);
  7629. canvas.style.cursor = "";
  7630. _this._meshUnderPointer = null;
  7631. }
  7632. };
  7633. this._onPointerDown = function (evt) {
  7634. var predicate = null;
  7635. if (!_this.onPointerDown) {
  7636. predicate = function (mesh) {
  7637. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7638. };
  7639. }
  7640. _this._updatePointerPosition(evt);
  7641. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7642. if (pickResult.hit) {
  7643. if (pickResult.pickedMesh.actionManager) {
  7644. switch (evt.button) {
  7645. case 0:
  7646. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7647. break;
  7648. case 1:
  7649. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7650. break;
  7651. case 2:
  7652. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7653. break;
  7654. }
  7655. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7656. }
  7657. }
  7658. if (_this.onPointerDown) {
  7659. _this.onPointerDown(evt, pickResult);
  7660. }
  7661. };
  7662. this._onKeyDown = function (evt) {
  7663. if (_this.actionManager) {
  7664. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7665. }
  7666. };
  7667. this._onKeyUp = function (evt) {
  7668. if (_this.actionManager) {
  7669. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7670. }
  7671. };
  7672. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7673. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7674. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7675. BABYLON.Tools.RegisterTopRootEvents([
  7676. { name: "keydown", handler: this._onKeyDown },
  7677. { name: "keyup", handler: this._onKeyUp }
  7678. ]);
  7679. };
  7680. Scene.prototype.detachControl = function () {
  7681. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7682. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7683. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7684. BABYLON.Tools.UnregisterTopRootEvents([
  7685. { name: "keydown", handler: this._onKeyDown },
  7686. { name: "keyup", handler: this._onKeyUp }
  7687. ]);
  7688. };
  7689. // Ready
  7690. Scene.prototype.isReady = function () {
  7691. if (this._pendingData.length > 0) {
  7692. return false;
  7693. }
  7694. for (var index = 0; index < this._geometries.length; index++) {
  7695. var geometry = this._geometries[index];
  7696. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7697. return false;
  7698. }
  7699. }
  7700. for (index = 0; index < this.meshes.length; index++) {
  7701. var mesh = this.meshes[index];
  7702. if (!mesh.isReady()) {
  7703. return false;
  7704. }
  7705. var mat = mesh.material;
  7706. if (mat) {
  7707. if (!mat.isReady(mesh)) {
  7708. return false;
  7709. }
  7710. }
  7711. }
  7712. return true;
  7713. };
  7714. Scene.prototype.resetCachedMaterial = function () {
  7715. this._cachedMaterial = null;
  7716. };
  7717. Scene.prototype.registerBeforeRender = function (func) {
  7718. this._onBeforeRenderCallbacks.push(func);
  7719. };
  7720. Scene.prototype.unregisterBeforeRender = function (func) {
  7721. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7722. if (index > -1) {
  7723. this._onBeforeRenderCallbacks.splice(index, 1);
  7724. }
  7725. };
  7726. Scene.prototype.registerAfterRender = function (func) {
  7727. this._onAfterRenderCallbacks.push(func);
  7728. };
  7729. Scene.prototype.unregisterAfterRender = function (func) {
  7730. var index = this._onAfterRenderCallbacks.indexOf(func);
  7731. if (index > -1) {
  7732. this._onAfterRenderCallbacks.splice(index, 1);
  7733. }
  7734. };
  7735. Scene.prototype._addPendingData = function (data) {
  7736. this._pendingData.push(data);
  7737. };
  7738. Scene.prototype._removePendingData = function (data) {
  7739. var index = this._pendingData.indexOf(data);
  7740. if (index !== -1) {
  7741. this._pendingData.splice(index, 1);
  7742. }
  7743. };
  7744. Scene.prototype.getWaitingItemsCount = function () {
  7745. return this._pendingData.length;
  7746. };
  7747. /**
  7748. * Registers a function to be executed when the scene is ready.
  7749. * @param {Function} func - the function to be executed.
  7750. */
  7751. Scene.prototype.executeWhenReady = function (func) {
  7752. var _this = this;
  7753. this._onReadyCallbacks.push(func);
  7754. if (this._executeWhenReadyTimeoutId !== -1) {
  7755. return;
  7756. }
  7757. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7758. _this._checkIsReady();
  7759. }, 150);
  7760. };
  7761. Scene.prototype._checkIsReady = function () {
  7762. var _this = this;
  7763. if (this.isReady()) {
  7764. this._onReadyCallbacks.forEach(function (func) {
  7765. func();
  7766. });
  7767. this._onReadyCallbacks = [];
  7768. this._executeWhenReadyTimeoutId = -1;
  7769. return;
  7770. }
  7771. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7772. _this._checkIsReady();
  7773. }, 150);
  7774. };
  7775. // Animations
  7776. /**
  7777. * Will start the animation sequence of a given target
  7778. * @param target - the target
  7779. * @param {number} from - from which frame should animation start
  7780. * @param {number} to - till which frame should animation run.
  7781. * @param {boolean} [loop] - should the animation loop
  7782. * @param {number} [speedRatio] - the speed in which to run the animation
  7783. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  7784. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  7785. * @return {BABYLON.Animatable} the animatable object created for this animation
  7786. * @see BABYLON.Animatable
  7787. * @see http://doc.babylonjs.com/page.php?p=22081
  7788. */
  7789. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7790. if (speedRatio === undefined) {
  7791. speedRatio = 1.0;
  7792. }
  7793. this.stopAnimation(target);
  7794. if (!animatable) {
  7795. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7796. }
  7797. // Local animations
  7798. if (target.animations) {
  7799. animatable.appendAnimations(target, target.animations);
  7800. }
  7801. // Children animations
  7802. if (target.getAnimatables) {
  7803. var animatables = target.getAnimatables();
  7804. for (var index = 0; index < animatables.length; index++) {
  7805. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7806. }
  7807. }
  7808. return animatable;
  7809. };
  7810. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7811. if (speedRatio === undefined) {
  7812. speedRatio = 1.0;
  7813. }
  7814. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7815. return animatable;
  7816. };
  7817. Scene.prototype.getAnimatableByTarget = function (target) {
  7818. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7819. if (this._activeAnimatables[index].target === target) {
  7820. return this._activeAnimatables[index];
  7821. }
  7822. }
  7823. return null;
  7824. };
  7825. /**
  7826. * Will stop the animation of the given target
  7827. * @param target - the target
  7828. * @see beginAnimation
  7829. */
  7830. Scene.prototype.stopAnimation = function (target) {
  7831. var animatable = this.getAnimatableByTarget(target);
  7832. if (animatable) {
  7833. animatable.stop();
  7834. }
  7835. };
  7836. Scene.prototype._animate = function () {
  7837. if (!this.animationsEnabled) {
  7838. return;
  7839. }
  7840. if (!this._animationStartDate) {
  7841. this._animationStartDate = BABYLON.Tools.Now;
  7842. }
  7843. // Getting time
  7844. var now = BABYLON.Tools.Now;
  7845. var delay = now - this._animationStartDate;
  7846. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7847. if (!this._activeAnimatables[index]._animate(delay)) {
  7848. this._activeAnimatables.splice(index, 1);
  7849. index--;
  7850. }
  7851. }
  7852. };
  7853. // Matrix
  7854. Scene.prototype.getViewMatrix = function () {
  7855. return this._viewMatrix;
  7856. };
  7857. Scene.prototype.getProjectionMatrix = function () {
  7858. return this._projectionMatrix;
  7859. };
  7860. Scene.prototype.getTransformMatrix = function () {
  7861. return this._transformMatrix;
  7862. };
  7863. Scene.prototype.setTransformMatrix = function (view, projection) {
  7864. this._viewMatrix = view;
  7865. this._projectionMatrix = projection;
  7866. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7867. };
  7868. // Methods
  7869. /**
  7870. * sets the active camera of the scene using its ID
  7871. * @param {string} id - the camera's ID
  7872. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  7873. * @see activeCamera
  7874. */
  7875. Scene.prototype.setActiveCameraByID = function (id) {
  7876. var camera = this.getCameraByID(id);
  7877. if (camera) {
  7878. this.activeCamera = camera;
  7879. return camera;
  7880. }
  7881. return null;
  7882. };
  7883. /**
  7884. * sets the active camera of the scene using its name
  7885. * @param {string} name - the camera's name
  7886. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  7887. * @see activeCamera
  7888. */
  7889. Scene.prototype.setActiveCameraByName = function (name) {
  7890. var camera = this.getCameraByName(name);
  7891. if (camera) {
  7892. this.activeCamera = camera;
  7893. return camera;
  7894. }
  7895. return null;
  7896. };
  7897. /**
  7898. * get a material using its id
  7899. * @param {string} the material's ID
  7900. * @return {BABYLON.Material|null} the material or null if none found.
  7901. */
  7902. Scene.prototype.getMaterialByID = function (id) {
  7903. for (var index = 0; index < this.materials.length; index++) {
  7904. if (this.materials[index].id === id) {
  7905. return this.materials[index];
  7906. }
  7907. }
  7908. return null;
  7909. };
  7910. /**
  7911. * get a material using its name
  7912. * @param {string} the material's name
  7913. * @return {BABYLON.Material|null} the material or null if none found.
  7914. */
  7915. Scene.prototype.getMaterialByName = function (name) {
  7916. for (var index = 0; index < this.materials.length; index++) {
  7917. if (this.materials[index].name === name) {
  7918. return this.materials[index];
  7919. }
  7920. }
  7921. return null;
  7922. };
  7923. Scene.prototype.getCameraByID = function (id) {
  7924. for (var index = 0; index < this.cameras.length; index++) {
  7925. if (this.cameras[index].id === id) {
  7926. return this.cameras[index];
  7927. }
  7928. }
  7929. return null;
  7930. };
  7931. /**
  7932. * get a camera using its name
  7933. * @param {string} the camera's name
  7934. * @return {BABYLON.Camera|null} the camera or null if none found.
  7935. */
  7936. Scene.prototype.getCameraByName = function (name) {
  7937. for (var index = 0; index < this.cameras.length; index++) {
  7938. if (this.cameras[index].name === name) {
  7939. return this.cameras[index];
  7940. }
  7941. }
  7942. return null;
  7943. };
  7944. /**
  7945. * get a light node using its name
  7946. * @param {string} the light's name
  7947. * @return {BABYLON.Light|null} the light or null if none found.
  7948. */
  7949. Scene.prototype.getLightByName = function (name) {
  7950. for (var index = 0; index < this.lights.length; index++) {
  7951. if (this.lights[index].name === name) {
  7952. return this.lights[index];
  7953. }
  7954. }
  7955. return null;
  7956. };
  7957. /**
  7958. * get a light node using its ID
  7959. * @param {string} the light's id
  7960. * @return {BABYLON.Light|null} the light or null if none found.
  7961. */
  7962. Scene.prototype.getLightByID = function (id) {
  7963. for (var index = 0; index < this.lights.length; index++) {
  7964. if (this.lights[index].id === id) {
  7965. return this.lights[index];
  7966. }
  7967. }
  7968. return null;
  7969. };
  7970. /**
  7971. * get a geometry using its ID
  7972. * @param {string} the geometry's id
  7973. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  7974. */
  7975. Scene.prototype.getGeometryByID = function (id) {
  7976. for (var index = 0; index < this._geometries.length; index++) {
  7977. if (this._geometries[index].id === id) {
  7978. return this._geometries[index];
  7979. }
  7980. }
  7981. return null;
  7982. };
  7983. /**
  7984. * add a new geometry to this scene.
  7985. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  7986. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  7987. * @return {boolean} was the geometry added or not
  7988. */
  7989. Scene.prototype.pushGeometry = function (geometry, force) {
  7990. if (!force && this.getGeometryByID(geometry.id)) {
  7991. return false;
  7992. }
  7993. this._geometries.push(geometry);
  7994. return true;
  7995. };
  7996. Scene.prototype.getGeometries = function () {
  7997. return this._geometries;
  7998. };
  7999. /**
  8000. * Get a the first added mesh found of a given ID
  8001. * @param {string} id - the id to search for
  8002. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8003. */
  8004. Scene.prototype.getMeshByID = function (id) {
  8005. for (var index = 0; index < this.meshes.length; index++) {
  8006. if (this.meshes[index].id === id) {
  8007. return this.meshes[index];
  8008. }
  8009. }
  8010. return null;
  8011. };
  8012. /**
  8013. * Get a the last added mesh found of a given ID
  8014. * @param {string} id - the id to search for
  8015. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8016. */
  8017. Scene.prototype.getLastMeshByID = function (id) {
  8018. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8019. if (this.meshes[index].id === id) {
  8020. return this.meshes[index];
  8021. }
  8022. }
  8023. return null;
  8024. };
  8025. /**
  8026. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8027. * @param {string} id - the id to search for
  8028. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8029. */
  8030. Scene.prototype.getLastEntryByID = function (id) {
  8031. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8032. if (this.meshes[index].id === id) {
  8033. return this.meshes[index];
  8034. }
  8035. }
  8036. for (index = this.cameras.length - 1; index >= 0; index--) {
  8037. if (this.cameras[index].id === id) {
  8038. return this.cameras[index];
  8039. }
  8040. }
  8041. for (index = this.lights.length - 1; index >= 0; index--) {
  8042. if (this.lights[index].id === id) {
  8043. return this.lights[index];
  8044. }
  8045. }
  8046. return null;
  8047. };
  8048. Scene.prototype.getNodeByName = function (name) {
  8049. var mesh = this.getMeshByName(name);
  8050. if (mesh) {
  8051. return mesh;
  8052. }
  8053. var light = this.getLightByName(name);
  8054. if (light) {
  8055. return light;
  8056. }
  8057. return this.getCameraByName(name);
  8058. };
  8059. Scene.prototype.getMeshByName = function (name) {
  8060. for (var index = 0; index < this.meshes.length; index++) {
  8061. if (this.meshes[index].name === name) {
  8062. return this.meshes[index];
  8063. }
  8064. }
  8065. return null;
  8066. };
  8067. Scene.prototype.getSoundByName = function (name) {
  8068. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8069. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8070. return this.mainSoundTrack.soundCollection[index];
  8071. }
  8072. }
  8073. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8074. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8075. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8076. return this.soundTracks[sdIndex].soundCollection[index];
  8077. }
  8078. }
  8079. }
  8080. return null;
  8081. };
  8082. Scene.prototype.getLastSkeletonByID = function (id) {
  8083. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8084. if (this.skeletons[index].id === id) {
  8085. return this.skeletons[index];
  8086. }
  8087. }
  8088. return null;
  8089. };
  8090. Scene.prototype.getSkeletonById = function (id) {
  8091. for (var index = 0; index < this.skeletons.length; index++) {
  8092. if (this.skeletons[index].id === id) {
  8093. return this.skeletons[index];
  8094. }
  8095. }
  8096. return null;
  8097. };
  8098. Scene.prototype.getSkeletonByName = function (name) {
  8099. for (var index = 0; index < this.skeletons.length; index++) {
  8100. if (this.skeletons[index].name === name) {
  8101. return this.skeletons[index];
  8102. }
  8103. }
  8104. return null;
  8105. };
  8106. Scene.prototype.isActiveMesh = function (mesh) {
  8107. return (this._activeMeshes.indexOf(mesh) !== -1);
  8108. };
  8109. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8110. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8111. var material = subMesh.getMaterial();
  8112. if (mesh.showSubMeshesBoundingBox) {
  8113. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8114. }
  8115. if (material) {
  8116. // Render targets
  8117. if (material.getRenderTargetTextures) {
  8118. if (this._processedMaterials.indexOf(material) === -1) {
  8119. this._processedMaterials.push(material);
  8120. this._renderTargets.concat(material.getRenderTargetTextures());
  8121. }
  8122. }
  8123. // Dispatch
  8124. this._activeVertices += subMesh.indexCount;
  8125. this._renderingManager.dispatch(subMesh);
  8126. }
  8127. }
  8128. };
  8129. Scene.prototype._evaluateActiveMeshes = function () {
  8130. this._activeMeshes.reset();
  8131. this._renderingManager.reset();
  8132. this._processedMaterials.reset();
  8133. this._activeParticleSystems.reset();
  8134. this._activeSkeletons.reset();
  8135. this._boundingBoxRenderer.reset();
  8136. if (!this._frustumPlanes) {
  8137. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8138. }
  8139. else {
  8140. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8141. }
  8142. // Meshes
  8143. var meshes;
  8144. var len;
  8145. if (this._selectionOctree) {
  8146. var selection = this._selectionOctree.select(this._frustumPlanes);
  8147. meshes = selection.data;
  8148. len = selection.length;
  8149. }
  8150. else {
  8151. len = this.meshes.length;
  8152. meshes = this.meshes;
  8153. }
  8154. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8155. var mesh = meshes[meshIndex];
  8156. if (mesh.isBlocked) {
  8157. continue;
  8158. }
  8159. this._totalVertices += mesh.getTotalVertices();
  8160. if (!mesh.isReady()) {
  8161. continue;
  8162. }
  8163. mesh.computeWorldMatrix();
  8164. // Intersections
  8165. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8166. this._meshesForIntersections.pushNoDuplicate(mesh);
  8167. }
  8168. // Switch to current LOD
  8169. var meshLOD = mesh.getLOD(this.activeCamera);
  8170. if (!meshLOD) {
  8171. continue;
  8172. }
  8173. mesh._preActivate();
  8174. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8175. this._activeMeshes.push(mesh);
  8176. mesh._activate(this._renderId);
  8177. this._activeMesh(meshLOD);
  8178. }
  8179. }
  8180. // Particle systems
  8181. var beforeParticlesDate = BABYLON.Tools.Now;
  8182. if (this.particlesEnabled) {
  8183. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8184. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8185. var particleSystem = this.particleSystems[particleIndex];
  8186. if (!particleSystem.isStarted()) {
  8187. continue;
  8188. }
  8189. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8190. this._activeParticleSystems.push(particleSystem);
  8191. particleSystem.animate();
  8192. }
  8193. }
  8194. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8195. }
  8196. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8197. };
  8198. Scene.prototype._activeMesh = function (mesh) {
  8199. if (mesh.skeleton && this.skeletonsEnabled) {
  8200. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8201. }
  8202. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8203. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8204. }
  8205. if (mesh && mesh.subMeshes) {
  8206. // Submeshes Octrees
  8207. var len;
  8208. var subMeshes;
  8209. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8210. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8211. len = intersections.length;
  8212. subMeshes = intersections.data;
  8213. }
  8214. else {
  8215. subMeshes = mesh.subMeshes;
  8216. len = subMeshes.length;
  8217. }
  8218. for (var subIndex = 0; subIndex < len; subIndex++) {
  8219. var subMesh = subMeshes[subIndex];
  8220. this._evaluateSubMesh(subMesh, mesh);
  8221. }
  8222. }
  8223. };
  8224. Scene.prototype.updateTransformMatrix = function (force) {
  8225. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8226. };
  8227. Scene.prototype._renderForCamera = function (camera) {
  8228. var engine = this._engine;
  8229. this.activeCamera = camera;
  8230. if (!this.activeCamera)
  8231. throw new Error("Active camera not set");
  8232. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8233. // Viewport
  8234. engine.setViewport(this.activeCamera.viewport);
  8235. // Camera
  8236. this._renderId++;
  8237. this.updateTransformMatrix();
  8238. if (this.beforeCameraRender) {
  8239. this.beforeCameraRender(this.activeCamera);
  8240. }
  8241. // Meshes
  8242. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8243. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8244. this._evaluateActiveMeshes();
  8245. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8246. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8247. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8248. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8249. skeleton.prepare();
  8250. this._activeBones += skeleton.bones.length;
  8251. }
  8252. // Render targets
  8253. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8254. if (this.renderTargetsEnabled) {
  8255. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8256. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8257. var renderTarget = this._renderTargets.data[renderIndex];
  8258. if (renderTarget._shouldRender()) {
  8259. this._renderId++;
  8260. renderTarget.render();
  8261. }
  8262. }
  8263. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8264. this._renderId++;
  8265. }
  8266. if (this._renderTargets.length > 0) {
  8267. engine.restoreDefaultFramebuffer();
  8268. }
  8269. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8270. // Prepare Frame
  8271. this.postProcessManager._prepareFrame();
  8272. var beforeRenderDate = BABYLON.Tools.Now;
  8273. // Backgrounds
  8274. if (this.layers.length) {
  8275. engine.setDepthBuffer(false);
  8276. var layerIndex;
  8277. var layer;
  8278. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8279. layer = this.layers[layerIndex];
  8280. if (layer.isBackground) {
  8281. layer.render();
  8282. }
  8283. }
  8284. engine.setDepthBuffer(true);
  8285. }
  8286. // Render
  8287. BABYLON.Tools.StartPerformanceCounter("Main render");
  8288. this._renderingManager.render(null, null, true, true);
  8289. BABYLON.Tools.EndPerformanceCounter("Main render");
  8290. // Bounding boxes
  8291. this._boundingBoxRenderer.render();
  8292. // Lens flares
  8293. if (this.lensFlaresEnabled) {
  8294. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8295. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8296. this.lensFlareSystems[lensFlareSystemIndex].render();
  8297. }
  8298. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8299. }
  8300. // Foregrounds
  8301. if (this.layers.length) {
  8302. engine.setDepthBuffer(false);
  8303. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8304. layer = this.layers[layerIndex];
  8305. if (!layer.isBackground) {
  8306. layer.render();
  8307. }
  8308. }
  8309. engine.setDepthBuffer(true);
  8310. }
  8311. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8312. // Finalize frame
  8313. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8314. // Update camera
  8315. this.activeCamera._updateFromScene();
  8316. // Reset some special arrays
  8317. this._renderTargets.reset();
  8318. if (this.afterCameraRender) {
  8319. this.afterCameraRender(this.activeCamera);
  8320. }
  8321. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8322. };
  8323. Scene.prototype._processSubCameras = function (camera) {
  8324. if (camera.subCameras.length === 0) {
  8325. this._renderForCamera(camera);
  8326. return;
  8327. }
  8328. for (var index = 0; index < camera.subCameras.length; index++) {
  8329. this._renderForCamera(camera.subCameras[index]);
  8330. }
  8331. this.activeCamera = camera;
  8332. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8333. // Update camera
  8334. this.activeCamera._updateFromScene();
  8335. };
  8336. Scene.prototype._checkIntersections = function () {
  8337. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8338. var sourceMesh = this._meshesForIntersections.data[index];
  8339. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8340. var action = sourceMesh.actionManager.actions[actionIndex];
  8341. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8342. var parameters = action.getTriggerParameter();
  8343. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  8344. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  8345. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8346. if (areIntersecting && currentIntersectionInProgress === -1) {
  8347. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8348. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8349. sourceMesh._intersectionsInProgress.push(otherMesh);
  8350. }
  8351. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8352. sourceMesh._intersectionsInProgress.push(otherMesh);
  8353. }
  8354. }
  8355. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8356. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8357. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8358. if (indexOfOther > -1) {
  8359. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8360. }
  8361. }
  8362. }
  8363. }
  8364. }
  8365. };
  8366. Scene.prototype.render = function () {
  8367. var startDate = BABYLON.Tools.Now;
  8368. this._particlesDuration = 0;
  8369. this._spritesDuration = 0;
  8370. this._activeParticles = 0;
  8371. this._renderDuration = 0;
  8372. this._renderTargetsDuration = 0;
  8373. this._evaluateActiveMeshesDuration = 0;
  8374. this._totalVertices = 0;
  8375. this._activeVertices = 0;
  8376. this._activeBones = 0;
  8377. this.getEngine().resetDrawCalls();
  8378. this._meshesForIntersections.reset();
  8379. this.resetCachedMaterial();
  8380. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8381. // Actions
  8382. if (this.actionManager) {
  8383. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8384. }
  8385. // Before render
  8386. if (this.beforeRender) {
  8387. this.beforeRender();
  8388. }
  8389. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8390. this._onBeforeRenderCallbacks[callbackIndex]();
  8391. }
  8392. // Animations
  8393. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8394. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8395. this._animate();
  8396. // Physics
  8397. if (this._physicsEngine) {
  8398. BABYLON.Tools.StartPerformanceCounter("Physics");
  8399. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8400. BABYLON.Tools.EndPerformanceCounter("Physics");
  8401. }
  8402. // Customs render targets
  8403. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8404. var engine = this.getEngine();
  8405. if (this.renderTargetsEnabled) {
  8406. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8407. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8408. var renderTarget = this.customRenderTargets[customIndex];
  8409. if (renderTarget._shouldRender()) {
  8410. this._renderId++;
  8411. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8412. if (!this.activeCamera)
  8413. throw new Error("Active camera not set");
  8414. // Viewport
  8415. engine.setViewport(this.activeCamera.viewport);
  8416. // Camera
  8417. this.updateTransformMatrix();
  8418. renderTarget.render();
  8419. }
  8420. }
  8421. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8422. this._renderId++;
  8423. }
  8424. if (this.customRenderTargets.length > 0) {
  8425. engine.restoreDefaultFramebuffer();
  8426. }
  8427. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8428. // Procedural textures
  8429. if (this.proceduralTexturesEnabled) {
  8430. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8431. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8432. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8433. if (proceduralTexture._shouldRender()) {
  8434. proceduralTexture.render();
  8435. }
  8436. }
  8437. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8438. }
  8439. // Clear
  8440. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8441. // Shadows
  8442. if (this.shadowsEnabled) {
  8443. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8444. var light = this.lights[lightIndex];
  8445. var shadowGenerator = light.getShadowGenerator();
  8446. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8447. this._renderTargets.push(shadowGenerator.getShadowMap());
  8448. }
  8449. }
  8450. }
  8451. // Depth renderer
  8452. if (this._depthRenderer) {
  8453. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8454. }
  8455. // RenderPipeline
  8456. this.postProcessRenderPipelineManager.update();
  8457. // Multi-cameras?
  8458. if (this.activeCameras.length > 0) {
  8459. var currentRenderId = this._renderId;
  8460. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8461. this._renderId = currentRenderId;
  8462. this._processSubCameras(this.activeCameras[cameraIndex]);
  8463. }
  8464. }
  8465. else {
  8466. if (!this.activeCamera) {
  8467. throw new Error("No camera defined");
  8468. }
  8469. this._processSubCameras(this.activeCamera);
  8470. }
  8471. // Intersection checks
  8472. this._checkIntersections();
  8473. // Update the audio listener attached to the camera
  8474. this._updateAudioParameters();
  8475. // After render
  8476. if (this.afterRender) {
  8477. this.afterRender();
  8478. }
  8479. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8480. this._onAfterRenderCallbacks[callbackIndex]();
  8481. }
  8482. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8483. this._toBeDisposed.data[index].dispose();
  8484. this._toBeDisposed[index] = null;
  8485. }
  8486. this._toBeDisposed.reset();
  8487. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8488. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8489. };
  8490. Scene.prototype._updateAudioParameters = function () {
  8491. var listeningCamera;
  8492. var audioEngine = BABYLON.Engine.audioEngine;
  8493. if (this.activeCameras.length > 0) {
  8494. listeningCamera = this.activeCameras[0];
  8495. }
  8496. else {
  8497. listeningCamera = this.activeCamera;
  8498. }
  8499. if (listeningCamera && audioEngine.canUseWebAudio) {
  8500. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8501. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8502. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8503. cameraDirection.normalize();
  8504. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8505. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8506. var sound = this.mainSoundTrack.soundCollection[i];
  8507. if (sound.useCustomAttenuation) {
  8508. sound.updateDistanceFromListener();
  8509. }
  8510. }
  8511. for (i = 0; i < this.soundTracks.length; i++) {
  8512. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8513. sound = this.soundTracks[i].soundCollection[j];
  8514. if (sound.useCustomAttenuation) {
  8515. sound.updateDistanceFromListener();
  8516. }
  8517. }
  8518. }
  8519. }
  8520. };
  8521. Scene.prototype.enableDepthRenderer = function () {
  8522. if (this._depthRenderer) {
  8523. return this._depthRenderer;
  8524. }
  8525. this._depthRenderer = new BABYLON.DepthRenderer(this);
  8526. return this._depthRenderer;
  8527. };
  8528. Scene.prototype.disableDepthRenderer = function () {
  8529. if (!this._depthRenderer) {
  8530. return;
  8531. }
  8532. this._depthRenderer.dispose();
  8533. this._depthRenderer = null;
  8534. };
  8535. Scene.prototype.dispose = function () {
  8536. this.beforeRender = null;
  8537. this.afterRender = null;
  8538. this.skeletons = [];
  8539. this._boundingBoxRenderer.dispose();
  8540. if (this._depthRenderer) {
  8541. this._depthRenderer.dispose();
  8542. }
  8543. // Debug layer
  8544. this.debugLayer.hide();
  8545. // Events
  8546. if (this.onDispose) {
  8547. this.onDispose();
  8548. }
  8549. this._onBeforeRenderCallbacks = [];
  8550. this._onAfterRenderCallbacks = [];
  8551. this.detachControl();
  8552. // Release sounds & sounds tracks
  8553. this.mainSoundTrack.dispose();
  8554. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  8555. this.soundTracks[scIndex].dispose();
  8556. }
  8557. // Detach cameras
  8558. var canvas = this._engine.getRenderingCanvas();
  8559. var index;
  8560. for (index = 0; index < this.cameras.length; index++) {
  8561. this.cameras[index].detachControl(canvas);
  8562. }
  8563. while (this.lights.length) {
  8564. this.lights[0].dispose();
  8565. }
  8566. while (this.meshes.length) {
  8567. this.meshes[0].dispose(true);
  8568. }
  8569. while (this.cameras.length) {
  8570. this.cameras[0].dispose();
  8571. }
  8572. while (this.materials.length) {
  8573. this.materials[0].dispose();
  8574. }
  8575. while (this.particleSystems.length) {
  8576. this.particleSystems[0].dispose();
  8577. }
  8578. while (this.spriteManagers.length) {
  8579. this.spriteManagers[0].dispose();
  8580. }
  8581. while (this.layers.length) {
  8582. this.layers[0].dispose();
  8583. }
  8584. while (this.textures.length) {
  8585. this.textures[0].dispose();
  8586. }
  8587. // Post-processes
  8588. this.postProcessManager.dispose();
  8589. // Physics
  8590. if (this._physicsEngine) {
  8591. this.disablePhysicsEngine();
  8592. }
  8593. // Remove from engine
  8594. index = this._engine.scenes.indexOf(this);
  8595. if (index > -1) {
  8596. this._engine.scenes.splice(index, 1);
  8597. }
  8598. this._engine.wipeCaches();
  8599. };
  8600. // Collisions
  8601. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8602. if (excludedMesh === void 0) { excludedMesh = null; }
  8603. position.divideToRef(collider.radius, this._scaledPosition);
  8604. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8605. collider.retry = 0;
  8606. collider.initialVelocity = this._scaledVelocity;
  8607. collider.initialPosition = this._scaledPosition;
  8608. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8609. finalPosition.multiplyInPlace(collider.radius);
  8610. };
  8611. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8612. if (excludedMesh === void 0) { excludedMesh = null; }
  8613. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8614. if (collider.retry >= maximumRetry) {
  8615. finalPosition.copyFrom(position);
  8616. return;
  8617. }
  8618. collider._initialize(position, velocity, closeDistance);
  8619. for (var index = 0; index < this.meshes.length; index++) {
  8620. var mesh = this.meshes[index];
  8621. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8622. mesh._checkCollision(collider);
  8623. }
  8624. }
  8625. if (!collider.collisionFound) {
  8626. position.addToRef(velocity, finalPosition);
  8627. return;
  8628. }
  8629. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8630. collider._getResponse(position, velocity);
  8631. }
  8632. if (velocity.length() <= closeDistance) {
  8633. finalPosition.copyFrom(position);
  8634. return;
  8635. }
  8636. collider.retry++;
  8637. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8638. };
  8639. // Octrees
  8640. Scene.prototype.getWorldExtends = function () {
  8641. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8642. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8643. for (var index = 0; index < this.meshes.length; index++) {
  8644. var mesh = this.meshes[index];
  8645. mesh.computeWorldMatrix(true);
  8646. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8647. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8648. BABYLON.Tools.CheckExtends(minBox, min, max);
  8649. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8650. }
  8651. return {
  8652. min: min,
  8653. max: max
  8654. };
  8655. };
  8656. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8657. if (maxCapacity === void 0) { maxCapacity = 64; }
  8658. if (maxDepth === void 0) { maxDepth = 2; }
  8659. if (!this._selectionOctree) {
  8660. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8661. }
  8662. var worldExtends = this.getWorldExtends();
  8663. // Update octree
  8664. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  8665. return this._selectionOctree;
  8666. };
  8667. // Picking
  8668. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8669. var engine = this._engine;
  8670. if (!camera) {
  8671. if (!this.activeCamera)
  8672. throw new Error("Active camera not set");
  8673. camera = this.activeCamera;
  8674. }
  8675. var cameraViewport = camera.viewport;
  8676. var viewport = cameraViewport.toGlobal(engine);
  8677. // Moving coordinates to local viewport world
  8678. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8679. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8680. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8681. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8682. };
  8683. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8684. var pickingInfo = null;
  8685. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8686. var mesh = this.meshes[meshIndex];
  8687. if (predicate) {
  8688. if (!predicate(mesh)) {
  8689. continue;
  8690. }
  8691. }
  8692. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8693. continue;
  8694. }
  8695. var world = mesh.getWorldMatrix();
  8696. var ray = rayFunction(world);
  8697. var result = mesh.intersects(ray, fastCheck);
  8698. if (!result || !result.hit)
  8699. continue;
  8700. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8701. continue;
  8702. pickingInfo = result;
  8703. if (fastCheck) {
  8704. break;
  8705. }
  8706. }
  8707. return pickingInfo || new BABYLON.PickingInfo();
  8708. };
  8709. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8710. var _this = this;
  8711. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8712. /// <param name="x">X position on screen</param>
  8713. /// <param name="y">Y position on screen</param>
  8714. /// <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>
  8715. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8716. /// <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>
  8717. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  8718. };
  8719. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8720. var _this = this;
  8721. return this._internalPick(function (world) {
  8722. if (!_this._pickWithRayInverseMatrix) {
  8723. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8724. }
  8725. world.invertToRef(_this._pickWithRayInverseMatrix);
  8726. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8727. }, predicate, fastCheck);
  8728. };
  8729. Scene.prototype.setPointerOverMesh = function (mesh) {
  8730. if (this._pointerOverMesh === mesh) {
  8731. return;
  8732. }
  8733. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8734. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8735. }
  8736. this._pointerOverMesh = mesh;
  8737. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8738. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8739. }
  8740. };
  8741. Scene.prototype.getPointerOverMesh = function () {
  8742. return this._pointerOverMesh;
  8743. };
  8744. // Physics
  8745. Scene.prototype.getPhysicsEngine = function () {
  8746. return this._physicsEngine;
  8747. };
  8748. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8749. if (this._physicsEngine) {
  8750. return true;
  8751. }
  8752. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8753. if (!this._physicsEngine.isSupported()) {
  8754. this._physicsEngine = null;
  8755. return false;
  8756. }
  8757. this._physicsEngine._initialize(gravity);
  8758. return true;
  8759. };
  8760. Scene.prototype.disablePhysicsEngine = function () {
  8761. if (!this._physicsEngine) {
  8762. return;
  8763. }
  8764. this._physicsEngine.dispose();
  8765. this._physicsEngine = undefined;
  8766. };
  8767. Scene.prototype.isPhysicsEnabled = function () {
  8768. return this._physicsEngine !== undefined;
  8769. };
  8770. Scene.prototype.setGravity = function (gravity) {
  8771. if (!this._physicsEngine) {
  8772. return;
  8773. }
  8774. this._physicsEngine._setGravity(gravity);
  8775. };
  8776. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8777. if (parts.parts) {
  8778. options = parts;
  8779. parts = parts.parts;
  8780. }
  8781. if (!this._physicsEngine) {
  8782. return null;
  8783. }
  8784. for (var index = 0; index < parts.length; index++) {
  8785. var mesh = parts[index].mesh;
  8786. mesh._physicImpostor = parts[index].impostor;
  8787. mesh._physicsMass = options.mass / parts.length;
  8788. mesh._physicsFriction = options.friction;
  8789. mesh._physicRestitution = options.restitution;
  8790. }
  8791. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8792. };
  8793. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8794. for (var index = 0; index < compound.parts.length; index++) {
  8795. var mesh = compound.parts[index].mesh;
  8796. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8797. this._physicsEngine._unregisterMesh(mesh);
  8798. }
  8799. };
  8800. // Misc.
  8801. Scene.prototype.createDefaultCameraOrLight = function () {
  8802. // Light
  8803. if (this.lights.length === 0) {
  8804. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  8805. }
  8806. // Camera
  8807. if (!this.activeCamera) {
  8808. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  8809. // Compute position
  8810. var worldExtends = this.getWorldExtends();
  8811. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  8812. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  8813. camera.setTarget(worldCenter);
  8814. this.activeCamera = camera;
  8815. }
  8816. };
  8817. // Tags
  8818. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  8819. if (tagsQuery === undefined) {
  8820. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8821. return list;
  8822. }
  8823. var listByTags = [];
  8824. forEach = forEach || (function (item) {
  8825. return;
  8826. });
  8827. for (var i in list) {
  8828. var item = list[i];
  8829. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8830. listByTags.push(item);
  8831. forEach(item);
  8832. }
  8833. }
  8834. return listByTags;
  8835. };
  8836. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  8837. return this._getByTags(this.meshes, tagsQuery, forEach);
  8838. };
  8839. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  8840. return this._getByTags(this.cameras, tagsQuery, forEach);
  8841. };
  8842. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  8843. return this._getByTags(this.lights, tagsQuery, forEach);
  8844. };
  8845. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  8846. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  8847. };
  8848. // Statics
  8849. Scene.FOGMODE_NONE = 0;
  8850. Scene.FOGMODE_EXP = 1;
  8851. Scene.FOGMODE_EXP2 = 2;
  8852. Scene.FOGMODE_LINEAR = 3;
  8853. Scene.MinDeltaTime = 1.0;
  8854. Scene.MaxDeltaTime = 1000.0;
  8855. return Scene;
  8856. })();
  8857. BABYLON.Scene = Scene;
  8858. })(BABYLON || (BABYLON = {}));
  8859. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  8860. (function (BABYLON) {
  8861. var VertexBuffer = (function () {
  8862. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8863. if (engine instanceof BABYLON.Mesh) {
  8864. this._engine = engine.getScene().getEngine();
  8865. }
  8866. else {
  8867. this._engine = engine;
  8868. }
  8869. this._updatable = updatable;
  8870. this._data = data;
  8871. if (!postponeInternalCreation) {
  8872. this.create();
  8873. }
  8874. this._kind = kind;
  8875. if (stride) {
  8876. this._strideSize = stride;
  8877. return;
  8878. }
  8879. switch (kind) {
  8880. case VertexBuffer.PositionKind:
  8881. this._strideSize = 3;
  8882. break;
  8883. case VertexBuffer.NormalKind:
  8884. this._strideSize = 3;
  8885. break;
  8886. case VertexBuffer.UVKind:
  8887. this._strideSize = 2;
  8888. break;
  8889. case VertexBuffer.UV2Kind:
  8890. this._strideSize = 2;
  8891. break;
  8892. case VertexBuffer.ColorKind:
  8893. this._strideSize = 4;
  8894. break;
  8895. case VertexBuffer.MatricesIndicesKind:
  8896. this._strideSize = 4;
  8897. break;
  8898. case VertexBuffer.MatricesWeightsKind:
  8899. this._strideSize = 4;
  8900. break;
  8901. }
  8902. }
  8903. // Properties
  8904. VertexBuffer.prototype.isUpdatable = function () {
  8905. return this._updatable;
  8906. };
  8907. VertexBuffer.prototype.getData = function () {
  8908. return this._data;
  8909. };
  8910. VertexBuffer.prototype.getBuffer = function () {
  8911. return this._buffer;
  8912. };
  8913. VertexBuffer.prototype.getStrideSize = function () {
  8914. return this._strideSize;
  8915. };
  8916. // Methods
  8917. VertexBuffer.prototype.create = function (data) {
  8918. if (!data && this._buffer) {
  8919. return; // nothing to do
  8920. }
  8921. data = data || this._data;
  8922. if (!this._buffer) {
  8923. if (this._updatable) {
  8924. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8925. }
  8926. else {
  8927. this._buffer = this._engine.createVertexBuffer(data);
  8928. }
  8929. }
  8930. if (this._updatable) {
  8931. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8932. this._data = data;
  8933. }
  8934. };
  8935. VertexBuffer.prototype.update = function (data) {
  8936. this.create(data);
  8937. };
  8938. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8939. if (!this._buffer) {
  8940. return;
  8941. }
  8942. if (this._updatable) {
  8943. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8944. this._data = null;
  8945. }
  8946. };
  8947. VertexBuffer.prototype.dispose = function () {
  8948. if (!this._buffer) {
  8949. return;
  8950. }
  8951. if (this._engine._releaseBuffer(this._buffer)) {
  8952. this._buffer = null;
  8953. }
  8954. };
  8955. Object.defineProperty(VertexBuffer, "PositionKind", {
  8956. get: function () {
  8957. return VertexBuffer._PositionKind;
  8958. },
  8959. enumerable: true,
  8960. configurable: true
  8961. });
  8962. Object.defineProperty(VertexBuffer, "NormalKind", {
  8963. get: function () {
  8964. return VertexBuffer._NormalKind;
  8965. },
  8966. enumerable: true,
  8967. configurable: true
  8968. });
  8969. Object.defineProperty(VertexBuffer, "UVKind", {
  8970. get: function () {
  8971. return VertexBuffer._UVKind;
  8972. },
  8973. enumerable: true,
  8974. configurable: true
  8975. });
  8976. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8977. get: function () {
  8978. return VertexBuffer._UV2Kind;
  8979. },
  8980. enumerable: true,
  8981. configurable: true
  8982. });
  8983. Object.defineProperty(VertexBuffer, "ColorKind", {
  8984. get: function () {
  8985. return VertexBuffer._ColorKind;
  8986. },
  8987. enumerable: true,
  8988. configurable: true
  8989. });
  8990. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  8991. get: function () {
  8992. return VertexBuffer._MatricesIndicesKind;
  8993. },
  8994. enumerable: true,
  8995. configurable: true
  8996. });
  8997. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  8998. get: function () {
  8999. return VertexBuffer._MatricesWeightsKind;
  9000. },
  9001. enumerable: true,
  9002. configurable: true
  9003. });
  9004. // Enums
  9005. VertexBuffer._PositionKind = "position";
  9006. VertexBuffer._NormalKind = "normal";
  9007. VertexBuffer._UVKind = "uv";
  9008. VertexBuffer._UV2Kind = "uv2";
  9009. VertexBuffer._ColorKind = "color";
  9010. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9011. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9012. return VertexBuffer;
  9013. })();
  9014. BABYLON.VertexBuffer = VertexBuffer;
  9015. })(BABYLON || (BABYLON = {}));
  9016. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9017. var BABYLON;
  9018. (function (BABYLON) {
  9019. var AbstractMesh = (function (_super) {
  9020. __extends(AbstractMesh, _super);
  9021. function AbstractMesh(name, scene) {
  9022. _super.call(this, name, scene);
  9023. // Properties
  9024. this.definedFacingForward = true; // orientation for POV movement & rotation
  9025. this.position = new BABYLON.Vector3(0, 0, 0);
  9026. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9027. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9028. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9029. this.visibility = 1.0;
  9030. this.alphaIndex = Number.MAX_VALUE;
  9031. this.infiniteDistance = false;
  9032. this.isVisible = true;
  9033. this.isPickable = true;
  9034. this.showBoundingBox = false;
  9035. this.showSubMeshesBoundingBox = false;
  9036. this.onDispose = null;
  9037. this.checkCollisions = false;
  9038. this.isBlocker = false;
  9039. this.renderingGroupId = 0;
  9040. this.receiveShadows = false;
  9041. this.renderOutline = false;
  9042. this.outlineColor = BABYLON.Color3.Red();
  9043. this.outlineWidth = 0.02;
  9044. this.renderOverlay = false;
  9045. this.overlayColor = BABYLON.Color3.Red();
  9046. this.overlayAlpha = 0.5;
  9047. this.hasVertexAlpha = false;
  9048. this.useVertexColors = true;
  9049. this.applyFog = true;
  9050. this.useOctreeForRenderingSelection = true;
  9051. this.useOctreeForPicking = true;
  9052. this.useOctreeForCollisions = true;
  9053. this.layerMask = 0xFFFFFFFF;
  9054. // Physics
  9055. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9056. // Collisions
  9057. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9058. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9059. this._collider = new BABYLON.Collider();
  9060. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9061. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9062. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9063. // Cache
  9064. this._localScaling = BABYLON.Matrix.Zero();
  9065. this._localRotation = BABYLON.Matrix.Zero();
  9066. this._localTranslation = BABYLON.Matrix.Zero();
  9067. this._localBillboard = BABYLON.Matrix.Zero();
  9068. this._localPivotScaling = BABYLON.Matrix.Zero();
  9069. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9070. this._localWorld = BABYLON.Matrix.Zero();
  9071. this._worldMatrix = BABYLON.Matrix.Zero();
  9072. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9073. this._absolutePosition = BABYLON.Vector3.Zero();
  9074. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9075. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9076. this._isDirty = false;
  9077. this._pivotMatrix = BABYLON.Matrix.Identity();
  9078. this._isDisposed = false;
  9079. this._renderId = 0;
  9080. this._intersectionsInProgress = new Array();
  9081. this._onAfterWorldMatrixUpdate = new Array();
  9082. scene.meshes.push(this);
  9083. }
  9084. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9085. get: function () {
  9086. return AbstractMesh._BILLBOARDMODE_NONE;
  9087. },
  9088. enumerable: true,
  9089. configurable: true
  9090. });
  9091. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9092. get: function () {
  9093. return AbstractMesh._BILLBOARDMODE_X;
  9094. },
  9095. enumerable: true,
  9096. configurable: true
  9097. });
  9098. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9099. get: function () {
  9100. return AbstractMesh._BILLBOARDMODE_Y;
  9101. },
  9102. enumerable: true,
  9103. configurable: true
  9104. });
  9105. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9106. get: function () {
  9107. return AbstractMesh._BILLBOARDMODE_Z;
  9108. },
  9109. enumerable: true,
  9110. configurable: true
  9111. });
  9112. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9113. get: function () {
  9114. return AbstractMesh._BILLBOARDMODE_ALL;
  9115. },
  9116. enumerable: true,
  9117. configurable: true
  9118. });
  9119. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9120. // Methods
  9121. get: function () {
  9122. return false;
  9123. },
  9124. enumerable: true,
  9125. configurable: true
  9126. });
  9127. AbstractMesh.prototype.getLOD = function (camera) {
  9128. return this;
  9129. };
  9130. AbstractMesh.prototype.getTotalVertices = function () {
  9131. return 0;
  9132. };
  9133. AbstractMesh.prototype.getIndices = function () {
  9134. return null;
  9135. };
  9136. AbstractMesh.prototype.getVerticesData = function (kind) {
  9137. return null;
  9138. };
  9139. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9140. return false;
  9141. };
  9142. AbstractMesh.prototype.getBoundingInfo = function () {
  9143. if (this._masterMesh) {
  9144. return this._masterMesh.getBoundingInfo();
  9145. }
  9146. if (!this._boundingInfo) {
  9147. this._updateBoundingInfo();
  9148. }
  9149. return this._boundingInfo;
  9150. };
  9151. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9152. get: function () {
  9153. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9154. },
  9155. enumerable: true,
  9156. configurable: true
  9157. });
  9158. AbstractMesh.prototype._preActivate = function () {
  9159. };
  9160. AbstractMesh.prototype._activate = function (renderId) {
  9161. this._renderId = renderId;
  9162. };
  9163. AbstractMesh.prototype.getWorldMatrix = function () {
  9164. if (this._masterMesh) {
  9165. return this._masterMesh.getWorldMatrix();
  9166. }
  9167. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9168. this.computeWorldMatrix();
  9169. }
  9170. return this._worldMatrix;
  9171. };
  9172. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9173. get: function () {
  9174. return this._worldMatrix;
  9175. },
  9176. enumerable: true,
  9177. configurable: true
  9178. });
  9179. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9180. get: function () {
  9181. return this._absolutePosition;
  9182. },
  9183. enumerable: true,
  9184. configurable: true
  9185. });
  9186. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9187. if (!this.rotationQuaternion) {
  9188. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9189. this.rotation = BABYLON.Vector3.Zero();
  9190. }
  9191. if (!space || space == 0 /* LOCAL */) {
  9192. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9193. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9194. }
  9195. else {
  9196. if (this.parent) {
  9197. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9198. invertParentWorldMatrix.invert();
  9199. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9200. }
  9201. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9202. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9203. }
  9204. };
  9205. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9206. var displacementVector = axis.scale(distance);
  9207. if (!space || space == 0 /* LOCAL */) {
  9208. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9209. this.setPositionWithLocalVector(tempV3);
  9210. }
  9211. else {
  9212. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9213. }
  9214. };
  9215. AbstractMesh.prototype.getAbsolutePosition = function () {
  9216. this.computeWorldMatrix();
  9217. return this._absolutePosition;
  9218. };
  9219. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9220. if (!absolutePosition) {
  9221. return;
  9222. }
  9223. var absolutePositionX;
  9224. var absolutePositionY;
  9225. var absolutePositionZ;
  9226. if (absolutePosition.x === undefined) {
  9227. if (arguments.length < 3) {
  9228. return;
  9229. }
  9230. absolutePositionX = arguments[0];
  9231. absolutePositionY = arguments[1];
  9232. absolutePositionZ = arguments[2];
  9233. }
  9234. else {
  9235. absolutePositionX = absolutePosition.x;
  9236. absolutePositionY = absolutePosition.y;
  9237. absolutePositionZ = absolutePosition.z;
  9238. }
  9239. if (this.parent) {
  9240. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9241. invertParentWorldMatrix.invert();
  9242. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9243. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9244. }
  9245. else {
  9246. this.position.x = absolutePositionX;
  9247. this.position.y = absolutePositionY;
  9248. this.position.z = absolutePositionZ;
  9249. }
  9250. };
  9251. // ================================== Point of View Movement =================================
  9252. /**
  9253. * Perform relative position change from the point of view of behind the front of the mesh.
  9254. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9255. * Supports definition of mesh facing forward or backward.
  9256. * @param {number} amountRight
  9257. * @param {number} amountUp
  9258. * @param {number} amountForward
  9259. */
  9260. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9261. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9262. };
  9263. /**
  9264. * Calculate relative position change from the point of view of behind the front of the mesh.
  9265. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9266. * Supports definition of mesh facing forward or backward.
  9267. * @param {number} amountRight
  9268. * @param {number} amountUp
  9269. * @param {number} amountForward
  9270. */
  9271. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9272. var rotMatrix = new BABYLON.Matrix();
  9273. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9274. rotQuaternion.toRotationMatrix(rotMatrix);
  9275. var translationDelta = BABYLON.Vector3.Zero();
  9276. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9277. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9278. return translationDelta;
  9279. };
  9280. // ================================== Point of View Rotation =================================
  9281. /**
  9282. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9283. * Supports definition of mesh facing forward or backward.
  9284. * @param {number} flipBack
  9285. * @param {number} twirlClockwise
  9286. * @param {number} tiltRight
  9287. */
  9288. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9289. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9290. };
  9291. /**
  9292. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9293. * Supports definition of mesh facing forward or backward.
  9294. * @param {number} flipBack
  9295. * @param {number} twirlClockwise
  9296. * @param {number} tiltRight
  9297. */
  9298. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9299. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9300. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9301. };
  9302. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9303. this._pivotMatrix = matrix;
  9304. this._cache.pivotMatrixUpdated = true;
  9305. };
  9306. AbstractMesh.prototype.getPivotMatrix = function () {
  9307. return this._pivotMatrix;
  9308. };
  9309. AbstractMesh.prototype._isSynchronized = function () {
  9310. if (this._isDirty) {
  9311. return false;
  9312. }
  9313. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9314. return false;
  9315. if (this._cache.pivotMatrixUpdated) {
  9316. return false;
  9317. }
  9318. if (this.infiniteDistance) {
  9319. return false;
  9320. }
  9321. if (!this._cache.position.equals(this.position))
  9322. return false;
  9323. if (this.rotationQuaternion) {
  9324. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9325. return false;
  9326. }
  9327. else {
  9328. if (!this._cache.rotation.equals(this.rotation))
  9329. return false;
  9330. }
  9331. if (!this._cache.scaling.equals(this.scaling))
  9332. return false;
  9333. return true;
  9334. };
  9335. AbstractMesh.prototype._initCache = function () {
  9336. _super.prototype._initCache.call(this);
  9337. this._cache.localMatrixUpdated = false;
  9338. this._cache.position = BABYLON.Vector3.Zero();
  9339. this._cache.scaling = BABYLON.Vector3.Zero();
  9340. this._cache.rotation = BABYLON.Vector3.Zero();
  9341. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9342. };
  9343. AbstractMesh.prototype.markAsDirty = function (property) {
  9344. if (property === "rotation") {
  9345. this.rotationQuaternion = null;
  9346. }
  9347. this._currentRenderId = Number.MAX_VALUE;
  9348. this._isDirty = true;
  9349. };
  9350. AbstractMesh.prototype._updateBoundingInfo = function () {
  9351. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9352. this._boundingInfo._update(this.worldMatrixFromCache);
  9353. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9354. };
  9355. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9356. if (!this.subMeshes) {
  9357. return;
  9358. }
  9359. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9360. var subMesh = this.subMeshes[subIndex];
  9361. subMesh.updateBoundingInfo(matrix);
  9362. }
  9363. };
  9364. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9365. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9366. return this._worldMatrix;
  9367. }
  9368. this._cache.position.copyFrom(this.position);
  9369. this._cache.scaling.copyFrom(this.scaling);
  9370. this._cache.pivotMatrixUpdated = false;
  9371. this._currentRenderId = this.getScene().getRenderId();
  9372. this._isDirty = false;
  9373. // Scaling
  9374. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9375. // Rotation
  9376. if (this.rotationQuaternion) {
  9377. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9378. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9379. }
  9380. else {
  9381. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9382. this._cache.rotation.copyFrom(this.rotation);
  9383. }
  9384. // Translation
  9385. if (this.infiniteDistance && !this.parent) {
  9386. var camera = this.getScene().activeCamera;
  9387. var cameraWorldMatrix = camera.getWorldMatrix();
  9388. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9389. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9390. }
  9391. else {
  9392. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9393. }
  9394. // Composing transformations
  9395. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9396. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9397. // Billboarding
  9398. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9399. var localPosition = this.position.clone();
  9400. var zero = this.getScene().activeCamera.position.clone();
  9401. if (this.parent && this.parent.position) {
  9402. localPosition.addInPlace(this.parent.position);
  9403. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9404. }
  9405. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9406. zero = this.getScene().activeCamera.position;
  9407. }
  9408. else {
  9409. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9410. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9411. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9412. zero.y = localPosition.y + 0.001;
  9413. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9414. zero.z = localPosition.z + 0.001;
  9415. }
  9416. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9417. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9418. this._localBillboard.invert();
  9419. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9420. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9421. }
  9422. // Local world
  9423. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9424. // Parent
  9425. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9426. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9427. }
  9428. else {
  9429. this._worldMatrix.copyFrom(this._localWorld);
  9430. }
  9431. // Bounding info
  9432. this._updateBoundingInfo();
  9433. // Absolute position
  9434. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9435. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9436. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9437. }
  9438. return this._worldMatrix;
  9439. };
  9440. /**
  9441. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9442. * @param func: callback function to add
  9443. */
  9444. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9445. this._onAfterWorldMatrixUpdate.push(func);
  9446. };
  9447. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9448. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9449. if (index > -1) {
  9450. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9451. }
  9452. };
  9453. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9454. this.computeWorldMatrix();
  9455. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9456. };
  9457. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9458. this.computeWorldMatrix();
  9459. var invLocalWorldMatrix = this._localWorld.clone();
  9460. invLocalWorldMatrix.invert();
  9461. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9462. };
  9463. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9464. this.computeWorldMatrix();
  9465. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9466. };
  9467. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9468. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9469. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9470. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9471. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9472. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9473. /// <returns>Mesh oriented towards targetMesh</returns>
  9474. yawCor = yawCor || 0; // default to zero if undefined
  9475. pitchCor = pitchCor || 0;
  9476. rollCor = rollCor || 0;
  9477. var dv = targetPoint.subtract(this.position);
  9478. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9479. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9480. var pitch = Math.atan2(dv.y, len);
  9481. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9482. };
  9483. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9484. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9485. return false;
  9486. }
  9487. return true;
  9488. };
  9489. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9490. if (!camera) {
  9491. camera = this.getScene().activeCamera;
  9492. }
  9493. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9494. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9495. return false;
  9496. }
  9497. return true;
  9498. };
  9499. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9500. if (!this._boundingInfo || !mesh._boundingInfo) {
  9501. return false;
  9502. }
  9503. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9504. };
  9505. AbstractMesh.prototype.intersectsPoint = function (point) {
  9506. if (!this._boundingInfo) {
  9507. return false;
  9508. }
  9509. return this._boundingInfo.intersectsPoint(point);
  9510. };
  9511. // Physics
  9512. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9513. var physicsEngine = this.getScene().getPhysicsEngine();
  9514. if (!physicsEngine) {
  9515. return;
  9516. }
  9517. if (impostor.impostor) {
  9518. // Old API
  9519. options = impostor;
  9520. impostor = impostor.impostor;
  9521. }
  9522. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9523. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9524. physicsEngine._unregisterMesh(this);
  9525. return;
  9526. }
  9527. options.mass = options.mass || 0;
  9528. options.friction = options.friction || 0.2;
  9529. options.restitution = options.restitution || 0.2;
  9530. this._physicImpostor = impostor;
  9531. this._physicsMass = options.mass;
  9532. this._physicsFriction = options.friction;
  9533. this._physicRestitution = options.restitution;
  9534. return physicsEngine._registerMesh(this, impostor, options);
  9535. };
  9536. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9537. if (!this._physicImpostor) {
  9538. return BABYLON.PhysicsEngine.NoImpostor;
  9539. }
  9540. return this._physicImpostor;
  9541. };
  9542. AbstractMesh.prototype.getPhysicsMass = function () {
  9543. if (!this._physicsMass) {
  9544. return 0;
  9545. }
  9546. return this._physicsMass;
  9547. };
  9548. AbstractMesh.prototype.getPhysicsFriction = function () {
  9549. if (!this._physicsFriction) {
  9550. return 0;
  9551. }
  9552. return this._physicsFriction;
  9553. };
  9554. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9555. if (!this._physicRestitution) {
  9556. return 0;
  9557. }
  9558. return this._physicRestitution;
  9559. };
  9560. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9561. if (!camera) {
  9562. camera = this.getScene().activeCamera;
  9563. }
  9564. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9565. };
  9566. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9567. if (!camera) {
  9568. camera = this.getScene().activeCamera;
  9569. }
  9570. return this.absolutePosition.subtract(camera.position).length();
  9571. };
  9572. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9573. if (!this._physicImpostor) {
  9574. return;
  9575. }
  9576. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9577. };
  9578. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9579. if (!this._physicImpostor) {
  9580. return;
  9581. }
  9582. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9583. };
  9584. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9585. if (!this._physicImpostor) {
  9586. return;
  9587. }
  9588. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9589. };
  9590. // Collisions
  9591. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9592. var globalPosition = this.getAbsolutePosition();
  9593. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9594. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9595. this._collider.radius = this.ellipsoid;
  9596. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9597. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9598. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9599. this.position.addInPlace(this._diffPositionForCollisions);
  9600. }
  9601. };
  9602. // Submeshes octree
  9603. /**
  9604. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9605. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9606. */
  9607. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9608. if (maxCapacity === void 0) { maxCapacity = 64; }
  9609. if (maxDepth === void 0) { maxDepth = 2; }
  9610. if (!this._submeshesOctree) {
  9611. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9612. }
  9613. this.computeWorldMatrix(true);
  9614. // Update octree
  9615. var bbox = this.getBoundingInfo().boundingBox;
  9616. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9617. return this._submeshesOctree;
  9618. };
  9619. // Collisions
  9620. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9621. this._generatePointsArray();
  9622. // Transformation
  9623. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9624. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9625. subMesh._lastColliderWorldVertices = [];
  9626. subMesh._trianglePlanes = [];
  9627. var start = subMesh.verticesStart;
  9628. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9629. for (var i = start; i < end; i++) {
  9630. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9631. }
  9632. }
  9633. // Collide
  9634. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9635. };
  9636. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9637. var subMeshes;
  9638. var len;
  9639. // Octrees
  9640. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9641. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9642. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9643. len = intersections.length;
  9644. subMeshes = intersections.data;
  9645. }
  9646. else {
  9647. subMeshes = this.subMeshes;
  9648. len = subMeshes.length;
  9649. }
  9650. for (var index = 0; index < len; index++) {
  9651. var subMesh = subMeshes[index];
  9652. // Bounding test
  9653. if (len > 1 && !subMesh._checkCollision(collider))
  9654. continue;
  9655. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9656. }
  9657. };
  9658. AbstractMesh.prototype._checkCollision = function (collider) {
  9659. // Bounding box test
  9660. if (!this._boundingInfo._checkCollision(collider))
  9661. return;
  9662. // Transformation matrix
  9663. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9664. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9665. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9666. };
  9667. // Picking
  9668. AbstractMesh.prototype._generatePointsArray = function () {
  9669. return false;
  9670. };
  9671. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9672. var pickingInfo = new BABYLON.PickingInfo();
  9673. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9674. return pickingInfo;
  9675. }
  9676. if (!this._generatePointsArray()) {
  9677. return pickingInfo;
  9678. }
  9679. var intersectInfo = null;
  9680. // Octrees
  9681. var subMeshes;
  9682. var len;
  9683. if (this._submeshesOctree && this.useOctreeForPicking) {
  9684. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9685. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9686. len = intersections.length;
  9687. subMeshes = intersections.data;
  9688. }
  9689. else {
  9690. subMeshes = this.subMeshes;
  9691. len = subMeshes.length;
  9692. }
  9693. for (var index = 0; index < len; index++) {
  9694. var subMesh = subMeshes[index];
  9695. // Bounding test
  9696. if (len > 1 && !subMesh.canIntersects(ray))
  9697. continue;
  9698. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9699. if (currentIntersectInfo) {
  9700. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9701. intersectInfo = currentIntersectInfo;
  9702. if (fastCheck) {
  9703. break;
  9704. }
  9705. }
  9706. }
  9707. }
  9708. if (intersectInfo) {
  9709. // Get picked point
  9710. var world = this.getWorldMatrix();
  9711. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9712. var direction = ray.direction.clone();
  9713. direction = direction.scale(intersectInfo.distance);
  9714. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9715. var pickedPoint = worldOrigin.add(worldDirection);
  9716. // Return result
  9717. pickingInfo.hit = true;
  9718. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9719. pickingInfo.pickedPoint = pickedPoint;
  9720. pickingInfo.pickedMesh = this;
  9721. pickingInfo.bu = intersectInfo.bu;
  9722. pickingInfo.bv = intersectInfo.bv;
  9723. pickingInfo.faceId = intersectInfo.faceId;
  9724. return pickingInfo;
  9725. }
  9726. return pickingInfo;
  9727. };
  9728. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9729. return null;
  9730. };
  9731. AbstractMesh.prototype.releaseSubMeshes = function () {
  9732. if (this.subMeshes) {
  9733. while (this.subMeshes.length) {
  9734. this.subMeshes[0].dispose();
  9735. }
  9736. }
  9737. else {
  9738. this.subMeshes = new Array();
  9739. }
  9740. };
  9741. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9742. // Physics
  9743. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9744. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9745. }
  9746. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9747. var other = this._intersectionsInProgress[index];
  9748. var pos = other._intersectionsInProgress.indexOf(this);
  9749. other._intersectionsInProgress.splice(pos, 1);
  9750. }
  9751. this._intersectionsInProgress = [];
  9752. // SubMeshes
  9753. this.releaseSubMeshes();
  9754. // Remove from scene
  9755. var index = this.getScene().meshes.indexOf(this);
  9756. if (index != -1) {
  9757. // Remove from the scene if mesh found
  9758. this.getScene().meshes.splice(index, 1);
  9759. }
  9760. if (!doNotRecurse) {
  9761. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9762. if (this.getScene().particleSystems[index].emitter == this) {
  9763. this.getScene().particleSystems[index].dispose();
  9764. index--;
  9765. }
  9766. }
  9767. // Children
  9768. var objects = this.getScene().meshes.slice(0);
  9769. for (index = 0; index < objects.length; index++) {
  9770. if (objects[index].parent == this) {
  9771. objects[index].dispose();
  9772. }
  9773. }
  9774. }
  9775. else {
  9776. for (index = 0; index < this.getScene().meshes.length; index++) {
  9777. var obj = this.getScene().meshes[index];
  9778. if (obj.parent === this) {
  9779. obj.parent = null;
  9780. obj.computeWorldMatrix(true);
  9781. }
  9782. }
  9783. }
  9784. this._onAfterWorldMatrixUpdate = [];
  9785. this._isDisposed = true;
  9786. // Callback
  9787. if (this.onDispose) {
  9788. this.onDispose();
  9789. }
  9790. };
  9791. // Statics
  9792. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9793. AbstractMesh._BILLBOARDMODE_X = 1;
  9794. AbstractMesh._BILLBOARDMODE_Y = 2;
  9795. AbstractMesh._BILLBOARDMODE_Z = 4;
  9796. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9797. return AbstractMesh;
  9798. })(BABYLON.Node);
  9799. BABYLON.AbstractMesh = AbstractMesh;
  9800. })(BABYLON || (BABYLON = {}));
  9801. //# sourceMappingURL=babylon.abstractMesh.js.map
  9802. var BABYLON;
  9803. (function (BABYLON) {
  9804. var _InstancesBatch = (function () {
  9805. function _InstancesBatch() {
  9806. this.mustReturn = false;
  9807. this.visibleInstances = new Array();
  9808. this.renderSelf = new Array();
  9809. }
  9810. return _InstancesBatch;
  9811. })();
  9812. BABYLON._InstancesBatch = _InstancesBatch;
  9813. var Mesh = (function (_super) {
  9814. __extends(Mesh, _super);
  9815. /**
  9816. * @constructor
  9817. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9818. * @param {Scene} scene - The scene to add this mesh to.
  9819. * @param {Node} parent - The parent of this mesh, if it has one
  9820. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9821. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9822. * When false, achieved by calling a clone(), also passing False.
  9823. * This will make creation of children, recursive.
  9824. */
  9825. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9826. if (parent === void 0) { parent = null; }
  9827. _super.call(this, name, scene);
  9828. // Members
  9829. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9830. this.instances = new Array();
  9831. this._LODLevels = new Array();
  9832. this._onBeforeRenderCallbacks = new Array();
  9833. this._onAfterRenderCallbacks = new Array();
  9834. this._visibleInstances = {};
  9835. this._renderIdForInstances = new Array();
  9836. this._batchCache = new _InstancesBatch();
  9837. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  9838. if (source) {
  9839. // Geometry
  9840. if (source._geometry) {
  9841. source._geometry.applyToMesh(this);
  9842. }
  9843. // Deep copy
  9844. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9845. // Material
  9846. this.material = source.material;
  9847. if (!doNotCloneChildren) {
  9848. for (var index = 0; index < scene.meshes.length; index++) {
  9849. var mesh = scene.meshes[index];
  9850. if (mesh.parent === source) {
  9851. // doNotCloneChildren is always going to be False
  9852. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9853. }
  9854. }
  9855. }
  9856. for (index = 0; index < scene.particleSystems.length; index++) {
  9857. var system = scene.particleSystems[index];
  9858. if (system.emitter === source) {
  9859. system.clone(system.name, this);
  9860. }
  9861. }
  9862. this.computeWorldMatrix(true);
  9863. }
  9864. // Parent
  9865. if (parent !== null) {
  9866. this.parent = parent;
  9867. }
  9868. }
  9869. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9870. // Methods
  9871. get: function () {
  9872. return this._LODLevels.length > 0;
  9873. },
  9874. enumerable: true,
  9875. configurable: true
  9876. });
  9877. Mesh.prototype._sortLODLevels = function () {
  9878. this._LODLevels.sort(function (a, b) {
  9879. if (a.distance < b.distance) {
  9880. return 1;
  9881. }
  9882. if (a.distance > b.distance) {
  9883. return -1;
  9884. }
  9885. return 0;
  9886. });
  9887. };
  9888. /**
  9889. * Add a mesh as LOD level triggered at the given distance.
  9890. * @param {number} distance - the distance from the center of the object to show this level
  9891. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  9892. * @return {BABYLON.Mesh} this mesh (for chaining)
  9893. */
  9894. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9895. if (mesh && mesh._masterMesh) {
  9896. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9897. return this;
  9898. }
  9899. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9900. this._LODLevels.push(level);
  9901. if (mesh) {
  9902. mesh._masterMesh = this;
  9903. }
  9904. this._sortLODLevels();
  9905. return this;
  9906. };
  9907. /**
  9908. * Remove a mesh from the LOD array
  9909. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  9910. * @return {BABYLON.Mesh} this mesh (for chaining)
  9911. */
  9912. Mesh.prototype.removeLODLevel = function (mesh) {
  9913. for (var index = 0; index < this._LODLevels.length; index++) {
  9914. if (this._LODLevels[index].mesh === mesh) {
  9915. this._LODLevels.splice(index, 1);
  9916. if (mesh) {
  9917. mesh._masterMesh = null;
  9918. }
  9919. }
  9920. }
  9921. this._sortLODLevels();
  9922. return this;
  9923. };
  9924. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9925. if (!this._LODLevels || this._LODLevels.length === 0) {
  9926. return this;
  9927. }
  9928. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9929. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9930. return this;
  9931. }
  9932. for (var index = 0; index < this._LODLevels.length; index++) {
  9933. var level = this._LODLevels[index];
  9934. if (level.distance < distanceToCamera) {
  9935. if (level.mesh) {
  9936. level.mesh._preActivate();
  9937. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9938. }
  9939. return level.mesh;
  9940. }
  9941. }
  9942. return this;
  9943. };
  9944. Object.defineProperty(Mesh.prototype, "geometry", {
  9945. get: function () {
  9946. return this._geometry;
  9947. },
  9948. enumerable: true,
  9949. configurable: true
  9950. });
  9951. Mesh.prototype.getTotalVertices = function () {
  9952. if (!this._geometry) {
  9953. return 0;
  9954. }
  9955. return this._geometry.getTotalVertices();
  9956. };
  9957. Mesh.prototype.getVerticesData = function (kind) {
  9958. if (!this._geometry) {
  9959. return null;
  9960. }
  9961. return this._geometry.getVerticesData(kind);
  9962. };
  9963. Mesh.prototype.getVertexBuffer = function (kind) {
  9964. if (!this._geometry) {
  9965. return undefined;
  9966. }
  9967. return this._geometry.getVertexBuffer(kind);
  9968. };
  9969. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9970. if (!this._geometry) {
  9971. if (this._delayInfo) {
  9972. return this._delayInfo.indexOf(kind) !== -1;
  9973. }
  9974. return false;
  9975. }
  9976. return this._geometry.isVerticesDataPresent(kind);
  9977. };
  9978. Mesh.prototype.getVerticesDataKinds = function () {
  9979. if (!this._geometry) {
  9980. var result = [];
  9981. if (this._delayInfo) {
  9982. for (var kind in this._delayInfo) {
  9983. result.push(kind);
  9984. }
  9985. }
  9986. return result;
  9987. }
  9988. return this._geometry.getVerticesDataKinds();
  9989. };
  9990. Mesh.prototype.getTotalIndices = function () {
  9991. if (!this._geometry) {
  9992. return 0;
  9993. }
  9994. return this._geometry.getTotalIndices();
  9995. };
  9996. Mesh.prototype.getIndices = function () {
  9997. if (!this._geometry) {
  9998. return [];
  9999. }
  10000. return this._geometry.getIndices();
  10001. };
  10002. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10003. get: function () {
  10004. return this._masterMesh !== null && this._masterMesh !== undefined;
  10005. },
  10006. enumerable: true,
  10007. configurable: true
  10008. });
  10009. Mesh.prototype.isReady = function () {
  10010. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10011. return false;
  10012. }
  10013. return _super.prototype.isReady.call(this);
  10014. };
  10015. Mesh.prototype.isDisposed = function () {
  10016. return this._isDisposed;
  10017. };
  10018. // Methods
  10019. Mesh.prototype._preActivate = function () {
  10020. var sceneRenderId = this.getScene().getRenderId();
  10021. if (this._preActivateId == sceneRenderId) {
  10022. return;
  10023. }
  10024. this._preActivateId = sceneRenderId;
  10025. this._visibleInstances = null;
  10026. };
  10027. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10028. if (!this._visibleInstances) {
  10029. this._visibleInstances = {};
  10030. this._visibleInstances.defaultRenderId = renderId;
  10031. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10032. }
  10033. if (!this._visibleInstances[renderId]) {
  10034. this._visibleInstances[renderId] = new Array();
  10035. }
  10036. this._visibleInstances[renderId].push(instance);
  10037. };
  10038. Mesh.prototype.refreshBoundingInfo = function () {
  10039. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10040. if (data) {
  10041. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10042. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10043. }
  10044. if (this.subMeshes) {
  10045. for (var index = 0; index < this.subMeshes.length; index++) {
  10046. this.subMeshes[index].refreshBoundingInfo();
  10047. }
  10048. }
  10049. this._updateBoundingInfo();
  10050. };
  10051. Mesh.prototype._createGlobalSubMesh = function () {
  10052. var totalVertices = this.getTotalVertices();
  10053. if (!totalVertices || !this.getIndices()) {
  10054. return null;
  10055. }
  10056. this.releaseSubMeshes();
  10057. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10058. };
  10059. Mesh.prototype.subdivide = function (count) {
  10060. if (count < 1) {
  10061. return;
  10062. }
  10063. var totalIndices = this.getTotalIndices();
  10064. var subdivisionSize = (totalIndices / count) | 0;
  10065. var offset = 0;
  10066. while (subdivisionSize % 3 != 0) {
  10067. subdivisionSize++;
  10068. }
  10069. this.releaseSubMeshes();
  10070. for (var index = 0; index < count; index++) {
  10071. if (offset >= totalIndices) {
  10072. break;
  10073. }
  10074. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10075. offset += subdivisionSize;
  10076. }
  10077. this.synchronizeInstances();
  10078. };
  10079. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10080. if (kind instanceof Array) {
  10081. var temp = data;
  10082. data = kind;
  10083. kind = temp;
  10084. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10085. }
  10086. if (!this._geometry) {
  10087. var vertexData = new BABYLON.VertexData();
  10088. vertexData.set(data, kind);
  10089. var scene = this.getScene();
  10090. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10091. }
  10092. else {
  10093. this._geometry.setVerticesData(kind, data, updatable, stride);
  10094. }
  10095. };
  10096. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10097. if (!this._geometry) {
  10098. return;
  10099. }
  10100. if (!makeItUnique) {
  10101. this._geometry.updateVerticesData(kind, data, updateExtends);
  10102. }
  10103. else {
  10104. this.makeGeometryUnique();
  10105. this.updateVerticesData(kind, data, updateExtends, false);
  10106. }
  10107. };
  10108. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10109. if (!this._geometry) {
  10110. return;
  10111. }
  10112. if (!makeItUnique) {
  10113. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10114. }
  10115. else {
  10116. this.makeGeometryUnique();
  10117. this.updateVerticesDataDirectly(kind, data, offset, false);
  10118. }
  10119. };
  10120. Mesh.prototype.makeGeometryUnique = function () {
  10121. if (!this._geometry) {
  10122. return;
  10123. }
  10124. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10125. geometry.applyToMesh(this);
  10126. };
  10127. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10128. if (!this._geometry) {
  10129. var vertexData = new BABYLON.VertexData();
  10130. vertexData.indices = indices;
  10131. var scene = this.getScene();
  10132. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10133. }
  10134. else {
  10135. this._geometry.setIndices(indices, totalVertices);
  10136. }
  10137. };
  10138. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10139. var engine = this.getScene().getEngine();
  10140. // Wireframe
  10141. var indexToBind;
  10142. switch (fillMode) {
  10143. case BABYLON.Material.PointFillMode:
  10144. indexToBind = null;
  10145. break;
  10146. case BABYLON.Material.WireFrameFillMode:
  10147. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10148. break;
  10149. default:
  10150. case BABYLON.Material.TriangleFillMode:
  10151. indexToBind = this._geometry.getIndexBuffer();
  10152. break;
  10153. }
  10154. // VBOs
  10155. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10156. };
  10157. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10158. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10159. return;
  10160. }
  10161. var engine = this.getScene().getEngine();
  10162. switch (fillMode) {
  10163. case BABYLON.Material.PointFillMode:
  10164. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10165. break;
  10166. case BABYLON.Material.WireFrameFillMode:
  10167. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10168. break;
  10169. default:
  10170. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10171. }
  10172. };
  10173. Mesh.prototype.registerBeforeRender = function (func) {
  10174. this._onBeforeRenderCallbacks.push(func);
  10175. };
  10176. Mesh.prototype.unregisterBeforeRender = function (func) {
  10177. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10178. if (index > -1) {
  10179. this._onBeforeRenderCallbacks.splice(index, 1);
  10180. }
  10181. };
  10182. Mesh.prototype.registerAfterRender = function (func) {
  10183. this._onAfterRenderCallbacks.push(func);
  10184. };
  10185. Mesh.prototype.unregisterAfterRender = function (func) {
  10186. var index = this._onAfterRenderCallbacks.indexOf(func);
  10187. if (index > -1) {
  10188. this._onAfterRenderCallbacks.splice(index, 1);
  10189. }
  10190. };
  10191. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10192. var scene = this.getScene();
  10193. this._batchCache.mustReturn = false;
  10194. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10195. this._batchCache.visibleInstances[subMeshId] = null;
  10196. if (this._visibleInstances) {
  10197. var currentRenderId = scene.getRenderId();
  10198. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10199. var selfRenderId = this._renderId;
  10200. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10201. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10202. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10203. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10204. }
  10205. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10206. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10207. this._batchCache.mustReturn = true;
  10208. return this._batchCache;
  10209. }
  10210. if (currentRenderId !== selfRenderId) {
  10211. this._batchCache.renderSelf[subMeshId] = false;
  10212. }
  10213. }
  10214. this._renderIdForInstances[subMeshId] = currentRenderId;
  10215. }
  10216. return this._batchCache;
  10217. };
  10218. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10219. var visibleInstances = batch.visibleInstances[subMesh._id];
  10220. var matricesCount = visibleInstances.length + 1;
  10221. var bufferSize = matricesCount * 16 * 4;
  10222. while (this._instancesBufferSize < bufferSize) {
  10223. this._instancesBufferSize *= 2;
  10224. }
  10225. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10226. if (this._worldMatricesInstancesBuffer) {
  10227. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10228. }
  10229. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10230. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10231. }
  10232. var offset = 0;
  10233. var instancesCount = 0;
  10234. var world = this.getWorldMatrix();
  10235. if (batch.renderSelf[subMesh._id]) {
  10236. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10237. offset += 16;
  10238. instancesCount++;
  10239. }
  10240. if (visibleInstances) {
  10241. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10242. var instance = visibleInstances[instanceIndex];
  10243. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10244. offset += 16;
  10245. instancesCount++;
  10246. }
  10247. }
  10248. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10249. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10250. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10251. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10252. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10253. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10254. this._draw(subMesh, fillMode, instancesCount);
  10255. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10256. };
  10257. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  10258. var scene = this.getScene();
  10259. var engine = scene.getEngine();
  10260. if (hardwareInstancedRendering) {
  10261. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10262. }
  10263. else {
  10264. if (batch.renderSelf[subMesh._id]) {
  10265. // Draw
  10266. if (onBeforeDraw) {
  10267. onBeforeDraw(false, this.getWorldMatrix());
  10268. }
  10269. this._draw(subMesh, fillMode);
  10270. }
  10271. if (batch.visibleInstances[subMesh._id]) {
  10272. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10273. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10274. // World
  10275. var world = instance.getWorldMatrix();
  10276. if (onBeforeDraw) {
  10277. onBeforeDraw(true, world);
  10278. }
  10279. // Draw
  10280. this._draw(subMesh, fillMode);
  10281. }
  10282. }
  10283. }
  10284. };
  10285. Mesh.prototype.render = function (subMesh) {
  10286. var scene = this.getScene();
  10287. // Managing instances
  10288. var batch = this._getInstancesRenderList(subMesh._id);
  10289. if (batch.mustReturn) {
  10290. return;
  10291. }
  10292. // Checking geometry state
  10293. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10294. return;
  10295. }
  10296. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10297. this._onBeforeRenderCallbacks[callbackIndex]();
  10298. }
  10299. var engine = scene.getEngine();
  10300. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10301. // Material
  10302. var effectiveMaterial = subMesh.getMaterial();
  10303. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10304. return;
  10305. }
  10306. // Outline - step 1
  10307. var savedDepthWrite = engine.getDepthWrite();
  10308. if (this.renderOutline) {
  10309. engine.setDepthWrite(false);
  10310. scene.getOutlineRenderer().render(subMesh, batch);
  10311. engine.setDepthWrite(savedDepthWrite);
  10312. }
  10313. effectiveMaterial._preBind();
  10314. var effect = effectiveMaterial.getEffect();
  10315. // Bind
  10316. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10317. this._bind(subMesh, effect, fillMode);
  10318. var world = this.getWorldMatrix();
  10319. effectiveMaterial.bind(world, this);
  10320. // Draw
  10321. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  10322. if (isInstance) {
  10323. effectiveMaterial.bindOnlyWorldMatrix(world);
  10324. }
  10325. });
  10326. // Unbind
  10327. effectiveMaterial.unbind();
  10328. // Outline - step 2
  10329. if (this.renderOutline && savedDepthWrite) {
  10330. engine.setDepthWrite(true);
  10331. engine.setColorWrite(false);
  10332. scene.getOutlineRenderer().render(subMesh, batch);
  10333. engine.setColorWrite(true);
  10334. }
  10335. // Overlay
  10336. if (this.renderOverlay) {
  10337. var currentMode = engine.getAlphaMode();
  10338. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10339. scene.getOutlineRenderer().render(subMesh, batch, true);
  10340. engine.setAlphaMode(currentMode);
  10341. }
  10342. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10343. this._onAfterRenderCallbacks[callbackIndex]();
  10344. }
  10345. };
  10346. Mesh.prototype.getEmittedParticleSystems = function () {
  10347. var results = new Array();
  10348. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10349. var particleSystem = this.getScene().particleSystems[index];
  10350. if (particleSystem.emitter === this) {
  10351. results.push(particleSystem);
  10352. }
  10353. }
  10354. return results;
  10355. };
  10356. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10357. var results = new Array();
  10358. var descendants = this.getDescendants();
  10359. descendants.push(this);
  10360. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10361. var particleSystem = this.getScene().particleSystems[index];
  10362. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10363. results.push(particleSystem);
  10364. }
  10365. }
  10366. return results;
  10367. };
  10368. Mesh.prototype.getChildren = function () {
  10369. var results = [];
  10370. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10371. var mesh = this.getScene().meshes[index];
  10372. if (mesh.parent === this) {
  10373. results.push(mesh);
  10374. }
  10375. }
  10376. return results;
  10377. };
  10378. Mesh.prototype._checkDelayState = function () {
  10379. var _this = this;
  10380. var that = this;
  10381. var scene = this.getScene();
  10382. if (this._geometry) {
  10383. this._geometry.load(scene);
  10384. }
  10385. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10386. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10387. scene._addPendingData(that);
  10388. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  10389. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10390. if (data instanceof ArrayBuffer) {
  10391. _this._delayLoadingFunction(data, _this);
  10392. }
  10393. else {
  10394. _this._delayLoadingFunction(JSON.parse(data), _this);
  10395. }
  10396. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10397. scene._removePendingData(_this);
  10398. }, function () {
  10399. }, scene.database, getBinaryData);
  10400. }
  10401. };
  10402. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10403. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10404. return false;
  10405. }
  10406. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10407. return false;
  10408. }
  10409. this._checkDelayState();
  10410. return true;
  10411. };
  10412. Mesh.prototype.setMaterialByID = function (id) {
  10413. var materials = this.getScene().materials;
  10414. for (var index = 0; index < materials.length; index++) {
  10415. if (materials[index].id === id) {
  10416. this.material = materials[index];
  10417. return;
  10418. }
  10419. }
  10420. // Multi
  10421. var multiMaterials = this.getScene().multiMaterials;
  10422. for (index = 0; index < multiMaterials.length; index++) {
  10423. if (multiMaterials[index].id === id) {
  10424. this.material = multiMaterials[index];
  10425. return;
  10426. }
  10427. }
  10428. };
  10429. Mesh.prototype.getAnimatables = function () {
  10430. var results = [];
  10431. if (this.material) {
  10432. results.push(this.material);
  10433. }
  10434. if (this.skeleton) {
  10435. results.push(this.skeleton);
  10436. }
  10437. return results;
  10438. };
  10439. // Geometry
  10440. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10441. // Position
  10442. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10443. return;
  10444. }
  10445. this._resetPointsArrayCache();
  10446. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10447. var temp = [];
  10448. for (var index = 0; index < data.length; index += 3) {
  10449. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10450. }
  10451. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  10452. // Normals
  10453. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10454. return;
  10455. }
  10456. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10457. for (index = 0; index < data.length; index += 3) {
  10458. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10459. }
  10460. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  10461. };
  10462. // Cache
  10463. Mesh.prototype._resetPointsArrayCache = function () {
  10464. this._positions = null;
  10465. };
  10466. Mesh.prototype._generatePointsArray = function () {
  10467. if (this._positions)
  10468. return true;
  10469. this._positions = [];
  10470. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10471. if (!data) {
  10472. return false;
  10473. }
  10474. for (var index = 0; index < data.length; index += 3) {
  10475. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  10476. }
  10477. return true;
  10478. };
  10479. // Clone
  10480. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10481. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  10482. };
  10483. // Dispose
  10484. Mesh.prototype.dispose = function (doNotRecurse) {
  10485. if (this._geometry) {
  10486. this._geometry.releaseForMesh(this, true);
  10487. }
  10488. // Instances
  10489. if (this._worldMatricesInstancesBuffer) {
  10490. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10491. this._worldMatricesInstancesBuffer = null;
  10492. }
  10493. while (this.instances.length) {
  10494. this.instances[0].dispose();
  10495. }
  10496. _super.prototype.dispose.call(this, doNotRecurse);
  10497. };
  10498. // Geometric tools
  10499. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  10500. var _this = this;
  10501. var scene = this.getScene();
  10502. var onload = function (img) {
  10503. // Getting height map data
  10504. var canvas = document.createElement("canvas");
  10505. var context = canvas.getContext("2d");
  10506. var heightMapWidth = img.width;
  10507. var heightMapHeight = img.height;
  10508. canvas.width = heightMapWidth;
  10509. canvas.height = heightMapHeight;
  10510. context.drawImage(img, 0, 0);
  10511. // Create VertexData from map data
  10512. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10513. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  10514. //execute success callback, if set
  10515. if (onSuccess) {
  10516. onSuccess(_this);
  10517. }
  10518. };
  10519. BABYLON.Tools.LoadImage(url, onload, function () {
  10520. }, scene.database);
  10521. };
  10522. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  10523. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10524. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  10525. return;
  10526. }
  10527. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10528. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10529. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10530. var position = BABYLON.Vector3.Zero();
  10531. var normal = BABYLON.Vector3.Zero();
  10532. var uv = BABYLON.Vector2.Zero();
  10533. for (var index = 0; index < positions.length; index += 3) {
  10534. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  10535. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  10536. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  10537. // Compute height
  10538. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  10539. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  10540. var pos = (u + v * heightMapWidth) * 4;
  10541. var r = buffer[pos] / 255.0;
  10542. var g = buffer[pos + 1] / 255.0;
  10543. var b = buffer[pos + 2] / 255.0;
  10544. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  10545. normal.normalize();
  10546. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  10547. position = position.add(normal);
  10548. position.toArray(positions, index);
  10549. }
  10550. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10551. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10552. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10553. };
  10554. Mesh.prototype.convertToFlatShadedMesh = function () {
  10555. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10556. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10557. var kinds = this.getVerticesDataKinds();
  10558. var vbs = [];
  10559. var data = [];
  10560. var newdata = [];
  10561. var updatableNormals = false;
  10562. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10563. var kind = kinds[kindIndex];
  10564. var vertexBuffer = this.getVertexBuffer(kind);
  10565. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10566. updatableNormals = vertexBuffer.isUpdatable();
  10567. kinds.splice(kindIndex, 1);
  10568. kindIndex--;
  10569. continue;
  10570. }
  10571. vbs[kind] = vertexBuffer;
  10572. data[kind] = vbs[kind].getData();
  10573. newdata[kind] = [];
  10574. }
  10575. // Save previous submeshes
  10576. var previousSubmeshes = this.subMeshes.slice(0);
  10577. var indices = this.getIndices();
  10578. var totalIndices = this.getTotalIndices();
  10579. for (var index = 0; index < totalIndices; index++) {
  10580. var vertexIndex = indices[index];
  10581. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10582. kind = kinds[kindIndex];
  10583. var stride = vbs[kind].getStrideSize();
  10584. for (var offset = 0; offset < stride; offset++) {
  10585. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10586. }
  10587. }
  10588. }
  10589. // Updating faces & normal
  10590. var normals = [];
  10591. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10592. for (index = 0; index < totalIndices; index += 3) {
  10593. indices[index] = index;
  10594. indices[index + 1] = index + 1;
  10595. indices[index + 2] = index + 2;
  10596. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10597. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10598. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10599. var p1p2 = p1.subtract(p2);
  10600. var p3p2 = p3.subtract(p2);
  10601. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10602. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10603. normals.push(normal.x);
  10604. normals.push(normal.y);
  10605. normals.push(normal.z);
  10606. }
  10607. }
  10608. this.setIndices(indices);
  10609. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10610. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10611. kind = kinds[kindIndex];
  10612. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10613. }
  10614. // Updating submeshes
  10615. this.releaseSubMeshes();
  10616. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10617. var previousOne = previousSubmeshes[submeshIndex];
  10618. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10619. }
  10620. this.synchronizeInstances();
  10621. };
  10622. // Instances
  10623. Mesh.prototype.createInstance = function (name) {
  10624. return new BABYLON.InstancedMesh(name, this);
  10625. };
  10626. Mesh.prototype.synchronizeInstances = function () {
  10627. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10628. var instance = this.instances[instanceIndex];
  10629. instance._syncSubMeshes();
  10630. }
  10631. };
  10632. /**
  10633. * Simplify the mesh according to the given array of settings.
  10634. * Function will return immediately and will simplify async.
  10635. * @param settings a collection of simplification settings.
  10636. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10637. * @param type the type of simplification to run.
  10638. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10639. */
  10640. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10641. var _this = this;
  10642. if (parallelProcessing === void 0) { parallelProcessing = true; }
  10643. if (type === void 0) { type = 0 /* QUADRATIC */; }
  10644. var getSimplifier = function () {
  10645. switch (type) {
  10646. case 0 /* QUADRATIC */:
  10647. default:
  10648. return new BABYLON.QuadraticErrorSimplification(_this);
  10649. }
  10650. };
  10651. if (parallelProcessing) {
  10652. //parallel simplifier
  10653. settings.forEach(function (setting) {
  10654. var simplifier = getSimplifier();
  10655. simplifier.simplify(setting, function (newMesh) {
  10656. _this.addLODLevel(setting.distance, newMesh);
  10657. //check if it is the last
  10658. if (setting.quality === settings[settings.length - 1].quality && successCallback) {
  10659. //all done, run the success callback.
  10660. successCallback();
  10661. }
  10662. });
  10663. });
  10664. }
  10665. else {
  10666. //single simplifier.
  10667. var simplifier = getSimplifier();
  10668. var runDecimation = function (setting, callback) {
  10669. simplifier.simplify(setting, function (newMesh) {
  10670. _this.addLODLevel(setting.distance, newMesh);
  10671. //run the next quality level
  10672. callback();
  10673. });
  10674. };
  10675. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  10676. runDecimation(settings[loop.index], function () {
  10677. loop.executeNext();
  10678. });
  10679. }, function () {
  10680. //execution ended, run the success callback.
  10681. if (successCallback) {
  10682. successCallback();
  10683. }
  10684. });
  10685. }
  10686. };
  10687. // Statics
  10688. Mesh.CreateBox = function (name, size, scene, updatable) {
  10689. var box = new Mesh(name, scene);
  10690. var vertexData = BABYLON.VertexData.CreateBox(size);
  10691. vertexData.applyToMesh(box, updatable);
  10692. return box;
  10693. };
  10694. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  10695. var sphere = new Mesh(name, scene);
  10696. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  10697. vertexData.applyToMesh(sphere, updatable);
  10698. return sphere;
  10699. };
  10700. // Cylinder and cone (Code inspired by SharpDX.org)
  10701. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  10702. // subdivisions is a new parameter, we need to support old signature
  10703. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  10704. if (scene !== undefined) {
  10705. updatable = scene;
  10706. }
  10707. scene = subdivisions;
  10708. subdivisions = 1;
  10709. }
  10710. var cylinder = new Mesh(name, scene);
  10711. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  10712. vertexData.applyToMesh(cylinder, updatable);
  10713. return cylinder;
  10714. };
  10715. // Torus (Code from SharpDX.org)
  10716. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  10717. var torus = new Mesh(name, scene);
  10718. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  10719. vertexData.applyToMesh(torus, updatable);
  10720. return torus;
  10721. };
  10722. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  10723. var torusKnot = new Mesh(name, scene);
  10724. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  10725. vertexData.applyToMesh(torusKnot, updatable);
  10726. return torusKnot;
  10727. };
  10728. // Lines
  10729. Mesh.CreateLines = function (name, points, scene, updatable) {
  10730. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  10731. var vertexData = BABYLON.VertexData.CreateLines(points);
  10732. vertexData.applyToMesh(lines, updatable);
  10733. return lines;
  10734. };
  10735. // Plane & ground
  10736. Mesh.CreatePlane = function (name, size, scene, updatable) {
  10737. var plane = new Mesh(name, scene);
  10738. var vertexData = BABYLON.VertexData.CreatePlane(size);
  10739. vertexData.applyToMesh(plane, updatable);
  10740. return plane;
  10741. };
  10742. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10743. var ground = new BABYLON.GroundMesh(name, scene);
  10744. ground._setReady(false);
  10745. ground._subdivisions = subdivisions;
  10746. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10747. vertexData.applyToMesh(ground, updatable);
  10748. ground._setReady(true);
  10749. return ground;
  10750. };
  10751. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10752. var tiledGround = new Mesh(name, scene);
  10753. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10754. vertexData.applyToMesh(tiledGround, updatable);
  10755. return tiledGround;
  10756. };
  10757. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  10758. var ground = new BABYLON.GroundMesh(name, scene);
  10759. ground._subdivisions = subdivisions;
  10760. ground._setReady(false);
  10761. var onload = function (img) {
  10762. // Getting height map data
  10763. var canvas = document.createElement("canvas");
  10764. var context = canvas.getContext("2d");
  10765. var heightMapWidth = img.width;
  10766. var heightMapHeight = img.height;
  10767. canvas.width = heightMapWidth;
  10768. canvas.height = heightMapHeight;
  10769. context.drawImage(img, 0, 0);
  10770. // Create VertexData from map data
  10771. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10772. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10773. vertexData.applyToMesh(ground, updatable);
  10774. ground._setReady(true);
  10775. //execute ready callback, if set
  10776. if (onReady) {
  10777. onReady(ground);
  10778. }
  10779. };
  10780. BABYLON.Tools.LoadImage(url, onload, function () {
  10781. }, scene.database);
  10782. return ground;
  10783. };
  10784. // Tools
  10785. Mesh.MinMax = function (meshes) {
  10786. var minVector = null;
  10787. var maxVector = null;
  10788. for (var i in meshes) {
  10789. var mesh = meshes[i];
  10790. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10791. if (!minVector) {
  10792. minVector = boundingBox.minimumWorld;
  10793. maxVector = boundingBox.maximumWorld;
  10794. continue;
  10795. }
  10796. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10797. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10798. }
  10799. return {
  10800. min: minVector,
  10801. max: maxVector
  10802. };
  10803. };
  10804. Mesh.Center = function (meshesOrMinMaxVector) {
  10805. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  10806. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10807. };
  10808. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10809. if (disposeSource === void 0) { disposeSource = true; }
  10810. var source = meshes[0];
  10811. var material = source.material;
  10812. var scene = source.getScene();
  10813. if (!allow32BitsIndices) {
  10814. var totalVertices = 0;
  10815. for (var index = 0; index < meshes.length; index++) {
  10816. totalVertices += meshes[index].getTotalVertices();
  10817. if (totalVertices > 65536) {
  10818. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10819. return null;
  10820. }
  10821. }
  10822. }
  10823. // Merge
  10824. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10825. vertexData.transform(source.getWorldMatrix());
  10826. for (index = 1; index < meshes.length; index++) {
  10827. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10828. otherVertexData.transform(meshes[index].getWorldMatrix());
  10829. vertexData.merge(otherVertexData);
  10830. }
  10831. var newMesh = new Mesh(source.name + "_merged", scene);
  10832. vertexData.applyToMesh(newMesh);
  10833. // Setting properties
  10834. newMesh.material = material;
  10835. newMesh.checkCollisions = source.checkCollisions;
  10836. // Cleaning
  10837. if (disposeSource) {
  10838. for (index = 0; index < meshes.length; index++) {
  10839. meshes[index].dispose();
  10840. }
  10841. }
  10842. return newMesh;
  10843. };
  10844. return Mesh;
  10845. })(BABYLON.AbstractMesh);
  10846. BABYLON.Mesh = Mesh;
  10847. })(BABYLON || (BABYLON = {}));
  10848. //# sourceMappingURL=babylon.mesh.js.map
  10849. var BABYLON;
  10850. (function (BABYLON) {
  10851. var GroundMesh = (function (_super) {
  10852. __extends(GroundMesh, _super);
  10853. function GroundMesh(name, scene) {
  10854. _super.call(this, name, scene);
  10855. this.generateOctree = false;
  10856. this._worldInverse = new BABYLON.Matrix();
  10857. }
  10858. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10859. get: function () {
  10860. return this._subdivisions;
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. GroundMesh.prototype.optimize = function (chunksCount) {
  10866. this.subdivide(this._subdivisions);
  10867. this.createOrUpdateSubmeshesOctree(32);
  10868. };
  10869. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10870. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10871. this.getWorldMatrix().invertToRef(this._worldInverse);
  10872. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10873. var pickInfo = this.intersects(ray);
  10874. if (pickInfo.hit) {
  10875. return pickInfo.pickedPoint.y;
  10876. }
  10877. return 0;
  10878. };
  10879. return GroundMesh;
  10880. })(BABYLON.Mesh);
  10881. BABYLON.GroundMesh = GroundMesh;
  10882. })(BABYLON || (BABYLON = {}));
  10883. //# sourceMappingURL=babylon.groundMesh.js.map
  10884. var BABYLON;
  10885. (function (BABYLON) {
  10886. /**
  10887. * Creates an instance based on a source mesh.
  10888. */
  10889. var InstancedMesh = (function (_super) {
  10890. __extends(InstancedMesh, _super);
  10891. function InstancedMesh(name, source) {
  10892. _super.call(this, name, source.getScene());
  10893. source.instances.push(this);
  10894. this._sourceMesh = source;
  10895. this.position.copyFrom(source.position);
  10896. this.rotation.copyFrom(source.rotation);
  10897. this.scaling.copyFrom(source.scaling);
  10898. if (source.rotationQuaternion) {
  10899. this.rotationQuaternion = source.rotationQuaternion.clone();
  10900. }
  10901. this.infiniteDistance = source.infiniteDistance;
  10902. this.setPivotMatrix(source.getPivotMatrix());
  10903. this.refreshBoundingInfo();
  10904. this._syncSubMeshes();
  10905. }
  10906. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10907. // Methods
  10908. get: function () {
  10909. return this._sourceMesh.receiveShadows;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. Object.defineProperty(InstancedMesh.prototype, "material", {
  10915. get: function () {
  10916. return this._sourceMesh.material;
  10917. },
  10918. enumerable: true,
  10919. configurable: true
  10920. });
  10921. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10922. get: function () {
  10923. return this._sourceMesh.visibility;
  10924. },
  10925. enumerable: true,
  10926. configurable: true
  10927. });
  10928. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  10929. get: function () {
  10930. return this._sourceMesh.skeleton;
  10931. },
  10932. enumerable: true,
  10933. configurable: true
  10934. });
  10935. InstancedMesh.prototype.getTotalVertices = function () {
  10936. return this._sourceMesh.getTotalVertices();
  10937. };
  10938. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  10939. get: function () {
  10940. return this._sourceMesh;
  10941. },
  10942. enumerable: true,
  10943. configurable: true
  10944. });
  10945. InstancedMesh.prototype.getVerticesData = function (kind) {
  10946. return this._sourceMesh.getVerticesData(kind);
  10947. };
  10948. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  10949. return this._sourceMesh.isVerticesDataPresent(kind);
  10950. };
  10951. InstancedMesh.prototype.getIndices = function () {
  10952. return this._sourceMesh.getIndices();
  10953. };
  10954. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  10955. get: function () {
  10956. return this._sourceMesh._positions;
  10957. },
  10958. enumerable: true,
  10959. configurable: true
  10960. });
  10961. InstancedMesh.prototype.refreshBoundingInfo = function () {
  10962. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10963. if (data) {
  10964. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  10965. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10966. }
  10967. this._updateBoundingInfo();
  10968. };
  10969. InstancedMesh.prototype._preActivate = function () {
  10970. if (this._currentLOD) {
  10971. this._currentLOD._preActivate();
  10972. }
  10973. };
  10974. InstancedMesh.prototype._activate = function (renderId) {
  10975. if (this._currentLOD) {
  10976. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10977. }
  10978. };
  10979. InstancedMesh.prototype.getLOD = function (camera) {
  10980. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10981. if (this._currentLOD === this.sourceMesh) {
  10982. return this;
  10983. }
  10984. return this._currentLOD;
  10985. };
  10986. InstancedMesh.prototype._syncSubMeshes = function () {
  10987. this.releaseSubMeshes();
  10988. if (this._sourceMesh.subMeshes) {
  10989. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10990. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10991. }
  10992. }
  10993. };
  10994. InstancedMesh.prototype._generatePointsArray = function () {
  10995. return this._sourceMesh._generatePointsArray();
  10996. };
  10997. // Clone
  10998. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10999. var result = this._sourceMesh.createInstance(name);
  11000. // Deep copy
  11001. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11002. // Bounding info
  11003. this.refreshBoundingInfo();
  11004. // Parent
  11005. if (newParent) {
  11006. result.parent = newParent;
  11007. }
  11008. if (!doNotCloneChildren) {
  11009. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11010. var mesh = this.getScene().meshes[index];
  11011. if (mesh.parent === this) {
  11012. mesh.clone(mesh.name, result);
  11013. }
  11014. }
  11015. }
  11016. result.computeWorldMatrix(true);
  11017. return result;
  11018. };
  11019. // Dispoe
  11020. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11021. // Remove from mesh
  11022. var index = this._sourceMesh.instances.indexOf(this);
  11023. this._sourceMesh.instances.splice(index, 1);
  11024. _super.prototype.dispose.call(this, doNotRecurse);
  11025. };
  11026. return InstancedMesh;
  11027. })(BABYLON.AbstractMesh);
  11028. BABYLON.InstancedMesh = InstancedMesh;
  11029. })(BABYLON || (BABYLON = {}));
  11030. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11031. (function (BABYLON) {
  11032. var SubMesh = (function () {
  11033. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11034. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11035. this.materialIndex = materialIndex;
  11036. this.verticesStart = verticesStart;
  11037. this.verticesCount = verticesCount;
  11038. this.indexStart = indexStart;
  11039. this.indexCount = indexCount;
  11040. this._renderId = 0;
  11041. this._mesh = mesh;
  11042. this._renderingMesh = renderingMesh || mesh;
  11043. mesh.subMeshes.push(this);
  11044. this._id = mesh.subMeshes.length - 1;
  11045. if (createBoundingBox) {
  11046. this.refreshBoundingInfo();
  11047. }
  11048. }
  11049. SubMesh.prototype.getBoundingInfo = function () {
  11050. return this._boundingInfo;
  11051. };
  11052. SubMesh.prototype.getMesh = function () {
  11053. return this._mesh;
  11054. };
  11055. SubMesh.prototype.getRenderingMesh = function () {
  11056. return this._renderingMesh;
  11057. };
  11058. SubMesh.prototype.getMaterial = function () {
  11059. var rootMaterial = this._renderingMesh.material;
  11060. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11061. var multiMaterial = rootMaterial;
  11062. return multiMaterial.getSubMaterial(this.materialIndex);
  11063. }
  11064. if (!rootMaterial) {
  11065. return this._mesh.getScene().defaultMaterial;
  11066. }
  11067. return rootMaterial;
  11068. };
  11069. // Methods
  11070. SubMesh.prototype.refreshBoundingInfo = function () {
  11071. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11072. if (!data) {
  11073. this._boundingInfo = this._mesh._boundingInfo;
  11074. return;
  11075. }
  11076. var indices = this._renderingMesh.getIndices();
  11077. var extend;
  11078. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11079. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11080. }
  11081. else {
  11082. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11083. }
  11084. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11085. };
  11086. SubMesh.prototype._checkCollision = function (collider) {
  11087. return this._boundingInfo._checkCollision(collider);
  11088. };
  11089. SubMesh.prototype.updateBoundingInfo = function (world) {
  11090. if (!this._boundingInfo) {
  11091. this.refreshBoundingInfo();
  11092. }
  11093. this._boundingInfo._update(world);
  11094. };
  11095. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11096. return this._boundingInfo.isInFrustum(frustumPlanes);
  11097. };
  11098. SubMesh.prototype.render = function () {
  11099. this._renderingMesh.render(this);
  11100. };
  11101. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11102. if (!this._linesIndexBuffer) {
  11103. var linesIndices = [];
  11104. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11105. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11106. }
  11107. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11108. this.linesIndexCount = linesIndices.length;
  11109. }
  11110. return this._linesIndexBuffer;
  11111. };
  11112. SubMesh.prototype.canIntersects = function (ray) {
  11113. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11114. };
  11115. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11116. var intersectInfo = null;
  11117. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11118. var p0 = positions[indices[index]];
  11119. var p1 = positions[indices[index + 1]];
  11120. var p2 = positions[indices[index + 2]];
  11121. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11122. if (currentIntersectInfo) {
  11123. if (currentIntersectInfo.distance < 0) {
  11124. continue;
  11125. }
  11126. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11127. intersectInfo = currentIntersectInfo;
  11128. intersectInfo.faceId = index / 3;
  11129. if (fastCheck) {
  11130. break;
  11131. }
  11132. }
  11133. }
  11134. }
  11135. return intersectInfo;
  11136. };
  11137. // Clone
  11138. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11139. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11140. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11141. return result;
  11142. };
  11143. // Dispose
  11144. SubMesh.prototype.dispose = function () {
  11145. if (this._linesIndexBuffer) {
  11146. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11147. this._linesIndexBuffer = null;
  11148. }
  11149. // Remove from mesh
  11150. var index = this._mesh.subMeshes.indexOf(this);
  11151. this._mesh.subMeshes.splice(index, 1);
  11152. };
  11153. // Statics
  11154. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11155. var minVertexIndex = Number.MAX_VALUE;
  11156. var maxVertexIndex = -Number.MAX_VALUE;
  11157. renderingMesh = renderingMesh || mesh;
  11158. var indices = renderingMesh.getIndices();
  11159. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11160. var vertexIndex = indices[index];
  11161. if (vertexIndex < minVertexIndex)
  11162. minVertexIndex = vertexIndex;
  11163. if (vertexIndex > maxVertexIndex)
  11164. maxVertexIndex = vertexIndex;
  11165. }
  11166. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11167. };
  11168. return SubMesh;
  11169. })();
  11170. BABYLON.SubMesh = SubMesh;
  11171. })(BABYLON || (BABYLON = {}));
  11172. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11173. (function (BABYLON) {
  11174. var BaseTexture = (function () {
  11175. function BaseTexture(scene) {
  11176. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11177. this.hasAlpha = false;
  11178. this.getAlphaFromRGB = false;
  11179. this.level = 1;
  11180. this.isCube = false;
  11181. this.isRenderTarget = false;
  11182. this.animations = new Array();
  11183. this.coordinatesIndex = 0;
  11184. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11185. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11186. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11187. this.anisotropicFilteringLevel = 4;
  11188. this._scene = scene;
  11189. this._scene.textures.push(this);
  11190. }
  11191. BaseTexture.prototype.getScene = function () {
  11192. return this._scene;
  11193. };
  11194. BaseTexture.prototype.getTextureMatrix = function () {
  11195. return null;
  11196. };
  11197. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11198. return null;
  11199. };
  11200. BaseTexture.prototype.getInternalTexture = function () {
  11201. return this._texture;
  11202. };
  11203. BaseTexture.prototype.isReady = function () {
  11204. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11205. return true;
  11206. }
  11207. if (this._texture) {
  11208. return this._texture.isReady;
  11209. }
  11210. return false;
  11211. };
  11212. BaseTexture.prototype.getSize = function () {
  11213. if (this._texture._width) {
  11214. return { width: this._texture._width, height: this._texture._height };
  11215. }
  11216. if (this._texture._size) {
  11217. return { width: this._texture._size, height: this._texture._size };
  11218. }
  11219. return { width: 0, height: 0 };
  11220. };
  11221. BaseTexture.prototype.getBaseSize = function () {
  11222. if (!this.isReady())
  11223. return { width: 0, height: 0 };
  11224. if (this._texture._size) {
  11225. return { width: this._texture._size, height: this._texture._size };
  11226. }
  11227. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11228. };
  11229. BaseTexture.prototype.scale = function (ratio) {
  11230. };
  11231. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11232. get: function () {
  11233. return false;
  11234. },
  11235. enumerable: true,
  11236. configurable: true
  11237. });
  11238. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11239. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11240. for (var index = 0; index < texturesCache.length; index++) {
  11241. var texturesCacheEntry = texturesCache[index];
  11242. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11243. texturesCache.splice(index, 1);
  11244. return;
  11245. }
  11246. }
  11247. };
  11248. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11249. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11250. for (var index = 0; index < texturesCache.length; index++) {
  11251. var texturesCacheEntry = texturesCache[index];
  11252. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11253. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11254. texturesCacheEntry.references++;
  11255. return texturesCacheEntry;
  11256. }
  11257. }
  11258. }
  11259. return null;
  11260. };
  11261. BaseTexture.prototype.delayLoad = function () {
  11262. };
  11263. BaseTexture.prototype.releaseInternalTexture = function () {
  11264. if (!this._texture) {
  11265. return;
  11266. }
  11267. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11268. this._texture.references--;
  11269. // Final reference ?
  11270. if (this._texture.references === 0) {
  11271. var index = texturesCache.indexOf(this._texture);
  11272. texturesCache.splice(index, 1);
  11273. this._scene.getEngine()._releaseTexture(this._texture);
  11274. delete this._texture;
  11275. }
  11276. };
  11277. BaseTexture.prototype.clone = function () {
  11278. return null;
  11279. };
  11280. BaseTexture.prototype.dispose = function () {
  11281. // Remove from scene
  11282. var index = this._scene.textures.indexOf(this);
  11283. if (index >= 0) {
  11284. this._scene.textures.splice(index, 1);
  11285. }
  11286. if (this._texture === undefined) {
  11287. return;
  11288. }
  11289. this.releaseInternalTexture();
  11290. // Callback
  11291. if (this.onDispose) {
  11292. this.onDispose();
  11293. }
  11294. };
  11295. return BaseTexture;
  11296. })();
  11297. BABYLON.BaseTexture = BaseTexture;
  11298. })(BABYLON || (BABYLON = {}));
  11299. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11300. (function (BABYLON) {
  11301. var RenderingGroup = (function () {
  11302. function RenderingGroup(index, scene) {
  11303. this.index = index;
  11304. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11305. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11306. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11307. this._scene = scene;
  11308. }
  11309. RenderingGroup.prototype.render = function (customRenderFunction) {
  11310. if (customRenderFunction) {
  11311. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11312. return true;
  11313. }
  11314. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11315. return false;
  11316. }
  11317. var engine = this._scene.getEngine();
  11318. // Opaque
  11319. var subIndex;
  11320. var submesh;
  11321. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11322. submesh = this._opaqueSubMeshes.data[subIndex];
  11323. submesh.render();
  11324. }
  11325. // Alpha test
  11326. engine.setAlphaTesting(true);
  11327. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11328. submesh = this._alphaTestSubMeshes.data[subIndex];
  11329. submesh.render();
  11330. }
  11331. engine.setAlphaTesting(false);
  11332. // Transparent
  11333. if (this._transparentSubMeshes.length) {
  11334. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11335. submesh = this._transparentSubMeshes.data[subIndex];
  11336. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11337. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11338. }
  11339. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11340. sortedArray.sort(function (a, b) {
  11341. // Alpha index first
  11342. if (a._alphaIndex > b._alphaIndex) {
  11343. return 1;
  11344. }
  11345. if (a._alphaIndex < b._alphaIndex) {
  11346. return -1;
  11347. }
  11348. // Then distance to camera
  11349. if (a._distanceToCamera < b._distanceToCamera) {
  11350. return 1;
  11351. }
  11352. if (a._distanceToCamera > b._distanceToCamera) {
  11353. return -1;
  11354. }
  11355. return 0;
  11356. });
  11357. // Rendering
  11358. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11359. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11360. submesh = sortedArray[subIndex];
  11361. submesh.render();
  11362. }
  11363. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11364. }
  11365. return true;
  11366. };
  11367. RenderingGroup.prototype.prepare = function () {
  11368. this._opaqueSubMeshes.reset();
  11369. this._transparentSubMeshes.reset();
  11370. this._alphaTestSubMeshes.reset();
  11371. };
  11372. RenderingGroup.prototype.dispatch = function (subMesh) {
  11373. var material = subMesh.getMaterial();
  11374. var mesh = subMesh.getMesh();
  11375. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11376. this._transparentSubMeshes.push(subMesh);
  11377. }
  11378. else if (material.needAlphaTesting()) {
  11379. this._alphaTestSubMeshes.push(subMesh);
  11380. }
  11381. else {
  11382. this._opaqueSubMeshes.push(subMesh); // Opaque
  11383. }
  11384. };
  11385. return RenderingGroup;
  11386. })();
  11387. BABYLON.RenderingGroup = RenderingGroup;
  11388. })(BABYLON || (BABYLON = {}));
  11389. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  11390. (function (BABYLON) {
  11391. var RenderingManager = (function () {
  11392. function RenderingManager(scene) {
  11393. this._renderingGroups = new Array();
  11394. this._scene = scene;
  11395. }
  11396. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11397. if (this._scene._activeParticleSystems.length === 0) {
  11398. return;
  11399. }
  11400. // Particles
  11401. var beforeParticlesDate = BABYLON.Tools.Now;
  11402. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11403. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11404. if (particleSystem.renderingGroupId !== index) {
  11405. continue;
  11406. }
  11407. this._clearDepthBuffer();
  11408. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11409. this._scene._activeParticles += particleSystem.render();
  11410. }
  11411. }
  11412. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11413. };
  11414. RenderingManager.prototype._renderSprites = function (index) {
  11415. if (this._scene.spriteManagers.length === 0) {
  11416. return;
  11417. }
  11418. // Sprites
  11419. var beforeSpritessDate = BABYLON.Tools.Now;
  11420. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11421. var spriteManager = this._scene.spriteManagers[id];
  11422. if (spriteManager.renderingGroupId === index) {
  11423. this._clearDepthBuffer();
  11424. spriteManager.render();
  11425. }
  11426. }
  11427. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11428. };
  11429. RenderingManager.prototype._clearDepthBuffer = function () {
  11430. if (this._depthBufferAlreadyCleaned) {
  11431. return;
  11432. }
  11433. this._scene.getEngine().clear(0, false, true);
  11434. this._depthBufferAlreadyCleaned = true;
  11435. };
  11436. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11437. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11438. this._depthBufferAlreadyCleaned = false;
  11439. var renderingGroup = this._renderingGroups[index];
  11440. if (renderingGroup) {
  11441. this._clearDepthBuffer();
  11442. if (!renderingGroup.render(customRenderFunction)) {
  11443. this._renderingGroups.splice(index, 1);
  11444. }
  11445. }
  11446. if (renderSprites) {
  11447. this._renderSprites(index);
  11448. }
  11449. if (renderParticles) {
  11450. this._renderParticles(index, activeMeshes);
  11451. }
  11452. }
  11453. };
  11454. RenderingManager.prototype.reset = function () {
  11455. for (var index in this._renderingGroups) {
  11456. var renderingGroup = this._renderingGroups[index];
  11457. renderingGroup.prepare();
  11458. }
  11459. };
  11460. RenderingManager.prototype.dispatch = function (subMesh) {
  11461. var mesh = subMesh.getMesh();
  11462. var renderingGroupId = mesh.renderingGroupId || 0;
  11463. if (!this._renderingGroups[renderingGroupId]) {
  11464. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11465. }
  11466. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11467. };
  11468. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11469. return RenderingManager;
  11470. })();
  11471. BABYLON.RenderingManager = RenderingManager;
  11472. })(BABYLON || (BABYLON = {}));
  11473. //# sourceMappingURL=babylon.renderingManager.js.map
  11474. var BABYLON;
  11475. (function (BABYLON) {
  11476. var Texture = (function (_super) {
  11477. __extends(Texture, _super);
  11478. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  11479. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11480. if (onLoad === void 0) { onLoad = null; }
  11481. if (onError === void 0) { onError = null; }
  11482. if (buffer === void 0) { buffer = null; }
  11483. if (deleteBuffer === void 0) { deleteBuffer = false; }
  11484. _super.call(this, scene);
  11485. this.uOffset = 0;
  11486. this.vOffset = 0;
  11487. this.uScale = 1.0;
  11488. this.vScale = 1.0;
  11489. this.uAng = 0;
  11490. this.vAng = 0;
  11491. this.wAng = 0;
  11492. this.name = url;
  11493. this.url = url;
  11494. this._noMipmap = noMipmap;
  11495. this._invertY = invertY;
  11496. this._samplingMode = samplingMode;
  11497. this._buffer = buffer;
  11498. this._deleteBuffer = deleteBuffer;
  11499. if (!url) {
  11500. return;
  11501. }
  11502. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  11503. if (!this._texture) {
  11504. if (!scene.useDelayedTextureLoading) {
  11505. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  11506. if (deleteBuffer) {
  11507. delete this._buffer;
  11508. }
  11509. }
  11510. else {
  11511. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11512. }
  11513. }
  11514. }
  11515. Texture.prototype.delayLoad = function () {
  11516. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11517. return;
  11518. }
  11519. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11520. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  11521. if (!this._texture) {
  11522. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  11523. if (this._deleteBuffer) {
  11524. delete this._buffer;
  11525. }
  11526. }
  11527. };
  11528. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  11529. x -= this.uOffset + 0.5;
  11530. y -= this.vOffset + 0.5;
  11531. z -= 0.5;
  11532. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  11533. t.x *= this.uScale;
  11534. t.y *= this.vScale;
  11535. t.x += 0.5;
  11536. t.y += 0.5;
  11537. t.z += 0.5;
  11538. };
  11539. Texture.prototype.getTextureMatrix = function () {
  11540. 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) {
  11541. return this._cachedTextureMatrix;
  11542. }
  11543. this._cachedUOffset = this.uOffset;
  11544. this._cachedVOffset = this.vOffset;
  11545. this._cachedUScale = this.uScale;
  11546. this._cachedVScale = this.vScale;
  11547. this._cachedUAng = this.uAng;
  11548. this._cachedVAng = this.vAng;
  11549. this._cachedWAng = this.wAng;
  11550. if (!this._cachedTextureMatrix) {
  11551. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11552. this._rowGenerationMatrix = new BABYLON.Matrix();
  11553. this._t0 = BABYLON.Vector3.Zero();
  11554. this._t1 = BABYLON.Vector3.Zero();
  11555. this._t2 = BABYLON.Vector3.Zero();
  11556. }
  11557. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  11558. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  11559. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  11560. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  11561. this._t1.subtractInPlace(this._t0);
  11562. this._t2.subtractInPlace(this._t0);
  11563. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11564. this._cachedTextureMatrix.m[0] = this._t1.x;
  11565. this._cachedTextureMatrix.m[1] = this._t1.y;
  11566. this._cachedTextureMatrix.m[2] = this._t1.z;
  11567. this._cachedTextureMatrix.m[4] = this._t2.x;
  11568. this._cachedTextureMatrix.m[5] = this._t2.y;
  11569. this._cachedTextureMatrix.m[6] = this._t2.z;
  11570. this._cachedTextureMatrix.m[8] = this._t0.x;
  11571. this._cachedTextureMatrix.m[9] = this._t0.y;
  11572. this._cachedTextureMatrix.m[10] = this._t0.z;
  11573. return this._cachedTextureMatrix;
  11574. };
  11575. Texture.prototype.getReflectionTextureMatrix = function () {
  11576. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11577. return this._cachedTextureMatrix;
  11578. }
  11579. if (!this._cachedTextureMatrix) {
  11580. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11581. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11582. }
  11583. this._cachedCoordinatesMode = this.coordinatesMode;
  11584. switch (this.coordinatesMode) {
  11585. case BABYLON.Texture.SPHERICAL_MODE:
  11586. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11587. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11588. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11589. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11590. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11591. break;
  11592. case BABYLON.Texture.PLANAR_MODE:
  11593. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11594. this._cachedTextureMatrix[0] = this.uScale;
  11595. this._cachedTextureMatrix[5] = this.vScale;
  11596. this._cachedTextureMatrix[12] = this.uOffset;
  11597. this._cachedTextureMatrix[13] = this.vOffset;
  11598. break;
  11599. case BABYLON.Texture.PROJECTION_MODE:
  11600. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11601. this._projectionModeMatrix.m[0] = 0.5;
  11602. this._projectionModeMatrix.m[5] = -0.5;
  11603. this._projectionModeMatrix.m[10] = 0.0;
  11604. this._projectionModeMatrix.m[12] = 0.5;
  11605. this._projectionModeMatrix.m[13] = 0.5;
  11606. this._projectionModeMatrix.m[14] = 1.0;
  11607. this._projectionModeMatrix.m[15] = 1.0;
  11608. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11609. break;
  11610. default:
  11611. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11612. break;
  11613. }
  11614. return this._cachedTextureMatrix;
  11615. };
  11616. Texture.prototype.clone = function () {
  11617. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  11618. // Base texture
  11619. newTexture.hasAlpha = this.hasAlpha;
  11620. newTexture.level = this.level;
  11621. newTexture.wrapU = this.wrapU;
  11622. newTexture.wrapV = this.wrapV;
  11623. newTexture.coordinatesIndex = this.coordinatesIndex;
  11624. newTexture.coordinatesMode = this.coordinatesMode;
  11625. // Texture
  11626. newTexture.uOffset = this.uOffset;
  11627. newTexture.vOffset = this.vOffset;
  11628. newTexture.uScale = this.uScale;
  11629. newTexture.vScale = this.vScale;
  11630. newTexture.uAng = this.uAng;
  11631. newTexture.vAng = this.vAng;
  11632. newTexture.wAng = this.wAng;
  11633. return newTexture;
  11634. };
  11635. // Statics
  11636. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  11637. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11638. if (onLoad === void 0) { onLoad = null; }
  11639. if (onError === void 0) { onError = null; }
  11640. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  11641. };
  11642. // Constants
  11643. Texture.NEAREST_SAMPLINGMODE = 1;
  11644. Texture.BILINEAR_SAMPLINGMODE = 2;
  11645. Texture.TRILINEAR_SAMPLINGMODE = 3;
  11646. Texture.EXPLICIT_MODE = 0;
  11647. Texture.SPHERICAL_MODE = 1;
  11648. Texture.PLANAR_MODE = 2;
  11649. Texture.CUBIC_MODE = 3;
  11650. Texture.PROJECTION_MODE = 4;
  11651. Texture.SKYBOX_MODE = 5;
  11652. Texture.CLAMP_ADDRESSMODE = 0;
  11653. Texture.WRAP_ADDRESSMODE = 1;
  11654. Texture.MIRROR_ADDRESSMODE = 2;
  11655. return Texture;
  11656. })(BABYLON.BaseTexture);
  11657. BABYLON.Texture = Texture;
  11658. })(BABYLON || (BABYLON = {}));
  11659. //# sourceMappingURL=babylon.texture.js.map
  11660. var BABYLON;
  11661. (function (BABYLON) {
  11662. var CubeTexture = (function (_super) {
  11663. __extends(CubeTexture, _super);
  11664. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  11665. _super.call(this, scene);
  11666. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  11667. this.name = rootUrl;
  11668. this.url = rootUrl;
  11669. this._noMipmap = noMipmap;
  11670. this.hasAlpha = false;
  11671. this._texture = this._getFromCache(rootUrl, noMipmap);
  11672. if (!extensions) {
  11673. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  11674. }
  11675. this._extensions = extensions;
  11676. if (!this._texture) {
  11677. if (!scene.useDelayedTextureLoading) {
  11678. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  11679. }
  11680. else {
  11681. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11682. }
  11683. }
  11684. this.isCube = true;
  11685. this._textureMatrix = BABYLON.Matrix.Identity();
  11686. }
  11687. CubeTexture.prototype.clone = function () {
  11688. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  11689. // Base texture
  11690. newTexture.level = this.level;
  11691. newTexture.wrapU = this.wrapU;
  11692. newTexture.wrapV = this.wrapV;
  11693. newTexture.coordinatesIndex = this.coordinatesIndex;
  11694. newTexture.coordinatesMode = this.coordinatesMode;
  11695. return newTexture;
  11696. };
  11697. // Methods
  11698. CubeTexture.prototype.delayLoad = function () {
  11699. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11700. return;
  11701. }
  11702. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11703. this._texture = this._getFromCache(this.url, this._noMipmap);
  11704. if (!this._texture) {
  11705. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  11706. }
  11707. };
  11708. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  11709. return this._textureMatrix;
  11710. };
  11711. return CubeTexture;
  11712. })(BABYLON.BaseTexture);
  11713. BABYLON.CubeTexture = CubeTexture;
  11714. })(BABYLON || (BABYLON = {}));
  11715. //# sourceMappingURL=babylon.cubeTexture.js.map
  11716. var BABYLON;
  11717. (function (BABYLON) {
  11718. var RenderTargetTexture = (function (_super) {
  11719. __extends(RenderTargetTexture, _super);
  11720. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  11721. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  11722. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  11723. _super.call(this, null, scene, !generateMipMaps);
  11724. this.renderList = new Array();
  11725. this.renderParticles = true;
  11726. this.renderSprites = false;
  11727. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  11728. this._currentRefreshId = -1;
  11729. this._refreshRate = 1;
  11730. this.name = name;
  11731. this.isRenderTarget = true;
  11732. this._size = size;
  11733. this._generateMipMaps = generateMipMaps;
  11734. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  11735. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  11736. // Rendering groups
  11737. this._renderingManager = new BABYLON.RenderingManager(scene);
  11738. }
  11739. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  11740. this._currentRefreshId = -1;
  11741. };
  11742. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  11743. get: function () {
  11744. return this._refreshRate;
  11745. },
  11746. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11747. set: function (value) {
  11748. this._refreshRate = value;
  11749. this.resetRefreshCounter();
  11750. },
  11751. enumerable: true,
  11752. configurable: true
  11753. });
  11754. RenderTargetTexture.prototype._shouldRender = function () {
  11755. if (this._currentRefreshId === -1) {
  11756. this._currentRefreshId = 1;
  11757. return true;
  11758. }
  11759. if (this.refreshRate === this._currentRefreshId) {
  11760. this._currentRefreshId = 1;
  11761. return true;
  11762. }
  11763. this._currentRefreshId++;
  11764. return false;
  11765. };
  11766. RenderTargetTexture.prototype.isReady = function () {
  11767. if (!this.getScene().renderTargetsEnabled) {
  11768. return false;
  11769. }
  11770. return _super.prototype.isReady.call(this);
  11771. };
  11772. RenderTargetTexture.prototype.getRenderSize = function () {
  11773. return this._size;
  11774. };
  11775. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11776. get: function () {
  11777. return true;
  11778. },
  11779. enumerable: true,
  11780. configurable: true
  11781. });
  11782. RenderTargetTexture.prototype.scale = function (ratio) {
  11783. var newSize = this._size * ratio;
  11784. this.resize(newSize, this._generateMipMaps);
  11785. };
  11786. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11787. this.releaseInternalTexture();
  11788. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11789. };
  11790. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11791. var scene = this.getScene();
  11792. var engine = scene.getEngine();
  11793. if (!this.activeCamera) {
  11794. this.activeCamera = scene.activeCamera;
  11795. }
  11796. if (this._waitingRenderList) {
  11797. this.renderList = [];
  11798. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11799. var id = this._waitingRenderList[index];
  11800. this.renderList.push(scene.getMeshByID(id));
  11801. }
  11802. delete this._waitingRenderList;
  11803. }
  11804. if (this.renderList && this.renderList.length === 0) {
  11805. return;
  11806. }
  11807. // Bind
  11808. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11809. engine.bindFramebuffer(this._texture);
  11810. }
  11811. // Clear
  11812. engine.clear(scene.clearColor, true, true);
  11813. this._renderingManager.reset();
  11814. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  11815. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  11816. var mesh = currentRenderList[meshIndex];
  11817. if (mesh) {
  11818. if (!mesh.isReady()) {
  11819. // Reset _currentRefreshId
  11820. this.resetRefreshCounter();
  11821. continue;
  11822. }
  11823. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  11824. mesh._activate(scene.getRenderId());
  11825. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11826. var subMesh = mesh.subMeshes[subIndex];
  11827. scene._activeVertices += subMesh.indexCount;
  11828. this._renderingManager.dispatch(subMesh);
  11829. }
  11830. }
  11831. }
  11832. }
  11833. if (!this._doNotChangeAspectRatio) {
  11834. scene.updateTransformMatrix(true);
  11835. }
  11836. if (this.onBeforeRender) {
  11837. this.onBeforeRender();
  11838. }
  11839. // Render
  11840. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  11841. if (useCameraPostProcess) {
  11842. scene.postProcessManager._finalizeFrame(false, this._texture);
  11843. }
  11844. if (this.onAfterRender) {
  11845. this.onAfterRender();
  11846. }
  11847. // Unbind
  11848. engine.unBindFramebuffer(this._texture);
  11849. if (!this._doNotChangeAspectRatio) {
  11850. scene.updateTransformMatrix(true);
  11851. }
  11852. };
  11853. RenderTargetTexture.prototype.clone = function () {
  11854. var textureSize = this.getSize();
  11855. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11856. // Base texture
  11857. newTexture.hasAlpha = this.hasAlpha;
  11858. newTexture.level = this.level;
  11859. // RenderTarget Texture
  11860. newTexture.coordinatesMode = this.coordinatesMode;
  11861. newTexture.renderList = this.renderList.slice(0);
  11862. return newTexture;
  11863. };
  11864. return RenderTargetTexture;
  11865. })(BABYLON.Texture);
  11866. BABYLON.RenderTargetTexture = RenderTargetTexture;
  11867. })(BABYLON || (BABYLON = {}));
  11868. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  11869. var BABYLON;
  11870. (function (BABYLON) {
  11871. var ProceduralTexture = (function (_super) {
  11872. __extends(ProceduralTexture, _super);
  11873. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11874. if (generateMipMaps === void 0) { generateMipMaps = true; }
  11875. _super.call(this, null, scene, !generateMipMaps);
  11876. this._currentRefreshId = -1;
  11877. this._refreshRate = 1;
  11878. this._vertexDeclaration = [2];
  11879. this._vertexStrideSize = 2 * 4;
  11880. this._uniforms = new Array();
  11881. this._samplers = new Array();
  11882. this._textures = new Array();
  11883. this._floats = new Array();
  11884. this._floatsArrays = {};
  11885. this._colors3 = new Array();
  11886. this._colors4 = new Array();
  11887. this._vectors2 = new Array();
  11888. this._vectors3 = new Array();
  11889. this._matrices = new Array();
  11890. this._fallbackTextureUsed = false;
  11891. scene._proceduralTextures.push(this);
  11892. this.name = name;
  11893. this.isRenderTarget = true;
  11894. this._size = size;
  11895. this._generateMipMaps = generateMipMaps;
  11896. this.setFragment(fragment);
  11897. this._fallbackTexture = fallbackTexture;
  11898. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11899. // VBO
  11900. var vertices = [];
  11901. vertices.push(1, 1);
  11902. vertices.push(-1, 1);
  11903. vertices.push(-1, -1);
  11904. vertices.push(1, -1);
  11905. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11906. // Indices
  11907. var indices = [];
  11908. indices.push(0);
  11909. indices.push(1);
  11910. indices.push(2);
  11911. indices.push(0);
  11912. indices.push(2);
  11913. indices.push(3);
  11914. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11915. }
  11916. ProceduralTexture.prototype.reset = function () {
  11917. if (this._effect === undefined) {
  11918. return;
  11919. }
  11920. var engine = this.getScene().getEngine();
  11921. engine._releaseEffect(this._effect);
  11922. };
  11923. ProceduralTexture.prototype.isReady = function () {
  11924. var _this = this;
  11925. var engine = this.getScene().getEngine();
  11926. var shaders;
  11927. if (!this._fragment) {
  11928. return false;
  11929. }
  11930. if (this._fallbackTextureUsed) {
  11931. return true;
  11932. }
  11933. if (this._fragment.fragmentElement !== undefined) {
  11934. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  11935. }
  11936. else {
  11937. shaders = { vertex: "procedural", fragment: this._fragment };
  11938. }
  11939. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  11940. _this.releaseInternalTexture();
  11941. if (_this._fallbackTexture) {
  11942. _this._texture = _this._fallbackTexture._texture;
  11943. _this._texture.references++;
  11944. }
  11945. _this._fallbackTextureUsed = true;
  11946. });
  11947. return this._effect.isReady();
  11948. };
  11949. ProceduralTexture.prototype.resetRefreshCounter = function () {
  11950. this._currentRefreshId = -1;
  11951. };
  11952. ProceduralTexture.prototype.setFragment = function (fragment) {
  11953. this._fragment = fragment;
  11954. };
  11955. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  11956. get: function () {
  11957. return this._refreshRate;
  11958. },
  11959. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11960. set: function (value) {
  11961. this._refreshRate = value;
  11962. this.resetRefreshCounter();
  11963. },
  11964. enumerable: true,
  11965. configurable: true
  11966. });
  11967. ProceduralTexture.prototype._shouldRender = function () {
  11968. if (!this.isReady() || !this._texture) {
  11969. return false;
  11970. }
  11971. if (this._fallbackTextureUsed) {
  11972. return false;
  11973. }
  11974. if (this._currentRefreshId === -1) {
  11975. this._currentRefreshId = 1;
  11976. return true;
  11977. }
  11978. if (this.refreshRate === this._currentRefreshId) {
  11979. this._currentRefreshId = 1;
  11980. return true;
  11981. }
  11982. this._currentRefreshId++;
  11983. return false;
  11984. };
  11985. ProceduralTexture.prototype.getRenderSize = function () {
  11986. return this._size;
  11987. };
  11988. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11989. if (this._fallbackTextureUsed) {
  11990. return;
  11991. }
  11992. this.releaseInternalTexture();
  11993. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11994. };
  11995. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11996. if (this._uniforms.indexOf(uniformName) === -1) {
  11997. this._uniforms.push(uniformName);
  11998. }
  11999. };
  12000. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12001. if (this._samplers.indexOf(name) === -1) {
  12002. this._samplers.push(name);
  12003. }
  12004. this._textures[name] = texture;
  12005. return this;
  12006. };
  12007. ProceduralTexture.prototype.setFloat = function (name, value) {
  12008. this._checkUniform(name);
  12009. this._floats[name] = value;
  12010. return this;
  12011. };
  12012. ProceduralTexture.prototype.setFloats = function (name, value) {
  12013. this._checkUniform(name);
  12014. this._floatsArrays[name] = value;
  12015. return this;
  12016. };
  12017. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12018. this._checkUniform(name);
  12019. this._colors3[name] = value;
  12020. return this;
  12021. };
  12022. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12023. this._checkUniform(name);
  12024. this._colors4[name] = value;
  12025. return this;
  12026. };
  12027. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12028. this._checkUniform(name);
  12029. this._vectors2[name] = value;
  12030. return this;
  12031. };
  12032. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12033. this._checkUniform(name);
  12034. this._vectors3[name] = value;
  12035. return this;
  12036. };
  12037. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12038. this._checkUniform(name);
  12039. this._matrices[name] = value;
  12040. return this;
  12041. };
  12042. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12043. var scene = this.getScene();
  12044. var engine = scene.getEngine();
  12045. engine.bindFramebuffer(this._texture);
  12046. // Clear
  12047. engine.clear(scene.clearColor, true, true);
  12048. // Render
  12049. engine.enableEffect(this._effect);
  12050. engine.setState(false);
  12051. for (var name in this._textures) {
  12052. this._effect.setTexture(name, this._textures[name]);
  12053. }
  12054. for (name in this._floats) {
  12055. this._effect.setFloat(name, this._floats[name]);
  12056. }
  12057. for (name in this._floatsArrays) {
  12058. this._effect.setArray(name, this._floatsArrays[name]);
  12059. }
  12060. for (name in this._colors3) {
  12061. this._effect.setColor3(name, this._colors3[name]);
  12062. }
  12063. for (name in this._colors4) {
  12064. var color = this._colors4[name];
  12065. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12066. }
  12067. for (name in this._vectors2) {
  12068. this._effect.setVector2(name, this._vectors2[name]);
  12069. }
  12070. for (name in this._vectors3) {
  12071. this._effect.setVector3(name, this._vectors3[name]);
  12072. }
  12073. for (name in this._matrices) {
  12074. this._effect.setMatrix(name, this._matrices[name]);
  12075. }
  12076. // VBOs
  12077. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12078. // Draw order
  12079. engine.draw(true, 0, 6);
  12080. // Unbind
  12081. engine.unBindFramebuffer(this._texture);
  12082. };
  12083. ProceduralTexture.prototype.clone = function () {
  12084. var textureSize = this.getSize();
  12085. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12086. // Base texture
  12087. newTexture.hasAlpha = this.hasAlpha;
  12088. newTexture.level = this.level;
  12089. // RenderTarget Texture
  12090. newTexture.coordinatesMode = this.coordinatesMode;
  12091. return newTexture;
  12092. };
  12093. ProceduralTexture.prototype.dispose = function () {
  12094. var index = this.getScene()._proceduralTextures.indexOf(this);
  12095. if (index >= 0) {
  12096. this.getScene()._proceduralTextures.splice(index, 1);
  12097. }
  12098. _super.prototype.dispose.call(this);
  12099. };
  12100. return ProceduralTexture;
  12101. })(BABYLON.Texture);
  12102. BABYLON.ProceduralTexture = ProceduralTexture;
  12103. })(BABYLON || (BABYLON = {}));
  12104. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12105. var BABYLON;
  12106. (function (BABYLON) {
  12107. var WoodProceduralTexture = (function (_super) {
  12108. __extends(WoodProceduralTexture, _super);
  12109. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12110. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12111. this._ampScale = 100.0;
  12112. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12113. this.updateShaderUniforms();
  12114. this.refreshRate = 0;
  12115. }
  12116. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12117. this.setFloat("ampScale", this._ampScale);
  12118. this.setColor3("woodColor", this._woodColor);
  12119. };
  12120. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12121. get: function () {
  12122. return this._ampScale;
  12123. },
  12124. set: function (value) {
  12125. this._ampScale = value;
  12126. this.updateShaderUniforms();
  12127. },
  12128. enumerable: true,
  12129. configurable: true
  12130. });
  12131. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12132. get: function () {
  12133. return this._woodColor;
  12134. },
  12135. set: function (value) {
  12136. this._woodColor = value;
  12137. this.updateShaderUniforms();
  12138. },
  12139. enumerable: true,
  12140. configurable: true
  12141. });
  12142. return WoodProceduralTexture;
  12143. })(BABYLON.ProceduralTexture);
  12144. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12145. var FireProceduralTexture = (function (_super) {
  12146. __extends(FireProceduralTexture, _super);
  12147. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12148. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12149. this._time = 0.0;
  12150. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12151. this._shift = 1.6;
  12152. this._autoGenerateTime = true;
  12153. this._alphaThreshold = 0.5;
  12154. this._fireColors = FireProceduralTexture.RedFireColors;
  12155. this.updateShaderUniforms();
  12156. this.refreshRate = 1;
  12157. }
  12158. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12159. this.setFloat("time", this._time);
  12160. this.setVector2("speed", this._speed);
  12161. this.setFloat("shift", this._shift);
  12162. this.setColor3("c1", this._fireColors[0]);
  12163. this.setColor3("c2", this._fireColors[1]);
  12164. this.setColor3("c3", this._fireColors[2]);
  12165. this.setColor3("c4", this._fireColors[3]);
  12166. this.setColor3("c5", this._fireColors[4]);
  12167. this.setColor3("c6", this._fireColors[5]);
  12168. this.setFloat("alphaThreshold", this._alphaThreshold);
  12169. };
  12170. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12171. if (this._autoGenerateTime) {
  12172. this._time += this.getScene().getAnimationRatio() * 0.03;
  12173. this.updateShaderUniforms();
  12174. }
  12175. _super.prototype.render.call(this, useCameraPostProcess);
  12176. };
  12177. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12178. get: function () {
  12179. return [
  12180. new BABYLON.Color3(0.5, 0.0, 1.0),
  12181. new BABYLON.Color3(0.9, 0.0, 1.0),
  12182. new BABYLON.Color3(0.2, 0.0, 1.0),
  12183. new BABYLON.Color3(1.0, 0.9, 1.0),
  12184. new BABYLON.Color3(0.1, 0.1, 1.0),
  12185. new BABYLON.Color3(0.9, 0.9, 1.0)
  12186. ];
  12187. },
  12188. enumerable: true,
  12189. configurable: true
  12190. });
  12191. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12192. get: function () {
  12193. return [
  12194. new BABYLON.Color3(0.5, 1.0, 0.0),
  12195. new BABYLON.Color3(0.5, 1.0, 0.0),
  12196. new BABYLON.Color3(0.3, 0.4, 0.0),
  12197. new BABYLON.Color3(0.5, 1.0, 0.0),
  12198. new BABYLON.Color3(0.2, 0.0, 0.0),
  12199. new BABYLON.Color3(0.5, 1.0, 0.0)
  12200. ];
  12201. },
  12202. enumerable: true,
  12203. configurable: true
  12204. });
  12205. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12206. get: function () {
  12207. return [
  12208. new BABYLON.Color3(0.5, 0.0, 0.1),
  12209. new BABYLON.Color3(0.9, 0.0, 0.0),
  12210. new BABYLON.Color3(0.2, 0.0, 0.0),
  12211. new BABYLON.Color3(1.0, 0.9, 0.0),
  12212. new BABYLON.Color3(0.1, 0.1, 0.1),
  12213. new BABYLON.Color3(0.9, 0.9, 0.9)
  12214. ];
  12215. },
  12216. enumerable: true,
  12217. configurable: true
  12218. });
  12219. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12220. get: function () {
  12221. return [
  12222. new BABYLON.Color3(0.1, 0.0, 0.5),
  12223. new BABYLON.Color3(0.0, 0.0, 0.5),
  12224. new BABYLON.Color3(0.1, 0.0, 0.2),
  12225. new BABYLON.Color3(0.0, 0.0, 1.0),
  12226. new BABYLON.Color3(0.1, 0.2, 0.3),
  12227. new BABYLON.Color3(0.0, 0.2, 0.9)
  12228. ];
  12229. },
  12230. enumerable: true,
  12231. configurable: true
  12232. });
  12233. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12234. get: function () {
  12235. return this._fireColors;
  12236. },
  12237. set: function (value) {
  12238. this._fireColors = value;
  12239. this.updateShaderUniforms();
  12240. },
  12241. enumerable: true,
  12242. configurable: true
  12243. });
  12244. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12245. get: function () {
  12246. return this._time;
  12247. },
  12248. set: function (value) {
  12249. this._time = value;
  12250. this.updateShaderUniforms();
  12251. },
  12252. enumerable: true,
  12253. configurable: true
  12254. });
  12255. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12256. get: function () {
  12257. return this._speed;
  12258. },
  12259. set: function (value) {
  12260. this._speed = value;
  12261. this.updateShaderUniforms();
  12262. },
  12263. enumerable: true,
  12264. configurable: true
  12265. });
  12266. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12267. get: function () {
  12268. return this._shift;
  12269. },
  12270. set: function (value) {
  12271. this._shift = value;
  12272. this.updateShaderUniforms();
  12273. },
  12274. enumerable: true,
  12275. configurable: true
  12276. });
  12277. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12278. get: function () {
  12279. return this._alphaThreshold;
  12280. },
  12281. set: function (value) {
  12282. this._alphaThreshold = value;
  12283. this.updateShaderUniforms();
  12284. },
  12285. enumerable: true,
  12286. configurable: true
  12287. });
  12288. return FireProceduralTexture;
  12289. })(BABYLON.ProceduralTexture);
  12290. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12291. var CloudProceduralTexture = (function (_super) {
  12292. __extends(CloudProceduralTexture, _super);
  12293. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12294. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12295. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12296. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12297. this.updateShaderUniforms();
  12298. this.refreshRate = 0;
  12299. }
  12300. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12301. this.setColor3("skyColor", this._skyColor);
  12302. this.setColor3("cloudColor", this._cloudColor);
  12303. };
  12304. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12305. get: function () {
  12306. return this._skyColor;
  12307. },
  12308. set: function (value) {
  12309. this._skyColor = value;
  12310. this.updateShaderUniforms();
  12311. },
  12312. enumerable: true,
  12313. configurable: true
  12314. });
  12315. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12316. get: function () {
  12317. return this._cloudColor;
  12318. },
  12319. set: function (value) {
  12320. this._cloudColor = value;
  12321. this.updateShaderUniforms();
  12322. },
  12323. enumerable: true,
  12324. configurable: true
  12325. });
  12326. return CloudProceduralTexture;
  12327. })(BABYLON.ProceduralTexture);
  12328. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12329. var GrassProceduralTexture = (function (_super) {
  12330. __extends(GrassProceduralTexture, _super);
  12331. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12332. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12333. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12334. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12335. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12336. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12337. this._grassColors = [
  12338. new BABYLON.Color3(0.29, 0.38, 0.02),
  12339. new BABYLON.Color3(0.36, 0.49, 0.09),
  12340. new BABYLON.Color3(0.51, 0.6, 0.28)
  12341. ];
  12342. this.updateShaderUniforms();
  12343. this.refreshRate = 0;
  12344. }
  12345. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  12346. this.setColor3("herb1Color", this._grassColors[0]);
  12347. this.setColor3("herb2Color", this._grassColors[1]);
  12348. this.setColor3("herb3Color", this._grassColors[2]);
  12349. this.setColor3("groundColor", this._groundColor);
  12350. };
  12351. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  12352. get: function () {
  12353. return this._grassColors;
  12354. },
  12355. set: function (value) {
  12356. this._grassColors = value;
  12357. this.updateShaderUniforms();
  12358. },
  12359. enumerable: true,
  12360. configurable: true
  12361. });
  12362. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  12363. get: function () {
  12364. return this._groundColor;
  12365. },
  12366. set: function (value) {
  12367. this.groundColor = value;
  12368. this.updateShaderUniforms();
  12369. },
  12370. enumerable: true,
  12371. configurable: true
  12372. });
  12373. return GrassProceduralTexture;
  12374. })(BABYLON.ProceduralTexture);
  12375. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  12376. var RoadProceduralTexture = (function (_super) {
  12377. __extends(RoadProceduralTexture, _super);
  12378. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12379. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  12380. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  12381. this.updateShaderUniforms();
  12382. this.refreshRate = 0;
  12383. }
  12384. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  12385. this.setColor3("roadColor", this._roadColor);
  12386. };
  12387. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  12388. get: function () {
  12389. return this._roadColor;
  12390. },
  12391. set: function (value) {
  12392. this._roadColor = value;
  12393. this.updateShaderUniforms();
  12394. },
  12395. enumerable: true,
  12396. configurable: true
  12397. });
  12398. return RoadProceduralTexture;
  12399. })(BABYLON.ProceduralTexture);
  12400. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  12401. var BrickProceduralTexture = (function (_super) {
  12402. __extends(BrickProceduralTexture, _super);
  12403. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12404. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  12405. this._numberOfBricksHeight = 15;
  12406. this._numberOfBricksWidth = 5;
  12407. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12408. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12409. this.updateShaderUniforms();
  12410. this.refreshRate = 0;
  12411. }
  12412. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  12413. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  12414. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  12415. this.setColor3("brickColor", this._brickColor);
  12416. this.setColor3("jointColor", this._jointColor);
  12417. };
  12418. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  12419. get: function () {
  12420. return this._numberOfBricksHeight;
  12421. },
  12422. enumerable: true,
  12423. configurable: true
  12424. });
  12425. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  12426. set: function (value) {
  12427. this._numberOfBricksHeight = value;
  12428. this.updateShaderUniforms();
  12429. },
  12430. enumerable: true,
  12431. configurable: true
  12432. });
  12433. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  12434. get: function () {
  12435. return this._numberOfBricksWidth;
  12436. },
  12437. set: function (value) {
  12438. this._numberOfBricksHeight = value;
  12439. this.updateShaderUniforms();
  12440. },
  12441. enumerable: true,
  12442. configurable: true
  12443. });
  12444. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  12445. get: function () {
  12446. return this._jointColor;
  12447. },
  12448. set: function (value) {
  12449. this._jointColor = value;
  12450. this.updateShaderUniforms();
  12451. },
  12452. enumerable: true,
  12453. configurable: true
  12454. });
  12455. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  12456. get: function () {
  12457. return this._brickColor;
  12458. },
  12459. set: function (value) {
  12460. this._brickColor = value;
  12461. this.updateShaderUniforms();
  12462. },
  12463. enumerable: true,
  12464. configurable: true
  12465. });
  12466. return BrickProceduralTexture;
  12467. })(BABYLON.ProceduralTexture);
  12468. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  12469. var MarbleProceduralTexture = (function (_super) {
  12470. __extends(MarbleProceduralTexture, _super);
  12471. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12472. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  12473. this._numberOfTilesHeight = 3;
  12474. this._numberOfTilesWidth = 3;
  12475. this._amplitude = 9.0;
  12476. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12477. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12478. this.updateShaderUniforms();
  12479. this.refreshRate = 0;
  12480. }
  12481. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  12482. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  12483. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  12484. this.setFloat("amplitude", this._amplitude);
  12485. this.setColor3("marbleColor", this._marbleColor);
  12486. this.setColor3("jointColor", this._jointColor);
  12487. };
  12488. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  12489. get: function () {
  12490. return this._numberOfTilesHeight;
  12491. },
  12492. set: function (value) {
  12493. this._numberOfTilesHeight = value;
  12494. this.updateShaderUniforms();
  12495. },
  12496. enumerable: true,
  12497. configurable: true
  12498. });
  12499. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  12500. get: function () {
  12501. return this._numberOfTilesWidth;
  12502. },
  12503. set: function (value) {
  12504. this._numberOfTilesWidth = value;
  12505. this.updateShaderUniforms();
  12506. },
  12507. enumerable: true,
  12508. configurable: true
  12509. });
  12510. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  12511. get: function () {
  12512. return this._jointColor;
  12513. },
  12514. set: function (value) {
  12515. this._jointColor = value;
  12516. this.updateShaderUniforms();
  12517. },
  12518. enumerable: true,
  12519. configurable: true
  12520. });
  12521. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  12522. get: function () {
  12523. return this._marbleColor;
  12524. },
  12525. set: function (value) {
  12526. this._marbleColor = value;
  12527. this.updateShaderUniforms();
  12528. },
  12529. enumerable: true,
  12530. configurable: true
  12531. });
  12532. return MarbleProceduralTexture;
  12533. })(BABYLON.ProceduralTexture);
  12534. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  12535. })(BABYLON || (BABYLON = {}));
  12536. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  12537. var BABYLON;
  12538. (function (BABYLON) {
  12539. var CustomProceduralTexture = (function (_super) {
  12540. __extends(CustomProceduralTexture, _super);
  12541. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  12542. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  12543. this._animate = true;
  12544. this._time = 0;
  12545. this._texturePath = texturePath;
  12546. //Try to load json
  12547. this.loadJson(texturePath);
  12548. this.refreshRate = 1;
  12549. }
  12550. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  12551. var _this = this;
  12552. var that = this;
  12553. function noConfigFile() {
  12554. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  12555. try {
  12556. that.setFragment(that._texturePath);
  12557. }
  12558. catch (ex) {
  12559. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  12560. }
  12561. }
  12562. var configFileUrl = jsonUrl + "/config.json";
  12563. var xhr = new XMLHttpRequest();
  12564. xhr.open("GET", configFileUrl, true);
  12565. xhr.addEventListener("load", function () {
  12566. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12567. try {
  12568. _this._config = JSON.parse(xhr.response);
  12569. _this.updateShaderUniforms();
  12570. _this.updateTextures();
  12571. _this.setFragment(_this._texturePath + "/custom");
  12572. _this._animate = _this._config.animate;
  12573. _this.refreshRate = _this._config.refreshrate;
  12574. }
  12575. catch (ex) {
  12576. noConfigFile();
  12577. }
  12578. }
  12579. else {
  12580. noConfigFile();
  12581. }
  12582. }, false);
  12583. xhr.addEventListener("error", function (event) {
  12584. noConfigFile();
  12585. }, false);
  12586. try {
  12587. xhr.send();
  12588. }
  12589. catch (ex) {
  12590. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12591. }
  12592. };
  12593. CustomProceduralTexture.prototype.isReady = function () {
  12594. if (!_super.prototype.isReady.call(this)) {
  12595. return false;
  12596. }
  12597. for (var name in this._textures) {
  12598. var texture = this._textures[name];
  12599. if (!texture.isReady()) {
  12600. return false;
  12601. }
  12602. }
  12603. return true;
  12604. };
  12605. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12606. if (this._animate) {
  12607. this._time += this.getScene().getAnimationRatio() * 0.03;
  12608. this.updateShaderUniforms();
  12609. }
  12610. _super.prototype.render.call(this, useCameraPostProcess);
  12611. };
  12612. CustomProceduralTexture.prototype.updateTextures = function () {
  12613. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12614. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12615. }
  12616. };
  12617. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12618. if (this._config) {
  12619. for (var j = 0; j < this._config.uniforms.length; j++) {
  12620. var uniform = this._config.uniforms[j];
  12621. switch (uniform.type) {
  12622. case "float":
  12623. this.setFloat(uniform.name, uniform.value);
  12624. break;
  12625. case "color3":
  12626. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12627. break;
  12628. case "color4":
  12629. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12630. break;
  12631. case "vector2":
  12632. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12633. break;
  12634. case "vector3":
  12635. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  12636. break;
  12637. }
  12638. }
  12639. }
  12640. this.setFloat("time", this._time);
  12641. };
  12642. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  12643. get: function () {
  12644. return this._animate;
  12645. },
  12646. set: function (value) {
  12647. this._animate = value;
  12648. },
  12649. enumerable: true,
  12650. configurable: true
  12651. });
  12652. return CustomProceduralTexture;
  12653. })(BABYLON.ProceduralTexture);
  12654. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  12655. })(BABYLON || (BABYLON = {}));
  12656. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  12657. var BABYLON;
  12658. (function (BABYLON) {
  12659. var MirrorTexture = (function (_super) {
  12660. __extends(MirrorTexture, _super);
  12661. function MirrorTexture(name, size, scene, generateMipMaps) {
  12662. var _this = this;
  12663. _super.call(this, name, size, scene, generateMipMaps, true);
  12664. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  12665. this._transformMatrix = BABYLON.Matrix.Zero();
  12666. this._mirrorMatrix = BABYLON.Matrix.Zero();
  12667. this.onBeforeRender = function () {
  12668. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  12669. _this._savedViewMatrix = scene.getViewMatrix();
  12670. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  12671. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  12672. scene.clipPlane = _this.mirrorPlane;
  12673. scene.getEngine().cullBackFaces = false;
  12674. };
  12675. this.onAfterRender = function () {
  12676. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  12677. scene.getEngine().cullBackFaces = true;
  12678. delete scene.clipPlane;
  12679. };
  12680. }
  12681. MirrorTexture.prototype.clone = function () {
  12682. var textureSize = this.getSize();
  12683. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12684. // Base texture
  12685. newTexture.hasAlpha = this.hasAlpha;
  12686. newTexture.level = this.level;
  12687. // Mirror Texture
  12688. newTexture.mirrorPlane = this.mirrorPlane.clone();
  12689. newTexture.renderList = this.renderList.slice(0);
  12690. return newTexture;
  12691. };
  12692. return MirrorTexture;
  12693. })(BABYLON.RenderTargetTexture);
  12694. BABYLON.MirrorTexture = MirrorTexture;
  12695. })(BABYLON || (BABYLON = {}));
  12696. //# sourceMappingURL=babylon.mirrorTexture.js.map
  12697. var BABYLON;
  12698. (function (BABYLON) {
  12699. var DynamicTexture = (function (_super) {
  12700. __extends(DynamicTexture, _super);
  12701. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  12702. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12703. _super.call(this, null, scene, !generateMipMaps);
  12704. this.name = name;
  12705. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12706. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12707. this._generateMipMaps = generateMipMaps;
  12708. if (options.getContext) {
  12709. this._canvas = options;
  12710. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12711. }
  12712. else {
  12713. this._canvas = document.createElement("canvas");
  12714. if (options.width) {
  12715. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12716. }
  12717. else {
  12718. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  12719. }
  12720. }
  12721. var textureSize = this.getSize();
  12722. this._canvas.width = textureSize.width;
  12723. this._canvas.height = textureSize.height;
  12724. this._context = this._canvas.getContext("2d");
  12725. }
  12726. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  12727. get: function () {
  12728. return true;
  12729. },
  12730. enumerable: true,
  12731. configurable: true
  12732. });
  12733. DynamicTexture.prototype.scale = function (ratio) {
  12734. var textureSize = this.getSize();
  12735. textureSize.width *= ratio;
  12736. textureSize.height *= ratio;
  12737. this._canvas.width = textureSize.width;
  12738. this._canvas.height = textureSize.height;
  12739. this.releaseInternalTexture();
  12740. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  12741. };
  12742. DynamicTexture.prototype.getContext = function () {
  12743. return this._context;
  12744. };
  12745. DynamicTexture.prototype.clear = function () {
  12746. var size = this.getSize();
  12747. this._context.fillRect(0, 0, size.width, size.height);
  12748. };
  12749. DynamicTexture.prototype.update = function (invertY) {
  12750. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  12751. };
  12752. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  12753. if (update === void 0) { update = true; }
  12754. var size = this.getSize();
  12755. if (clearColor) {
  12756. this._context.fillStyle = clearColor;
  12757. this._context.fillRect(0, 0, size.width, size.height);
  12758. }
  12759. this._context.font = font;
  12760. if (x === null) {
  12761. var textSize = this._context.measureText(text);
  12762. x = (size.width - textSize.width) / 2;
  12763. }
  12764. this._context.fillStyle = color;
  12765. this._context.fillText(text, x, y);
  12766. if (update) {
  12767. this.update(invertY);
  12768. }
  12769. };
  12770. DynamicTexture.prototype.clone = function () {
  12771. var textureSize = this.getSize();
  12772. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12773. // Base texture
  12774. newTexture.hasAlpha = this.hasAlpha;
  12775. newTexture.level = this.level;
  12776. // Dynamic Texture
  12777. newTexture.wrapU = this.wrapU;
  12778. newTexture.wrapV = this.wrapV;
  12779. return newTexture;
  12780. };
  12781. return DynamicTexture;
  12782. })(BABYLON.Texture);
  12783. BABYLON.DynamicTexture = DynamicTexture;
  12784. })(BABYLON || (BABYLON = {}));
  12785. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12786. var BABYLON;
  12787. (function (BABYLON) {
  12788. var VideoTexture = (function (_super) {
  12789. __extends(VideoTexture, _super);
  12790. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12791. var _this = this;
  12792. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12793. _super.call(this, null, scene, !generateMipMaps, invertY);
  12794. this._autoLaunch = true;
  12795. this.name = name;
  12796. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12797. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12798. var requiredWidth = size.width || size;
  12799. var requiredHeight = size.height || size;
  12800. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12801. var textureSize = this.getSize();
  12802. this.video = document.createElement("video");
  12803. this.video.width = textureSize.width;
  12804. this.video.height = textureSize.height;
  12805. this.video.autoplay = false;
  12806. this.video.loop = true;
  12807. this.video.addEventListener("canplaythrough", function () {
  12808. if (_this._texture) {
  12809. _this._texture.isReady = true;
  12810. }
  12811. });
  12812. urls.forEach(function (url) {
  12813. var source = document.createElement("source");
  12814. source.src = url;
  12815. _this.video.appendChild(source);
  12816. });
  12817. this._lastUpdate = BABYLON.Tools.Now;
  12818. }
  12819. VideoTexture.prototype.update = function () {
  12820. if (this._autoLaunch) {
  12821. this._autoLaunch = false;
  12822. this.video.play();
  12823. }
  12824. var now = BABYLON.Tools.Now;
  12825. if (now - this._lastUpdate < 15) {
  12826. return false;
  12827. }
  12828. this._lastUpdate = now;
  12829. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12830. return true;
  12831. };
  12832. return VideoTexture;
  12833. })(BABYLON.Texture);
  12834. BABYLON.VideoTexture = VideoTexture;
  12835. })(BABYLON || (BABYLON = {}));
  12836. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  12837. (function (BABYLON) {
  12838. var EffectFallbacks = (function () {
  12839. function EffectFallbacks() {
  12840. this._defines = {};
  12841. this._currentRank = 32;
  12842. this._maxRank = -1;
  12843. }
  12844. EffectFallbacks.prototype.addFallback = function (rank, define) {
  12845. if (!this._defines[rank]) {
  12846. if (rank < this._currentRank) {
  12847. this._currentRank = rank;
  12848. }
  12849. if (rank > this._maxRank) {
  12850. this._maxRank = rank;
  12851. }
  12852. this._defines[rank] = new Array();
  12853. }
  12854. this._defines[rank].push(define);
  12855. };
  12856. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  12857. get: function () {
  12858. return this._currentRank <= this._maxRank;
  12859. },
  12860. enumerable: true,
  12861. configurable: true
  12862. });
  12863. EffectFallbacks.prototype.reduce = function (currentDefines) {
  12864. var currentFallbacks = this._defines[this._currentRank];
  12865. for (var index = 0; index < currentFallbacks.length; index++) {
  12866. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  12867. }
  12868. this._currentRank++;
  12869. return currentDefines;
  12870. };
  12871. return EffectFallbacks;
  12872. })();
  12873. BABYLON.EffectFallbacks = EffectFallbacks;
  12874. var Effect = (function () {
  12875. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  12876. var _this = this;
  12877. this._isReady = false;
  12878. this._compilationError = "";
  12879. this._valueCache = [];
  12880. this._engine = engine;
  12881. this.name = baseName;
  12882. this.defines = defines;
  12883. this._uniformsNames = uniformsNames.concat(samplers);
  12884. this._samplers = samplers;
  12885. this._attributesNames = attributesNames;
  12886. this.onError = onError;
  12887. this.onCompiled = onCompiled;
  12888. var vertexSource;
  12889. var fragmentSource;
  12890. if (baseName.vertexElement) {
  12891. vertexSource = document.getElementById(baseName.vertexElement);
  12892. if (!vertexSource) {
  12893. vertexSource = baseName.vertexElement;
  12894. }
  12895. }
  12896. else {
  12897. vertexSource = baseName.vertex || baseName;
  12898. }
  12899. if (baseName.fragmentElement) {
  12900. fragmentSource = document.getElementById(baseName.fragmentElement);
  12901. if (!fragmentSource) {
  12902. fragmentSource = baseName.fragmentElement;
  12903. }
  12904. }
  12905. else {
  12906. fragmentSource = baseName.fragment || baseName;
  12907. }
  12908. this._loadVertexShader(vertexSource, function (vertexCode) {
  12909. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12910. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12911. });
  12912. });
  12913. }
  12914. // Properties
  12915. Effect.prototype.isReady = function () {
  12916. return this._isReady;
  12917. };
  12918. Effect.prototype.getProgram = function () {
  12919. return this._program;
  12920. };
  12921. Effect.prototype.getAttributesNames = function () {
  12922. return this._attributesNames;
  12923. };
  12924. Effect.prototype.getAttributeLocation = function (index) {
  12925. return this._attributes[index];
  12926. };
  12927. Effect.prototype.getAttributeLocationByName = function (name) {
  12928. var index = this._attributesNames.indexOf(name);
  12929. return this._attributes[index];
  12930. };
  12931. Effect.prototype.getAttributesCount = function () {
  12932. return this._attributes.length;
  12933. };
  12934. Effect.prototype.getUniformIndex = function (uniformName) {
  12935. return this._uniformsNames.indexOf(uniformName);
  12936. };
  12937. Effect.prototype.getUniform = function (uniformName) {
  12938. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  12939. };
  12940. Effect.prototype.getSamplers = function () {
  12941. return this._samplers;
  12942. };
  12943. Effect.prototype.getCompilationError = function () {
  12944. return this._compilationError;
  12945. };
  12946. // Methods
  12947. Effect.prototype._loadVertexShader = function (vertex, callback) {
  12948. // DOM element ?
  12949. if (vertex instanceof HTMLElement) {
  12950. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  12951. callback(vertexCode);
  12952. return;
  12953. }
  12954. // Is in local store ?
  12955. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  12956. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  12957. return;
  12958. }
  12959. var vertexShaderUrl;
  12960. if (vertex[0] === ".") {
  12961. vertexShaderUrl = vertex;
  12962. }
  12963. else {
  12964. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  12965. }
  12966. // Vertex shader
  12967. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  12968. };
  12969. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  12970. // DOM element ?
  12971. if (fragment instanceof HTMLElement) {
  12972. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  12973. callback(fragmentCode);
  12974. return;
  12975. }
  12976. // Is in local store ?
  12977. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  12978. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  12979. return;
  12980. }
  12981. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  12982. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  12983. return;
  12984. }
  12985. var fragmentShaderUrl;
  12986. if (fragment[0] === ".") {
  12987. fragmentShaderUrl = fragment;
  12988. }
  12989. else {
  12990. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  12991. }
  12992. // Fragment shader
  12993. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  12994. };
  12995. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  12996. try {
  12997. var engine = this._engine;
  12998. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  12999. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13000. this._attributes = engine.getAttributes(this._program, attributesNames);
  13001. for (var index = 0; index < this._samplers.length; index++) {
  13002. var sampler = this.getUniform(this._samplers[index]);
  13003. if (sampler == null) {
  13004. this._samplers.splice(index, 1);
  13005. index--;
  13006. }
  13007. }
  13008. engine.bindSamplers(this);
  13009. this._isReady = true;
  13010. if (this.onCompiled) {
  13011. this.onCompiled(this);
  13012. }
  13013. }
  13014. catch (e) {
  13015. // Is it a problem with precision?
  13016. if (e.message.indexOf("highp") !== -1) {
  13017. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13018. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13019. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13020. return;
  13021. }
  13022. // Let's go through fallbacks then
  13023. if (fallbacks && fallbacks.isMoreFallbacks) {
  13024. defines = fallbacks.reduce(defines);
  13025. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13026. }
  13027. else {
  13028. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13029. BABYLON.Tools.Error("Defines: " + defines);
  13030. BABYLON.Tools.Error("Error: " + e.message);
  13031. this._compilationError = e.message;
  13032. if (this.onError) {
  13033. this.onError(this, this._compilationError);
  13034. }
  13035. }
  13036. }
  13037. };
  13038. Effect.prototype._bindTexture = function (channel, texture) {
  13039. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13040. };
  13041. Effect.prototype.setTexture = function (channel, texture) {
  13042. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13043. };
  13044. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13045. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13046. };
  13047. //public _cacheMatrix(uniformName, matrix) {
  13048. // if (!this._valueCache[uniformName]) {
  13049. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13050. // }
  13051. // for (var index = 0; index < 16; index++) {
  13052. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13053. // }
  13054. //};
  13055. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13056. if (!this._valueCache[uniformName]) {
  13057. this._valueCache[uniformName] = [x, y];
  13058. return;
  13059. }
  13060. this._valueCache[uniformName][0] = x;
  13061. this._valueCache[uniformName][1] = y;
  13062. };
  13063. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13064. if (!this._valueCache[uniformName]) {
  13065. this._valueCache[uniformName] = [x, y, z];
  13066. return;
  13067. }
  13068. this._valueCache[uniformName][0] = x;
  13069. this._valueCache[uniformName][1] = y;
  13070. this._valueCache[uniformName][2] = z;
  13071. };
  13072. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13073. if (!this._valueCache[uniformName]) {
  13074. this._valueCache[uniformName] = [x, y, z, w];
  13075. return;
  13076. }
  13077. this._valueCache[uniformName][0] = x;
  13078. this._valueCache[uniformName][1] = y;
  13079. this._valueCache[uniformName][2] = z;
  13080. this._valueCache[uniformName][3] = w;
  13081. };
  13082. Effect.prototype.setArray = function (uniformName, array) {
  13083. this._engine.setArray(this.getUniform(uniformName), array);
  13084. return this;
  13085. };
  13086. Effect.prototype.setArray2 = function (uniformName, array) {
  13087. this._engine.setArray2(this.getUniform(uniformName), array);
  13088. return this;
  13089. };
  13090. Effect.prototype.setArray3 = function (uniformName, array) {
  13091. this._engine.setArray3(this.getUniform(uniformName), array);
  13092. return this;
  13093. };
  13094. Effect.prototype.setArray4 = function (uniformName, array) {
  13095. this._engine.setArray4(this.getUniform(uniformName), array);
  13096. return this;
  13097. };
  13098. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13099. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13100. return this;
  13101. };
  13102. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13103. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13104. // return;
  13105. //this._cacheMatrix(uniformName, matrix);
  13106. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13107. return this;
  13108. };
  13109. Effect.prototype.setFloat = function (uniformName, value) {
  13110. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13111. return this;
  13112. this._valueCache[uniformName] = value;
  13113. this._engine.setFloat(this.getUniform(uniformName), value);
  13114. return this;
  13115. };
  13116. Effect.prototype.setBool = function (uniformName, bool) {
  13117. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13118. return this;
  13119. this._valueCache[uniformName] = bool;
  13120. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13121. return this;
  13122. };
  13123. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13124. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13125. return this;
  13126. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13127. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13128. return this;
  13129. };
  13130. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13131. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13132. return this;
  13133. this._cacheFloat2(uniformName, x, y);
  13134. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13135. return this;
  13136. };
  13137. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13138. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13139. return this;
  13140. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13141. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13142. return this;
  13143. };
  13144. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13145. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13146. return this;
  13147. this._cacheFloat3(uniformName, x, y, z);
  13148. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13149. return this;
  13150. };
  13151. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13152. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13153. return this;
  13154. this._cacheFloat4(uniformName, x, y, z, w);
  13155. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13156. return this;
  13157. };
  13158. Effect.prototype.setColor3 = function (uniformName, color3) {
  13159. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13160. return this;
  13161. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13162. this._engine.setColor3(this.getUniform(uniformName), color3);
  13163. return this;
  13164. };
  13165. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13166. 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)
  13167. return this;
  13168. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13169. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13170. return this;
  13171. };
  13172. // Statics
  13173. 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}",
  13174. 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}",
  13175. 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}",
  13176. 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}",
  13177. 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}",
  13178. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13179. 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}",
  13180. 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}",
  13181. 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}",
  13182. 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}",
  13183. depthPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nuniform float far;\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n float depth = gl_FragCoord.z / far;\n gl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\n}",
  13184. 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}",
  13185. 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}",
  13186. 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}",
  13187. 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}",
  13188. 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}",
  13189. 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}",
  13190. 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}",
  13191. 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}",
  13192. 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}",
  13193. 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}",
  13194. 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}",
  13195. 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}",
  13196. 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}",
  13197. 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}",
  13198. 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}",
  13199. 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}",
  13200. 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}",
  13201. 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}",
  13202. 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}",
  13203. 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}",
  13204. 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}",
  13205. 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}",
  13206. 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}",
  13207. 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}",
  13208. 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}",
  13209. 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}",
  13210. 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}",
  13211. ssaoPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define SAMPLES 16\n\nuniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\n\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.00001;\n const float radius = 0.002;\n\n vec3 random = texture2D(randomSampler, vUV * 4.0).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 = 1.0;\n\n}",
  13212. ssaoCombinePixelShader:"#ifdef GL_ES\nprecision mediump float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D originalColor;\n\nvarying vec2 vUV;\n\nvoid main(void) {\n gl_FragColor = texture2D(textureSampler, vUV) * texture2D(originalColor, vUV);\n}",
  13213. 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\n}",
  13214. 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}",
  13215. 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}",
  13216. };
  13217. return Effect;
  13218. })();
  13219. BABYLON.Effect = Effect;
  13220. })(BABYLON || (BABYLON = {}));
  13221. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13222. (function (BABYLON) {
  13223. var Material = (function () {
  13224. function Material(name, scene, doNotAdd) {
  13225. this.name = name;
  13226. this.checkReadyOnEveryCall = true;
  13227. this.checkReadyOnlyOnce = false;
  13228. this.state = "";
  13229. this.alpha = 1.0;
  13230. this.backFaceCulling = true;
  13231. this._wasPreviouslyReady = false;
  13232. this._fillMode = Material.TriangleFillMode;
  13233. this.pointSize = 1.0;
  13234. this.id = name;
  13235. this._scene = scene;
  13236. if (!doNotAdd) {
  13237. scene.materials.push(this);
  13238. }
  13239. }
  13240. Object.defineProperty(Material, "TriangleFillMode", {
  13241. get: function () {
  13242. return Material._TriangleFillMode;
  13243. },
  13244. enumerable: true,
  13245. configurable: true
  13246. });
  13247. Object.defineProperty(Material, "WireFrameFillMode", {
  13248. get: function () {
  13249. return Material._WireFrameFillMode;
  13250. },
  13251. enumerable: true,
  13252. configurable: true
  13253. });
  13254. Object.defineProperty(Material, "PointFillMode", {
  13255. get: function () {
  13256. return Material._PointFillMode;
  13257. },
  13258. enumerable: true,
  13259. configurable: true
  13260. });
  13261. Object.defineProperty(Material.prototype, "wireframe", {
  13262. get: function () {
  13263. return this._fillMode === Material.WireFrameFillMode;
  13264. },
  13265. set: function (value) {
  13266. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13267. },
  13268. enumerable: true,
  13269. configurable: true
  13270. });
  13271. Object.defineProperty(Material.prototype, "pointsCloud", {
  13272. get: function () {
  13273. return this._fillMode === Material.PointFillMode;
  13274. },
  13275. set: function (value) {
  13276. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13277. },
  13278. enumerable: true,
  13279. configurable: true
  13280. });
  13281. Object.defineProperty(Material.prototype, "fillMode", {
  13282. get: function () {
  13283. return this._fillMode;
  13284. },
  13285. set: function (value) {
  13286. this._fillMode = value;
  13287. },
  13288. enumerable: true,
  13289. configurable: true
  13290. });
  13291. Material.prototype.isReady = function (mesh, useInstances) {
  13292. return true;
  13293. };
  13294. Material.prototype.getEffect = function () {
  13295. return this._effect;
  13296. };
  13297. Material.prototype.getScene = function () {
  13298. return this._scene;
  13299. };
  13300. Material.prototype.needAlphaBlending = function () {
  13301. return (this.alpha < 1.0);
  13302. };
  13303. Material.prototype.needAlphaTesting = function () {
  13304. return false;
  13305. };
  13306. Material.prototype.getAlphaTestTexture = function () {
  13307. return null;
  13308. };
  13309. Material.prototype.trackCreation = function (onCompiled, onError) {
  13310. };
  13311. Material.prototype._preBind = function () {
  13312. var engine = this._scene.getEngine();
  13313. engine.enableEffect(this._effect);
  13314. engine.setState(this.backFaceCulling);
  13315. };
  13316. Material.prototype.bind = function (world, mesh) {
  13317. this._scene._cachedMaterial = this;
  13318. if (this.onBind) {
  13319. this.onBind(this);
  13320. }
  13321. };
  13322. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13323. };
  13324. Material.prototype.unbind = function () {
  13325. };
  13326. Material.prototype.dispose = function (forceDisposeEffect) {
  13327. // Remove from scene
  13328. var index = this._scene.materials.indexOf(this);
  13329. this._scene.materials.splice(index, 1);
  13330. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13331. if (forceDisposeEffect && this._effect) {
  13332. this._scene.getEngine()._releaseEffect(this._effect);
  13333. this._effect = null;
  13334. }
  13335. // Callback
  13336. if (this.onDispose) {
  13337. this.onDispose();
  13338. }
  13339. };
  13340. Material._TriangleFillMode = 0;
  13341. Material._WireFrameFillMode = 1;
  13342. Material._PointFillMode = 2;
  13343. return Material;
  13344. })();
  13345. BABYLON.Material = Material;
  13346. })(BABYLON || (BABYLON = {}));
  13347. //# sourceMappingURL=babylon.material.js.map
  13348. var BABYLON;
  13349. (function (BABYLON) {
  13350. var maxSimultaneousLights = 4;
  13351. var FresnelParameters = (function () {
  13352. function FresnelParameters() {
  13353. this.isEnabled = true;
  13354. this.leftColor = BABYLON.Color3.White();
  13355. this.rightColor = BABYLON.Color3.Black();
  13356. this.bias = 0;
  13357. this.power = 1;
  13358. }
  13359. return FresnelParameters;
  13360. })();
  13361. BABYLON.FresnelParameters = FresnelParameters;
  13362. var StandardMaterial = (function (_super) {
  13363. __extends(StandardMaterial, _super);
  13364. function StandardMaterial(name, scene) {
  13365. var _this = this;
  13366. _super.call(this, name, scene);
  13367. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13368. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  13369. this.specularColor = new BABYLON.Color3(1, 1, 1);
  13370. this.specularPower = 64;
  13371. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  13372. this.useAlphaFromDiffuseTexture = false;
  13373. this.useSpecularOverAlpha = true;
  13374. this.fogEnabled = true;
  13375. this._cachedDefines = null;
  13376. this._renderTargets = new BABYLON.SmartArray(16);
  13377. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  13378. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  13379. this._scaledDiffuse = new BABYLON.Color3();
  13380. this._scaledSpecular = new BABYLON.Color3();
  13381. this.getRenderTargetTextures = function () {
  13382. _this._renderTargets.reset();
  13383. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  13384. _this._renderTargets.push(_this.reflectionTexture);
  13385. }
  13386. return _this._renderTargets;
  13387. };
  13388. }
  13389. StandardMaterial.prototype.needAlphaBlending = function () {
  13390. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  13391. };
  13392. StandardMaterial.prototype.needAlphaTesting = function () {
  13393. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  13394. };
  13395. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  13396. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  13397. };
  13398. StandardMaterial.prototype.getAlphaTestTexture = function () {
  13399. return this.diffuseTexture;
  13400. };
  13401. // Methods
  13402. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  13403. if (this.checkReadyOnlyOnce) {
  13404. if (this._wasPreviouslyReady) {
  13405. return true;
  13406. }
  13407. }
  13408. var scene = this.getScene();
  13409. if (!this.checkReadyOnEveryCall) {
  13410. if (this._renderId === scene.getRenderId()) {
  13411. return true;
  13412. }
  13413. }
  13414. var engine = scene.getEngine();
  13415. var defines = [];
  13416. var fallbacks = new BABYLON.EffectFallbacks();
  13417. // Textures
  13418. if (scene.texturesEnabled) {
  13419. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13420. if (!this.diffuseTexture.isReady()) {
  13421. return false;
  13422. }
  13423. else {
  13424. defines.push("#define DIFFUSE");
  13425. }
  13426. }
  13427. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13428. if (!this.ambientTexture.isReady()) {
  13429. return false;
  13430. }
  13431. else {
  13432. defines.push("#define AMBIENT");
  13433. }
  13434. }
  13435. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13436. if (!this.opacityTexture.isReady()) {
  13437. return false;
  13438. }
  13439. else {
  13440. defines.push("#define OPACITY");
  13441. if (this.opacityTexture.getAlphaFromRGB) {
  13442. defines.push("#define OPACITYRGB");
  13443. }
  13444. }
  13445. }
  13446. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13447. if (!this.reflectionTexture.isReady()) {
  13448. return false;
  13449. }
  13450. else {
  13451. defines.push("#define REFLECTION");
  13452. fallbacks.addFallback(0, "REFLECTION");
  13453. }
  13454. }
  13455. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13456. if (!this.emissiveTexture.isReady()) {
  13457. return false;
  13458. }
  13459. else {
  13460. defines.push("#define EMISSIVE");
  13461. }
  13462. }
  13463. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13464. if (!this.specularTexture.isReady()) {
  13465. return false;
  13466. }
  13467. else {
  13468. defines.push("#define SPECULAR");
  13469. fallbacks.addFallback(0, "SPECULAR");
  13470. }
  13471. }
  13472. }
  13473. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  13474. if (!this.bumpTexture.isReady()) {
  13475. return false;
  13476. }
  13477. else {
  13478. defines.push("#define BUMP");
  13479. fallbacks.addFallback(0, "BUMP");
  13480. }
  13481. }
  13482. // Effect
  13483. if (this.useSpecularOverAlpha) {
  13484. defines.push("#define SPECULAROVERALPHA");
  13485. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  13486. }
  13487. if (scene.clipPlane) {
  13488. defines.push("#define CLIPPLANE");
  13489. }
  13490. if (engine.getAlphaTesting()) {
  13491. defines.push("#define ALPHATEST");
  13492. }
  13493. if (this._shouldUseAlphaFromDiffuseTexture()) {
  13494. defines.push("#define ALPHAFROMDIFFUSE");
  13495. }
  13496. // Point size
  13497. if (this.pointsCloud || scene.forcePointsCloud) {
  13498. defines.push("#define POINTSIZE");
  13499. }
  13500. // Fog
  13501. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13502. defines.push("#define FOG");
  13503. fallbacks.addFallback(1, "FOG");
  13504. }
  13505. var shadowsActivated = false;
  13506. var lightIndex = 0;
  13507. if (scene.lightsEnabled) {
  13508. for (var index = 0; index < scene.lights.length; index++) {
  13509. var light = scene.lights[index];
  13510. if (!light.isEnabled()) {
  13511. continue;
  13512. }
  13513. // Excluded check
  13514. if (light._excludedMeshesIds.length > 0) {
  13515. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  13516. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  13517. if (excludedMesh) {
  13518. light.excludedMeshes.push(excludedMesh);
  13519. }
  13520. }
  13521. light._excludedMeshesIds = [];
  13522. }
  13523. // Included check
  13524. if (light._includedOnlyMeshesIds.length > 0) {
  13525. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  13526. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  13527. if (includedOnlyMesh) {
  13528. light.includedOnlyMeshes.push(includedOnlyMesh);
  13529. }
  13530. }
  13531. light._includedOnlyMeshesIds = [];
  13532. }
  13533. if (!light.canAffectMesh(mesh)) {
  13534. continue;
  13535. }
  13536. defines.push("#define LIGHT" + lightIndex);
  13537. if (lightIndex > 0) {
  13538. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  13539. }
  13540. var type;
  13541. if (light instanceof BABYLON.SpotLight) {
  13542. type = "#define SPOTLIGHT" + lightIndex;
  13543. }
  13544. else if (light instanceof BABYLON.HemisphericLight) {
  13545. type = "#define HEMILIGHT" + lightIndex;
  13546. }
  13547. else {
  13548. type = "#define POINTDIRLIGHT" + lightIndex;
  13549. }
  13550. defines.push(type);
  13551. if (lightIndex > 0) {
  13552. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  13553. }
  13554. // Shadows
  13555. if (scene.shadowsEnabled) {
  13556. var shadowGenerator = light.getShadowGenerator();
  13557. if (mesh && mesh.receiveShadows && shadowGenerator) {
  13558. defines.push("#define SHADOW" + lightIndex);
  13559. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  13560. if (!shadowsActivated) {
  13561. defines.push("#define SHADOWS");
  13562. shadowsActivated = true;
  13563. }
  13564. if (shadowGenerator.useVarianceShadowMap) {
  13565. defines.push("#define SHADOWVSM" + lightIndex);
  13566. if (lightIndex > 0) {
  13567. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  13568. }
  13569. }
  13570. if (shadowGenerator.usePoissonSampling) {
  13571. defines.push("#define SHADOWPCF" + lightIndex);
  13572. if (lightIndex > 0) {
  13573. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  13574. }
  13575. }
  13576. }
  13577. }
  13578. lightIndex++;
  13579. if (lightIndex === maxSimultaneousLights)
  13580. break;
  13581. }
  13582. }
  13583. if (StandardMaterial.FresnelEnabled) {
  13584. // Fresnel
  13585. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13586. var fresnelRank = 1;
  13587. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13588. defines.push("#define DIFFUSEFRESNEL");
  13589. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  13590. fresnelRank++;
  13591. }
  13592. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13593. defines.push("#define OPACITYFRESNEL");
  13594. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  13595. fresnelRank++;
  13596. }
  13597. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13598. defines.push("#define REFLECTIONFRESNEL");
  13599. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  13600. fresnelRank++;
  13601. }
  13602. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13603. defines.push("#define EMISSIVEFRESNEL");
  13604. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  13605. fresnelRank++;
  13606. }
  13607. defines.push("#define FRESNEL");
  13608. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  13609. }
  13610. }
  13611. // Attribs
  13612. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  13613. if (mesh) {
  13614. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13615. attribs.push(BABYLON.VertexBuffer.UVKind);
  13616. defines.push("#define UV1");
  13617. }
  13618. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13619. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13620. defines.push("#define UV2");
  13621. }
  13622. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13623. attribs.push(BABYLON.VertexBuffer.ColorKind);
  13624. defines.push("#define VERTEXCOLOR");
  13625. if (mesh.hasVertexAlpha) {
  13626. defines.push("#define VERTEXALPHA");
  13627. }
  13628. }
  13629. if (mesh.useBones) {
  13630. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13631. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13632. defines.push("#define BONES");
  13633. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13634. defines.push("#define BONES4");
  13635. fallbacks.addFallback(0, "BONES4");
  13636. }
  13637. // Instances
  13638. if (useInstances) {
  13639. defines.push("#define INSTANCES");
  13640. attribs.push("world0");
  13641. attribs.push("world1");
  13642. attribs.push("world2");
  13643. attribs.push("world3");
  13644. }
  13645. }
  13646. // Get correct effect
  13647. var join = defines.join("\n");
  13648. if (this._cachedDefines !== join) {
  13649. this._cachedDefines = join;
  13650. scene.resetCachedMaterial();
  13651. // Legacy browser patch
  13652. var shaderName = "default";
  13653. if (!scene.getEngine().getCaps().standardDerivatives) {
  13654. shaderName = "legacydefault";
  13655. }
  13656. 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);
  13657. }
  13658. if (!this._effect.isReady()) {
  13659. return false;
  13660. }
  13661. this._renderId = scene.getRenderId();
  13662. this._wasPreviouslyReady = true;
  13663. return true;
  13664. };
  13665. StandardMaterial.prototype.unbind = function () {
  13666. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  13667. this._effect.setTexture("reflection2DSampler", null);
  13668. }
  13669. };
  13670. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  13671. this._effect.setMatrix("world", world);
  13672. };
  13673. StandardMaterial.prototype.bind = function (world, mesh) {
  13674. var scene = this.getScene();
  13675. // Matrices
  13676. this.bindOnlyWorldMatrix(world);
  13677. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  13678. // Bones
  13679. if (mesh.useBones) {
  13680. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  13681. }
  13682. if (scene.getCachedMaterial() !== this) {
  13683. if (StandardMaterial.FresnelEnabled) {
  13684. // Fresnel
  13685. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13686. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  13687. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  13688. }
  13689. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13690. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  13691. }
  13692. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13693. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  13694. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  13695. }
  13696. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13697. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  13698. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  13699. }
  13700. }
  13701. // Textures
  13702. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13703. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  13704. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  13705. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  13706. }
  13707. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13708. this._effect.setTexture("ambientSampler", this.ambientTexture);
  13709. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  13710. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  13711. }
  13712. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13713. this._effect.setTexture("opacitySampler", this.opacityTexture);
  13714. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  13715. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  13716. }
  13717. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13718. if (this.reflectionTexture.isCube) {
  13719. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  13720. }
  13721. else {
  13722. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  13723. }
  13724. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  13725. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  13726. }
  13727. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13728. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  13729. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  13730. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  13731. }
  13732. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13733. this._effect.setTexture("specularSampler", this.specularTexture);
  13734. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  13735. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  13736. }
  13737. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  13738. this._effect.setTexture("bumpSampler", this.bumpTexture);
  13739. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  13740. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  13741. }
  13742. // Clip plane
  13743. if (scene.clipPlane) {
  13744. var clipPlane = scene.clipPlane;
  13745. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13746. }
  13747. // Point size
  13748. if (this.pointsCloud) {
  13749. this._effect.setFloat("pointSize", this.pointSize);
  13750. }
  13751. // Colors
  13752. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  13753. // Scaling down color according to emissive
  13754. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13755. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13756. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13757. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  13758. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  13759. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  13760. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  13761. }
  13762. // Scaling down color according to emissive
  13763. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13764. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13765. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13766. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  13767. if (scene.lightsEnabled) {
  13768. var lightIndex = 0;
  13769. for (var index = 0; index < scene.lights.length; index++) {
  13770. var light = scene.lights[index];
  13771. if (!light.isEnabled()) {
  13772. continue;
  13773. }
  13774. if (!light.canAffectMesh(mesh)) {
  13775. continue;
  13776. }
  13777. if (light instanceof BABYLON.PointLight) {
  13778. // Point Light
  13779. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13780. }
  13781. else if (light instanceof BABYLON.DirectionalLight) {
  13782. // Directional Light
  13783. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13784. }
  13785. else if (light instanceof BABYLON.SpotLight) {
  13786. // Spot Light
  13787. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  13788. }
  13789. else if (light instanceof BABYLON.HemisphericLight) {
  13790. // Hemispheric Light
  13791. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  13792. }
  13793. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  13794. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  13795. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13796. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13797. // Shadows
  13798. if (scene.shadowsEnabled) {
  13799. var shadowGenerator = light.getShadowGenerator();
  13800. if (mesh.receiveShadows && shadowGenerator) {
  13801. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13802. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13803. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13804. }
  13805. }
  13806. lightIndex++;
  13807. if (lightIndex === maxSimultaneousLights)
  13808. break;
  13809. }
  13810. }
  13811. // View
  13812. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13813. this._effect.setMatrix("view", scene.getViewMatrix());
  13814. }
  13815. // Fog
  13816. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13817. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13818. this._effect.setColor3("vFogColor", scene.fogColor);
  13819. }
  13820. _super.prototype.bind.call(this, world, mesh);
  13821. };
  13822. StandardMaterial.prototype.getAnimatables = function () {
  13823. var results = [];
  13824. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13825. results.push(this.diffuseTexture);
  13826. }
  13827. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13828. results.push(this.ambientTexture);
  13829. }
  13830. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13831. results.push(this.opacityTexture);
  13832. }
  13833. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13834. results.push(this.reflectionTexture);
  13835. }
  13836. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13837. results.push(this.emissiveTexture);
  13838. }
  13839. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  13840. results.push(this.specularTexture);
  13841. }
  13842. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  13843. results.push(this.bumpTexture);
  13844. }
  13845. return results;
  13846. };
  13847. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  13848. if (this.diffuseTexture) {
  13849. this.diffuseTexture.dispose();
  13850. }
  13851. if (this.ambientTexture) {
  13852. this.ambientTexture.dispose();
  13853. }
  13854. if (this.opacityTexture) {
  13855. this.opacityTexture.dispose();
  13856. }
  13857. if (this.reflectionTexture) {
  13858. this.reflectionTexture.dispose();
  13859. }
  13860. if (this.emissiveTexture) {
  13861. this.emissiveTexture.dispose();
  13862. }
  13863. if (this.specularTexture) {
  13864. this.specularTexture.dispose();
  13865. }
  13866. if (this.bumpTexture) {
  13867. this.bumpTexture.dispose();
  13868. }
  13869. _super.prototype.dispose.call(this, forceDisposeEffect);
  13870. };
  13871. StandardMaterial.prototype.clone = function (name) {
  13872. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  13873. // Base material
  13874. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  13875. newStandardMaterial.alpha = this.alpha;
  13876. newStandardMaterial.fillMode = this.fillMode;
  13877. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  13878. // Standard material
  13879. if (this.diffuseTexture && this.diffuseTexture.clone) {
  13880. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  13881. }
  13882. if (this.ambientTexture && this.ambientTexture.clone) {
  13883. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  13884. }
  13885. if (this.opacityTexture && this.opacityTexture.clone) {
  13886. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  13887. }
  13888. if (this.reflectionTexture && this.reflectionTexture.clone) {
  13889. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  13890. }
  13891. if (this.emissiveTexture && this.emissiveTexture.clone) {
  13892. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  13893. }
  13894. if (this.specularTexture && this.specularTexture.clone) {
  13895. newStandardMaterial.specularTexture = this.specularTexture.clone();
  13896. }
  13897. if (this.bumpTexture && this.bumpTexture.clone) {
  13898. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  13899. }
  13900. newStandardMaterial.ambientColor = this.ambientColor.clone();
  13901. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  13902. newStandardMaterial.specularColor = this.specularColor.clone();
  13903. newStandardMaterial.specularPower = this.specularPower;
  13904. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  13905. return newStandardMaterial;
  13906. };
  13907. // Statics
  13908. // Flags used to enable or disable a type of texture for all Standard Materials
  13909. StandardMaterial.DiffuseTextureEnabled = true;
  13910. StandardMaterial.AmbientTextureEnabled = true;
  13911. StandardMaterial.OpacityTextureEnabled = true;
  13912. StandardMaterial.ReflectionTextureEnabled = true;
  13913. StandardMaterial.EmissiveTextureEnabled = true;
  13914. StandardMaterial.SpecularTextureEnabled = true;
  13915. StandardMaterial.BumpTextureEnabled = true;
  13916. StandardMaterial.FresnelEnabled = true;
  13917. return StandardMaterial;
  13918. })(BABYLON.Material);
  13919. BABYLON.StandardMaterial = StandardMaterial;
  13920. })(BABYLON || (BABYLON = {}));
  13921. //# sourceMappingURL=babylon.standardMaterial.js.map
  13922. var BABYLON;
  13923. (function (BABYLON) {
  13924. var MultiMaterial = (function (_super) {
  13925. __extends(MultiMaterial, _super);
  13926. function MultiMaterial(name, scene) {
  13927. _super.call(this, name, scene, true);
  13928. this.subMaterials = new Array();
  13929. scene.multiMaterials.push(this);
  13930. }
  13931. // Properties
  13932. MultiMaterial.prototype.getSubMaterial = function (index) {
  13933. if (index < 0 || index >= this.subMaterials.length) {
  13934. return this.getScene().defaultMaterial;
  13935. }
  13936. return this.subMaterials[index];
  13937. };
  13938. // Methods
  13939. MultiMaterial.prototype.isReady = function (mesh) {
  13940. for (var index = 0; index < this.subMaterials.length; index++) {
  13941. var subMaterial = this.subMaterials[index];
  13942. if (subMaterial) {
  13943. if (!this.subMaterials[index].isReady(mesh)) {
  13944. return false;
  13945. }
  13946. }
  13947. }
  13948. return true;
  13949. };
  13950. return MultiMaterial;
  13951. })(BABYLON.Material);
  13952. BABYLON.MultiMaterial = MultiMaterial;
  13953. })(BABYLON || (BABYLON = {}));
  13954. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  13955. (function (BABYLON) {
  13956. var Database = (function () {
  13957. function Database(urlToScene, callbackManifestChecked) {
  13958. // Handling various flavors of prefixed version of IndexedDB
  13959. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  13960. this.callbackManifestChecked = callbackManifestChecked;
  13961. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  13962. this.db = null;
  13963. this.enableSceneOffline = false;
  13964. this.enableTexturesOffline = false;
  13965. this.manifestVersionFound = 0;
  13966. this.mustUpdateRessources = false;
  13967. this.hasReachedQuota = false;
  13968. this.checkManifestFile();
  13969. }
  13970. Database.prototype.checkManifestFile = function () {
  13971. var _this = this;
  13972. function noManifestFile() {
  13973. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  13974. that.enableSceneOffline = false;
  13975. that.enableTexturesOffline = false;
  13976. that.callbackManifestChecked(false);
  13977. }
  13978. var that = this;
  13979. var manifestURL = this.currentSceneUrl + ".manifest";
  13980. var xhr = new XMLHttpRequest();
  13981. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  13982. xhr.open("GET", manifestURLTimeStamped, true);
  13983. xhr.addEventListener("load", function () {
  13984. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13985. try {
  13986. var manifestFile = JSON.parse(xhr.response);
  13987. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  13988. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  13989. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  13990. _this.manifestVersionFound = manifestFile.version;
  13991. }
  13992. if (_this.callbackManifestChecked) {
  13993. _this.callbackManifestChecked(true);
  13994. }
  13995. }
  13996. catch (ex) {
  13997. noManifestFile();
  13998. }
  13999. }
  14000. else {
  14001. noManifestFile();
  14002. }
  14003. }, false);
  14004. xhr.addEventListener("error", function (event) {
  14005. noManifestFile();
  14006. }, false);
  14007. try {
  14008. xhr.send();
  14009. }
  14010. catch (ex) {
  14011. BABYLON.Tools.Error("Error on XHR send request.");
  14012. that.callbackManifestChecked(false);
  14013. }
  14014. };
  14015. Database.prototype.openAsync = function (successCallback, errorCallback) {
  14016. var _this = this;
  14017. function handleError() {
  14018. that.isSupported = false;
  14019. if (errorCallback)
  14020. errorCallback();
  14021. }
  14022. var that = this;
  14023. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14024. // Your browser doesn't support IndexedDB
  14025. this.isSupported = false;
  14026. if (errorCallback)
  14027. errorCallback();
  14028. }
  14029. else {
  14030. // If the DB hasn't been opened or created yet
  14031. if (!this.db) {
  14032. this.hasReachedQuota = false;
  14033. this.isSupported = true;
  14034. var request = this.idbFactory.open("babylonjs", 1);
  14035. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14036. request.onerror = function (event) {
  14037. handleError();
  14038. };
  14039. // executes when a version change transaction cannot complete due to other active transactions
  14040. request.onblocked = function (event) {
  14041. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14042. handleError();
  14043. };
  14044. // DB has been opened successfully
  14045. request.onsuccess = function (event) {
  14046. _this.db = request.result;
  14047. successCallback();
  14048. };
  14049. // Initialization of the DB. Creating Scenes & Textures stores
  14050. request.onupgradeneeded = function (event) {
  14051. _this.db = (event.target).result;
  14052. try {
  14053. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14054. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14055. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14056. }
  14057. catch (ex) {
  14058. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14059. handleError();
  14060. }
  14061. };
  14062. }
  14063. else {
  14064. if (successCallback)
  14065. successCallback();
  14066. }
  14067. }
  14068. };
  14069. Database.prototype.loadImageFromDB = function (url, image) {
  14070. var _this = this;
  14071. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  14072. var saveAndLoadImage = function () {
  14073. if (!_this.hasReachedQuota && _this.db !== null) {
  14074. // the texture is not yet in the DB, let's try to save it
  14075. _this._saveImageIntoDBAsync(completeURL, image);
  14076. }
  14077. else {
  14078. image.src = url;
  14079. }
  14080. };
  14081. if (!this.mustUpdateRessources) {
  14082. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14083. }
  14084. else {
  14085. saveAndLoadImage();
  14086. }
  14087. };
  14088. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14089. if (this.isSupported && this.db !== null) {
  14090. var texture;
  14091. var transaction = this.db.transaction(["textures"]);
  14092. transaction.onabort = function (event) {
  14093. image.src = url;
  14094. };
  14095. transaction.oncomplete = function (event) {
  14096. var blobTextureURL;
  14097. if (texture) {
  14098. var URL = window.URL || window.webkitURL;
  14099. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14100. image.onerror = function () {
  14101. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14102. image.src = url;
  14103. };
  14104. image.src = blobTextureURL;
  14105. }
  14106. else {
  14107. notInDBCallback();
  14108. }
  14109. };
  14110. var getRequest = transaction.objectStore("textures").get(url);
  14111. getRequest.onsuccess = function (event) {
  14112. texture = (event.target).result;
  14113. };
  14114. getRequest.onerror = function (event) {
  14115. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14116. image.src = url;
  14117. };
  14118. }
  14119. else {
  14120. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14121. image.src = url;
  14122. }
  14123. };
  14124. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14125. var _this = this;
  14126. if (this.isSupported) {
  14127. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14128. var generateBlobUrl = function () {
  14129. var blobTextureURL;
  14130. if (blob) {
  14131. var URL = window.URL || window.webkitURL;
  14132. try {
  14133. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14134. }
  14135. catch (ex) {
  14136. blobTextureURL = URL.createObjectURL(blob);
  14137. }
  14138. }
  14139. image.src = blobTextureURL;
  14140. };
  14141. if (BABYLON.Database.isUASupportingBlobStorage) {
  14142. var xhr = new XMLHttpRequest(), blob;
  14143. xhr.open("GET", url, true);
  14144. xhr.responseType = "blob";
  14145. xhr.addEventListener("load", function () {
  14146. if (xhr.status === 200) {
  14147. // Blob as response (XHR2)
  14148. blob = xhr.response;
  14149. var transaction = _this.db.transaction(["textures"], "readwrite");
  14150. // the transaction could abort because of a QuotaExceededError error
  14151. transaction.onabort = function (event) {
  14152. try {
  14153. if (event.srcElement.error.name === "QuotaExceededError") {
  14154. this.hasReachedQuota = true;
  14155. }
  14156. }
  14157. catch (ex) {
  14158. }
  14159. generateBlobUrl();
  14160. };
  14161. transaction.oncomplete = function (event) {
  14162. generateBlobUrl();
  14163. };
  14164. var newTexture = { textureUrl: url, data: blob };
  14165. try {
  14166. // Put the blob into the dabase
  14167. var addRequest = transaction.objectStore("textures").put(newTexture);
  14168. addRequest.onsuccess = function (event) {
  14169. };
  14170. addRequest.onerror = function (event) {
  14171. generateBlobUrl();
  14172. };
  14173. }
  14174. catch (ex) {
  14175. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14176. if (ex.code === 25) {
  14177. BABYLON.Database.isUASupportingBlobStorage = false;
  14178. }
  14179. image.src = url;
  14180. }
  14181. }
  14182. else {
  14183. image.src = url;
  14184. }
  14185. }, false);
  14186. xhr.addEventListener("error", function (event) {
  14187. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14188. image.src = url;
  14189. }, false);
  14190. xhr.send();
  14191. }
  14192. else {
  14193. image.src = url;
  14194. }
  14195. }
  14196. else {
  14197. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14198. image.src = url;
  14199. }
  14200. };
  14201. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14202. var _this = this;
  14203. var updateVersion = function (event) {
  14204. // the version is not yet in the DB or we need to update it
  14205. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14206. };
  14207. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14208. };
  14209. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14210. var _this = this;
  14211. if (this.isSupported) {
  14212. var version;
  14213. try {
  14214. var transaction = this.db.transaction(["versions"]);
  14215. transaction.oncomplete = function (event) {
  14216. if (version) {
  14217. // If the version in the JSON file is > than the version in DB
  14218. if (_this.manifestVersionFound > version.data) {
  14219. _this.mustUpdateRessources = true;
  14220. updateInDBCallback();
  14221. }
  14222. else {
  14223. callback(version.data);
  14224. }
  14225. }
  14226. else {
  14227. _this.mustUpdateRessources = true;
  14228. updateInDBCallback();
  14229. }
  14230. };
  14231. transaction.onabort = function (event) {
  14232. callback(-1);
  14233. };
  14234. var getRequest = transaction.objectStore("versions").get(url);
  14235. getRequest.onsuccess = function (event) {
  14236. version = (event.target).result;
  14237. };
  14238. getRequest.onerror = function (event) {
  14239. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14240. callback(-1);
  14241. };
  14242. }
  14243. catch (ex) {
  14244. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14245. callback(-1);
  14246. }
  14247. }
  14248. else {
  14249. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14250. callback(-1);
  14251. }
  14252. };
  14253. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14254. var _this = this;
  14255. if (this.isSupported && !this.hasReachedQuota) {
  14256. try {
  14257. // Open a transaction to the database
  14258. var transaction = this.db.transaction(["versions"], "readwrite");
  14259. // the transaction could abort because of a QuotaExceededError error
  14260. transaction.onabort = function (event) {
  14261. try {
  14262. if (event.srcElement.error.name === "QuotaExceededError") {
  14263. _this.hasReachedQuota = true;
  14264. }
  14265. }
  14266. catch (ex) {
  14267. }
  14268. callback(-1);
  14269. };
  14270. transaction.oncomplete = function (event) {
  14271. callback(_this.manifestVersionFound);
  14272. };
  14273. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14274. // Put the scene into the database
  14275. var addRequest = transaction.objectStore("versions").put(newVersion);
  14276. addRequest.onsuccess = function (event) {
  14277. };
  14278. addRequest.onerror = function (event) {
  14279. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14280. };
  14281. }
  14282. catch (ex) {
  14283. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14284. callback(-1);
  14285. }
  14286. }
  14287. else {
  14288. callback(-1);
  14289. }
  14290. };
  14291. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14292. var _this = this;
  14293. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  14294. var saveAndLoadFile = function (event) {
  14295. // the scene is not yet in the DB, let's try to save it
  14296. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14297. };
  14298. this._checkVersionFromDB(completeUrl, function (version) {
  14299. if (version !== -1) {
  14300. if (!_this.mustUpdateRessources) {
  14301. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14302. }
  14303. else {
  14304. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14305. }
  14306. }
  14307. else {
  14308. errorCallback();
  14309. }
  14310. });
  14311. };
  14312. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14313. if (this.isSupported) {
  14314. var targetStore;
  14315. if (url.indexOf(".babylon") !== -1) {
  14316. targetStore = "scenes";
  14317. }
  14318. else {
  14319. targetStore = "textures";
  14320. }
  14321. var file;
  14322. var transaction = this.db.transaction([targetStore]);
  14323. transaction.oncomplete = function (event) {
  14324. if (file) {
  14325. callback(file.data);
  14326. }
  14327. else {
  14328. notInDBCallback();
  14329. }
  14330. };
  14331. transaction.onabort = function (event) {
  14332. notInDBCallback();
  14333. };
  14334. var getRequest = transaction.objectStore(targetStore).get(url);
  14335. getRequest.onsuccess = function (event) {
  14336. file = (event.target).result;
  14337. };
  14338. getRequest.onerror = function (event) {
  14339. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  14340. notInDBCallback();
  14341. };
  14342. }
  14343. else {
  14344. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14345. callback();
  14346. }
  14347. };
  14348. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  14349. var _this = this;
  14350. if (this.isSupported) {
  14351. var targetStore;
  14352. if (url.indexOf(".babylon") !== -1) {
  14353. targetStore = "scenes";
  14354. }
  14355. else {
  14356. targetStore = "textures";
  14357. }
  14358. // Create XHR
  14359. var xhr = new XMLHttpRequest(), fileData;
  14360. xhr.open("GET", url, true);
  14361. if (useArrayBuffer) {
  14362. xhr.responseType = "arraybuffer";
  14363. }
  14364. xhr.onprogress = progressCallback;
  14365. xhr.addEventListener("load", function () {
  14366. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  14367. // Blob as response (XHR2)
  14368. //fileData = xhr.responseText;
  14369. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  14370. if (!_this.hasReachedQuota) {
  14371. // Open a transaction to the database
  14372. var transaction = _this.db.transaction([targetStore], "readwrite");
  14373. // the transaction could abort because of a QuotaExceededError error
  14374. transaction.onabort = function (event) {
  14375. try {
  14376. if (event.srcElement.error.name === "QuotaExceededError") {
  14377. this.hasReachedQuota = true;
  14378. }
  14379. }
  14380. catch (ex) {
  14381. }
  14382. callback(fileData);
  14383. };
  14384. transaction.oncomplete = function (event) {
  14385. callback(fileData);
  14386. };
  14387. var newFile;
  14388. if (targetStore === "scenes") {
  14389. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  14390. }
  14391. else {
  14392. newFile = { textureUrl: url, data: fileData };
  14393. }
  14394. try {
  14395. // Put the scene into the database
  14396. var addRequest = transaction.objectStore(targetStore).put(newFile);
  14397. addRequest.onsuccess = function (event) {
  14398. };
  14399. addRequest.onerror = function (event) {
  14400. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  14401. };
  14402. }
  14403. catch (ex) {
  14404. callback(fileData);
  14405. }
  14406. }
  14407. else {
  14408. callback(fileData);
  14409. }
  14410. }
  14411. else {
  14412. callback();
  14413. }
  14414. }, false);
  14415. xhr.addEventListener("error", function (event) {
  14416. BABYLON.Tools.Error("error on XHR request.");
  14417. callback();
  14418. }, false);
  14419. xhr.send();
  14420. }
  14421. else {
  14422. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14423. callback();
  14424. }
  14425. };
  14426. Database.isUASupportingBlobStorage = true;
  14427. Database.parseURL = function (url) {
  14428. var a = document.createElement('a');
  14429. a.href = url;
  14430. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  14431. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  14432. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  14433. return absLocation;
  14434. };
  14435. Database.ReturnFullUrlLocation = function (url) {
  14436. if (url.indexOf("http:/") === -1) {
  14437. return (BABYLON.Database.parseURL(window.location.href) + url);
  14438. }
  14439. else {
  14440. return url;
  14441. }
  14442. };
  14443. return Database;
  14444. })();
  14445. BABYLON.Database = Database;
  14446. })(BABYLON || (BABYLON = {}));
  14447. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  14448. (function (BABYLON) {
  14449. var SpriteManager = (function () {
  14450. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  14451. this.name = name;
  14452. this.cellSize = cellSize;
  14453. this.sprites = new Array();
  14454. this.renderingGroupId = 0;
  14455. this.fogEnabled = true;
  14456. this._vertexDeclaration = [3, 4, 4, 4];
  14457. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  14458. this._capacity = capacity;
  14459. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  14460. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14461. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14462. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  14463. this._scene = scene;
  14464. this._scene.spriteManagers.push(this);
  14465. // VBO
  14466. this._vertexDeclaration = [3, 4, 4, 4];
  14467. this._vertexStrideSize = 15 * 4;
  14468. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14469. var indices = [];
  14470. var index = 0;
  14471. for (var count = 0; count < capacity; count++) {
  14472. indices.push(index);
  14473. indices.push(index + 1);
  14474. indices.push(index + 2);
  14475. indices.push(index);
  14476. indices.push(index + 2);
  14477. indices.push(index + 3);
  14478. index += 4;
  14479. }
  14480. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14481. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14482. // Effects
  14483. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  14484. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  14485. }
  14486. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  14487. var arrayOffset = index * 15;
  14488. if (offsetX == 0)
  14489. offsetX = this._epsilon;
  14490. else if (offsetX == 1)
  14491. offsetX = 1 - this._epsilon;
  14492. if (offsetY == 0)
  14493. offsetY = this._epsilon;
  14494. else if (offsetY == 1)
  14495. offsetY = 1 - this._epsilon;
  14496. this._vertices[arrayOffset] = sprite.position.x;
  14497. this._vertices[arrayOffset + 1] = sprite.position.y;
  14498. this._vertices[arrayOffset + 2] = sprite.position.z;
  14499. this._vertices[arrayOffset + 3] = sprite.angle;
  14500. this._vertices[arrayOffset + 4] = sprite.size;
  14501. this._vertices[arrayOffset + 5] = offsetX;
  14502. this._vertices[arrayOffset + 6] = offsetY;
  14503. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  14504. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  14505. var offset = (sprite.cellIndex / rowSize) >> 0;
  14506. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  14507. this._vertices[arrayOffset + 10] = offset;
  14508. // Color
  14509. this._vertices[arrayOffset + 11] = sprite.color.r;
  14510. this._vertices[arrayOffset + 12] = sprite.color.g;
  14511. this._vertices[arrayOffset + 13] = sprite.color.b;
  14512. this._vertices[arrayOffset + 14] = sprite.color.a;
  14513. };
  14514. SpriteManager.prototype.render = function () {
  14515. // Check
  14516. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  14517. return;
  14518. var engine = this._scene.getEngine();
  14519. var baseSize = this._spriteTexture.getBaseSize();
  14520. // Sprites
  14521. var deltaTime = engine.getDeltaTime();
  14522. var max = Math.min(this._capacity, this.sprites.length);
  14523. var rowSize = baseSize.width / this.cellSize;
  14524. var offset = 0;
  14525. for (var index = 0; index < max; index++) {
  14526. var sprite = this.sprites[index];
  14527. if (!sprite) {
  14528. continue;
  14529. }
  14530. sprite._animate(deltaTime);
  14531. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  14532. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  14533. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  14534. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  14535. }
  14536. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14537. // Render
  14538. var effect = this._effectBase;
  14539. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14540. effect = this._effectFog;
  14541. }
  14542. engine.enableEffect(effect);
  14543. var viewMatrix = this._scene.getViewMatrix();
  14544. effect.setTexture("diffuseSampler", this._spriteTexture);
  14545. effect.setMatrix("view", viewMatrix);
  14546. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14547. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  14548. // Fog
  14549. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14550. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  14551. effect.setColor3("vFogColor", this._scene.fogColor);
  14552. }
  14553. // VBOs
  14554. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14555. // Draw order
  14556. effect.setBool("alphaTest", true);
  14557. engine.setColorWrite(false);
  14558. engine.draw(true, 0, max * 6);
  14559. engine.setColorWrite(true);
  14560. effect.setBool("alphaTest", false);
  14561. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14562. engine.draw(true, 0, max * 6);
  14563. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14564. };
  14565. SpriteManager.prototype.dispose = function () {
  14566. if (this._vertexBuffer) {
  14567. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14568. this._vertexBuffer = null;
  14569. }
  14570. if (this._indexBuffer) {
  14571. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14572. this._indexBuffer = null;
  14573. }
  14574. if (this._spriteTexture) {
  14575. this._spriteTexture.dispose();
  14576. this._spriteTexture = null;
  14577. }
  14578. // Remove from scene
  14579. var index = this._scene.spriteManagers.indexOf(this);
  14580. this._scene.spriteManagers.splice(index, 1);
  14581. // Callback
  14582. if (this.onDispose) {
  14583. this.onDispose();
  14584. }
  14585. };
  14586. return SpriteManager;
  14587. })();
  14588. BABYLON.SpriteManager = SpriteManager;
  14589. })(BABYLON || (BABYLON = {}));
  14590. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  14591. (function (BABYLON) {
  14592. var Sprite = (function () {
  14593. function Sprite(name, manager) {
  14594. this.name = name;
  14595. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14596. this.size = 1.0;
  14597. this.angle = 0;
  14598. this.cellIndex = 0;
  14599. this.invertU = 0;
  14600. this.invertV = 0;
  14601. this.animations = new Array();
  14602. this._animationStarted = false;
  14603. this._loopAnimation = false;
  14604. this._fromIndex = 0;
  14605. this._toIndex = 0;
  14606. this._delay = 0;
  14607. this._direction = 1;
  14608. this._frameCount = 0;
  14609. this._time = 0;
  14610. this._manager = manager;
  14611. this._manager.sprites.push(this);
  14612. this.position = BABYLON.Vector3.Zero();
  14613. }
  14614. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  14615. this._fromIndex = from;
  14616. this._toIndex = to;
  14617. this._loopAnimation = loop;
  14618. this._delay = delay;
  14619. this._animationStarted = true;
  14620. this._direction = from < to ? 1 : -1;
  14621. this.cellIndex = from;
  14622. this._time = 0;
  14623. };
  14624. Sprite.prototype.stopAnimation = function () {
  14625. this._animationStarted = false;
  14626. };
  14627. Sprite.prototype._animate = function (deltaTime) {
  14628. if (!this._animationStarted)
  14629. return;
  14630. this._time += deltaTime;
  14631. if (this._time > this._delay) {
  14632. this._time = this._time % this._delay;
  14633. this.cellIndex += this._direction;
  14634. if (this.cellIndex == this._toIndex) {
  14635. if (this._loopAnimation) {
  14636. this.cellIndex = this._fromIndex;
  14637. }
  14638. else {
  14639. this._animationStarted = false;
  14640. if (this.disposeWhenFinishedAnimating) {
  14641. this.dispose();
  14642. }
  14643. }
  14644. }
  14645. }
  14646. };
  14647. Sprite.prototype.dispose = function () {
  14648. for (var i = 0; i < this._manager.sprites.length; i++) {
  14649. if (this._manager.sprites[i] == this) {
  14650. this._manager.sprites.splice(i, 1);
  14651. }
  14652. }
  14653. };
  14654. return Sprite;
  14655. })();
  14656. BABYLON.Sprite = Sprite;
  14657. })(BABYLON || (BABYLON = {}));
  14658. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  14659. (function (BABYLON) {
  14660. var Layer = (function () {
  14661. function Layer(name, imgUrl, scene, isBackground, color) {
  14662. this.name = name;
  14663. this._vertexDeclaration = [2];
  14664. this._vertexStrideSize = 2 * 4;
  14665. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  14666. this.isBackground = isBackground === undefined ? true : isBackground;
  14667. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  14668. this._scene = scene;
  14669. this._scene.layers.push(this);
  14670. // VBO
  14671. var vertices = [];
  14672. vertices.push(1, 1);
  14673. vertices.push(-1, 1);
  14674. vertices.push(-1, -1);
  14675. vertices.push(1, -1);
  14676. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14677. // Indices
  14678. var indices = [];
  14679. indices.push(0);
  14680. indices.push(1);
  14681. indices.push(2);
  14682. indices.push(0);
  14683. indices.push(2);
  14684. indices.push(3);
  14685. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14686. // Effects
  14687. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  14688. }
  14689. Layer.prototype.render = function () {
  14690. // Check
  14691. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  14692. return;
  14693. var engine = this._scene.getEngine();
  14694. // Render
  14695. engine.enableEffect(this._effect);
  14696. engine.setState(false);
  14697. // Texture
  14698. this._effect.setTexture("textureSampler", this.texture);
  14699. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  14700. // Color
  14701. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  14702. // VBOs
  14703. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14704. // Draw order
  14705. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14706. engine.draw(true, 0, 6);
  14707. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14708. };
  14709. Layer.prototype.dispose = function () {
  14710. if (this._vertexBuffer) {
  14711. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14712. this._vertexBuffer = null;
  14713. }
  14714. if (this._indexBuffer) {
  14715. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14716. this._indexBuffer = null;
  14717. }
  14718. if (this.texture) {
  14719. this.texture.dispose();
  14720. this.texture = null;
  14721. }
  14722. // Remove from scene
  14723. var index = this._scene.layers.indexOf(this);
  14724. this._scene.layers.splice(index, 1);
  14725. // Callback
  14726. if (this.onDispose) {
  14727. this.onDispose();
  14728. }
  14729. };
  14730. return Layer;
  14731. })();
  14732. BABYLON.Layer = Layer;
  14733. })(BABYLON || (BABYLON = {}));
  14734. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  14735. (function (BABYLON) {
  14736. var Particle = (function () {
  14737. function Particle() {
  14738. this.position = BABYLON.Vector3.Zero();
  14739. this.direction = BABYLON.Vector3.Zero();
  14740. this.color = new BABYLON.Color4(0, 0, 0, 0);
  14741. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  14742. this.lifeTime = 1.0;
  14743. this.age = 0;
  14744. this.size = 0;
  14745. this.angle = 0;
  14746. this.angularSpeed = 0;
  14747. }
  14748. Particle.prototype.copyTo = function (other) {
  14749. other.position.copyFrom(this.position);
  14750. other.direction.copyFrom(this.direction);
  14751. other.color.copyFrom(this.color);
  14752. other.colorStep.copyFrom(this.colorStep);
  14753. other.lifeTime = this.lifeTime;
  14754. other.age = this.age;
  14755. other.size = this.size;
  14756. other.angle = this.angle;
  14757. other.angularSpeed = this.angularSpeed;
  14758. };
  14759. return Particle;
  14760. })();
  14761. BABYLON.Particle = Particle;
  14762. })(BABYLON || (BABYLON = {}));
  14763. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  14764. (function (BABYLON) {
  14765. var randomNumber = function (min, max) {
  14766. if (min === max) {
  14767. return (min);
  14768. }
  14769. var random = Math.random();
  14770. return ((random * (max - min)) + min);
  14771. };
  14772. var ParticleSystem = (function () {
  14773. function ParticleSystem(name, capacity, scene, customEffect) {
  14774. var _this = this;
  14775. this.name = name;
  14776. this.renderingGroupId = 0;
  14777. this.emitter = null;
  14778. this.emitRate = 10;
  14779. this.manualEmitCount = -1;
  14780. this.updateSpeed = 0.01;
  14781. this.targetStopDuration = 0;
  14782. this.disposeOnStop = false;
  14783. this.minEmitPower = 1;
  14784. this.maxEmitPower = 1;
  14785. this.minLifeTime = 1;
  14786. this.maxLifeTime = 1;
  14787. this.minSize = 1;
  14788. this.maxSize = 1;
  14789. this.minAngularSpeed = 0;
  14790. this.maxAngularSpeed = 0;
  14791. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  14792. this.forceDepthWrite = false;
  14793. this.gravity = BABYLON.Vector3.Zero();
  14794. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  14795. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  14796. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  14797. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14798. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14799. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14800. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  14801. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14802. this.particles = new Array();
  14803. this._vertexDeclaration = [3, 4, 4];
  14804. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  14805. this._stockParticles = new Array();
  14806. this._newPartsExcess = 0;
  14807. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  14808. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  14809. this._scaledDirection = BABYLON.Vector3.Zero();
  14810. this._scaledGravity = BABYLON.Vector3.Zero();
  14811. this._currentRenderId = -1;
  14812. this._started = false;
  14813. this._stopped = false;
  14814. this._actualFrame = 0;
  14815. this.id = name;
  14816. this._capacity = capacity;
  14817. this._scene = scene;
  14818. this._customEffect = customEffect;
  14819. scene.particleSystems.push(this);
  14820. // VBO
  14821. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14822. var indices = [];
  14823. var index = 0;
  14824. for (var count = 0; count < capacity; count++) {
  14825. indices.push(index);
  14826. indices.push(index + 1);
  14827. indices.push(index + 2);
  14828. indices.push(index);
  14829. indices.push(index + 2);
  14830. indices.push(index + 3);
  14831. index += 4;
  14832. }
  14833. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14834. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14835. // Default behaviors
  14836. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  14837. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  14838. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  14839. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  14840. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  14841. };
  14842. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  14843. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  14844. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  14845. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  14846. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  14847. };
  14848. this.updateFunction = function (particles) {
  14849. for (var index = 0; index < particles.length; index++) {
  14850. var particle = particles[index];
  14851. particle.age += _this._scaledUpdateSpeed;
  14852. if (particle.age >= particle.lifeTime) {
  14853. _this.recycleParticle(particle);
  14854. index--;
  14855. continue;
  14856. }
  14857. else {
  14858. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  14859. particle.color.addInPlace(_this._scaledColorStep);
  14860. if (particle.color.a < 0)
  14861. particle.color.a = 0;
  14862. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  14863. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  14864. particle.position.addInPlace(_this._scaledDirection);
  14865. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  14866. particle.direction.addInPlace(_this._scaledGravity);
  14867. }
  14868. }
  14869. };
  14870. }
  14871. ParticleSystem.prototype.recycleParticle = function (particle) {
  14872. var lastParticle = this.particles.pop();
  14873. if (lastParticle !== particle) {
  14874. lastParticle.copyTo(particle);
  14875. this._stockParticles.push(lastParticle);
  14876. }
  14877. };
  14878. ParticleSystem.prototype.getCapacity = function () {
  14879. return this._capacity;
  14880. };
  14881. ParticleSystem.prototype.isAlive = function () {
  14882. return this._alive;
  14883. };
  14884. ParticleSystem.prototype.isStarted = function () {
  14885. return this._started;
  14886. };
  14887. ParticleSystem.prototype.start = function () {
  14888. this._started = true;
  14889. this._stopped = false;
  14890. this._actualFrame = 0;
  14891. };
  14892. ParticleSystem.prototype.stop = function () {
  14893. this._stopped = true;
  14894. };
  14895. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  14896. var offset = index * 11;
  14897. this._vertices[offset] = particle.position.x;
  14898. this._vertices[offset + 1] = particle.position.y;
  14899. this._vertices[offset + 2] = particle.position.z;
  14900. this._vertices[offset + 3] = particle.color.r;
  14901. this._vertices[offset + 4] = particle.color.g;
  14902. this._vertices[offset + 5] = particle.color.b;
  14903. this._vertices[offset + 6] = particle.color.a;
  14904. this._vertices[offset + 7] = particle.angle;
  14905. this._vertices[offset + 8] = particle.size;
  14906. this._vertices[offset + 9] = offsetX;
  14907. this._vertices[offset + 10] = offsetY;
  14908. };
  14909. ParticleSystem.prototype._update = function (newParticles) {
  14910. // Update current
  14911. this._alive = this.particles.length > 0;
  14912. this.updateFunction(this.particles);
  14913. // Add new ones
  14914. var worldMatrix;
  14915. if (this.emitter.position) {
  14916. worldMatrix = this.emitter.getWorldMatrix();
  14917. }
  14918. else {
  14919. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  14920. }
  14921. for (var index = 0; index < newParticles; index++) {
  14922. if (this.particles.length === this._capacity) {
  14923. break;
  14924. }
  14925. if (this._stockParticles.length !== 0) {
  14926. var particle = this._stockParticles.pop();
  14927. particle.age = 0;
  14928. }
  14929. else {
  14930. particle = new BABYLON.Particle();
  14931. }
  14932. this.particles.push(particle);
  14933. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  14934. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  14935. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  14936. particle.size = randomNumber(this.minSize, this.maxSize);
  14937. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  14938. this.startPositionFunction(worldMatrix, particle.position);
  14939. var step = randomNumber(0, 1.0);
  14940. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  14941. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  14942. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  14943. }
  14944. };
  14945. ParticleSystem.prototype._getEffect = function () {
  14946. if (this._customEffect) {
  14947. return this._customEffect;
  14948. }
  14949. ;
  14950. var defines = [];
  14951. if (this._scene.clipPlane) {
  14952. defines.push("#define CLIPPLANE");
  14953. }
  14954. // Effect
  14955. var join = defines.join("\n");
  14956. if (this._cachedDefines !== join) {
  14957. this._cachedDefines = join;
  14958. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  14959. }
  14960. return this._effect;
  14961. };
  14962. ParticleSystem.prototype.animate = function () {
  14963. if (!this._started)
  14964. return;
  14965. var effect = this._getEffect();
  14966. // Check
  14967. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  14968. return;
  14969. if (this._currentRenderId === this._scene.getRenderId()) {
  14970. return;
  14971. }
  14972. this._currentRenderId = this._scene.getRenderId();
  14973. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  14974. // determine the number of particles we need to create
  14975. var emitCout;
  14976. if (this.manualEmitCount > -1) {
  14977. emitCout = this.manualEmitCount;
  14978. this.manualEmitCount = 0;
  14979. }
  14980. else {
  14981. emitCout = this.emitRate;
  14982. }
  14983. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  14984. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  14985. if (this._newPartsExcess > 1.0) {
  14986. newParticles += this._newPartsExcess >> 0;
  14987. this._newPartsExcess -= this._newPartsExcess >> 0;
  14988. }
  14989. this._alive = false;
  14990. if (!this._stopped) {
  14991. this._actualFrame += this._scaledUpdateSpeed;
  14992. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  14993. this.stop();
  14994. }
  14995. else {
  14996. newParticles = 0;
  14997. }
  14998. this._update(newParticles);
  14999. // Stopped?
  15000. if (this._stopped) {
  15001. if (!this._alive) {
  15002. this._started = false;
  15003. if (this.disposeOnStop) {
  15004. this._scene._toBeDisposed.push(this);
  15005. }
  15006. }
  15007. }
  15008. // Update VBO
  15009. var offset = 0;
  15010. for (var index = 0; index < this.particles.length; index++) {
  15011. var particle = this.particles[index];
  15012. this._appendParticleVertex(offset++, particle, 0, 0);
  15013. this._appendParticleVertex(offset++, particle, 1, 0);
  15014. this._appendParticleVertex(offset++, particle, 1, 1);
  15015. this._appendParticleVertex(offset++, particle, 0, 1);
  15016. }
  15017. var engine = this._scene.getEngine();
  15018. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15019. };
  15020. ParticleSystem.prototype.render = function () {
  15021. var effect = this._getEffect();
  15022. // Check
  15023. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15024. return 0;
  15025. var engine = this._scene.getEngine();
  15026. // Render
  15027. engine.enableEffect(effect);
  15028. engine.setState(false);
  15029. var viewMatrix = this._scene.getViewMatrix();
  15030. effect.setTexture("diffuseSampler", this.particleTexture);
  15031. effect.setMatrix("view", viewMatrix);
  15032. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15033. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15034. if (this._scene.clipPlane) {
  15035. var clipPlane = this._scene.clipPlane;
  15036. var invView = viewMatrix.clone();
  15037. invView.invert();
  15038. effect.setMatrix("invView", invView);
  15039. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15040. }
  15041. // VBOs
  15042. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15043. // Draw order
  15044. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15045. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15046. }
  15047. else {
  15048. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15049. }
  15050. if (this.forceDepthWrite) {
  15051. engine.setDepthWrite(true);
  15052. }
  15053. engine.draw(true, 0, this.particles.length * 6);
  15054. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15055. return this.particles.length;
  15056. };
  15057. ParticleSystem.prototype.dispose = function () {
  15058. if (this._vertexBuffer) {
  15059. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15060. this._vertexBuffer = null;
  15061. }
  15062. if (this._indexBuffer) {
  15063. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15064. this._indexBuffer = null;
  15065. }
  15066. if (this.particleTexture) {
  15067. this.particleTexture.dispose();
  15068. this.particleTexture = null;
  15069. }
  15070. // Remove from scene
  15071. var index = this._scene.particleSystems.indexOf(this);
  15072. this._scene.particleSystems.splice(index, 1);
  15073. // Callback
  15074. if (this.onDispose) {
  15075. this.onDispose();
  15076. }
  15077. };
  15078. // Clone
  15079. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15080. var result = new ParticleSystem(name, this._capacity, this._scene);
  15081. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15082. if (newEmitter === undefined) {
  15083. newEmitter = this.emitter;
  15084. }
  15085. result.emitter = newEmitter;
  15086. if (this.particleTexture) {
  15087. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15088. }
  15089. result.start();
  15090. return result;
  15091. };
  15092. // Statics
  15093. ParticleSystem.BLENDMODE_ONEONE = 0;
  15094. ParticleSystem.BLENDMODE_STANDARD = 1;
  15095. return ParticleSystem;
  15096. })();
  15097. BABYLON.ParticleSystem = ParticleSystem;
  15098. })(BABYLON || (BABYLON = {}));
  15099. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15100. (function (BABYLON) {
  15101. var Animation = (function () {
  15102. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15103. this.name = name;
  15104. this.targetProperty = targetProperty;
  15105. this.framePerSecond = framePerSecond;
  15106. this.dataType = dataType;
  15107. this.loopMode = loopMode;
  15108. this._offsetsCache = {};
  15109. this._highLimitsCache = {};
  15110. this._stopped = false;
  15111. this.targetPropertyPath = targetProperty.split(".");
  15112. this.dataType = dataType;
  15113. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15114. }
  15115. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15116. var dataType = undefined;
  15117. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15118. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15119. }
  15120. else if (from instanceof BABYLON.Quaternion) {
  15121. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15122. }
  15123. else if (from instanceof BABYLON.Vector3) {
  15124. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15125. }
  15126. else if (from instanceof BABYLON.Vector2) {
  15127. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15128. }
  15129. else if (from instanceof BABYLON.Color3) {
  15130. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15131. }
  15132. if (dataType == undefined) {
  15133. return;
  15134. }
  15135. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15136. var keys = [];
  15137. keys.push({ frame: 0, value: from });
  15138. keys.push({ frame: totalFrame, value: to });
  15139. animation.setKeys(keys);
  15140. mesh.animations.push(animation);
  15141. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15142. };
  15143. // Methods
  15144. Animation.prototype.isStopped = function () {
  15145. return this._stopped;
  15146. };
  15147. Animation.prototype.getKeys = function () {
  15148. return this._keys;
  15149. };
  15150. Animation.prototype.getEasingFunction = function () {
  15151. return this._easingFunction;
  15152. };
  15153. Animation.prototype.setEasingFunction = function (easingFunction) {
  15154. this._easingFunction = easingFunction;
  15155. };
  15156. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15157. return startValue + (endValue - startValue) * gradient;
  15158. };
  15159. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15160. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15161. };
  15162. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15163. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15164. };
  15165. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15166. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15167. };
  15168. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15169. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15170. };
  15171. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15172. var startScale = new BABYLON.Vector3(0, 0, 0);
  15173. var startRotation = new BABYLON.Quaternion();
  15174. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15175. startValue.decompose(startScale, startRotation, startTranslation);
  15176. var endScale = new BABYLON.Vector3(0, 0, 0);
  15177. var endRotation = new BABYLON.Quaternion();
  15178. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15179. endValue.decompose(endScale, endRotation, endTranslation);
  15180. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15181. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15182. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15183. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15184. return result;
  15185. };
  15186. Animation.prototype.clone = function () {
  15187. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15188. clone.setKeys(this._keys);
  15189. return clone;
  15190. };
  15191. Animation.prototype.setKeys = function (values) {
  15192. this._keys = values.slice(0);
  15193. this._offsetsCache = {};
  15194. this._highLimitsCache = {};
  15195. };
  15196. Animation.prototype._getKeyValue = function (value) {
  15197. if (typeof value === "function") {
  15198. return value();
  15199. }
  15200. return value;
  15201. };
  15202. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15203. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15204. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15205. }
  15206. this.currentFrame = currentFrame;
  15207. for (var key = 0; key < this._keys.length; key++) {
  15208. // for each frame, we need the key just before the frame superior
  15209. if (this._keys[key + 1].frame >= currentFrame) {
  15210. var startValue = this._getKeyValue(this._keys[key].value);
  15211. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15212. // gradient : percent of currentFrame between the frame inf and the frame sup
  15213. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15214. // check for easingFunction and correction of gradient
  15215. if (this._easingFunction != null) {
  15216. gradient = this._easingFunction.ease(gradient);
  15217. }
  15218. switch (this.dataType) {
  15219. case Animation.ANIMATIONTYPE_FLOAT:
  15220. switch (loopMode) {
  15221. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15222. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15223. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15224. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15225. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15226. }
  15227. break;
  15228. case Animation.ANIMATIONTYPE_QUATERNION:
  15229. var quaternion = null;
  15230. switch (loopMode) {
  15231. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15232. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15233. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15234. break;
  15235. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15236. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15237. break;
  15238. }
  15239. return quaternion;
  15240. case Animation.ANIMATIONTYPE_VECTOR3:
  15241. switch (loopMode) {
  15242. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15243. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15244. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15245. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15246. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15247. }
  15248. case Animation.ANIMATIONTYPE_VECTOR2:
  15249. switch (loopMode) {
  15250. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15251. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15252. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15253. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15254. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15255. }
  15256. case Animation.ANIMATIONTYPE_COLOR3:
  15257. switch (loopMode) {
  15258. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15259. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15260. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15261. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15262. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15263. }
  15264. case Animation.ANIMATIONTYPE_MATRIX:
  15265. switch (loopMode) {
  15266. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15267. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15268. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15269. return startValue;
  15270. }
  15271. default:
  15272. break;
  15273. }
  15274. break;
  15275. }
  15276. }
  15277. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15278. };
  15279. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15280. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15281. this._stopped = true;
  15282. return false;
  15283. }
  15284. var returnValue = true;
  15285. // Adding a start key at frame 0 if missing
  15286. if (this._keys[0].frame !== 0) {
  15287. var newKey = { frame: 0, value: this._keys[0].value };
  15288. this._keys.splice(0, 0, newKey);
  15289. }
  15290. // Check limits
  15291. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15292. from = this._keys[0].frame;
  15293. }
  15294. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15295. to = this._keys[this._keys.length - 1].frame;
  15296. }
  15297. // Compute ratio
  15298. var range = to - from;
  15299. var offsetValue;
  15300. // ratio represents the frame delta between from and to
  15301. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15302. var highLimitValue = 0;
  15303. if (ratio > range && !loop) {
  15304. returnValue = false;
  15305. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15306. }
  15307. else {
  15308. // Get max value if required
  15309. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15310. var keyOffset = to.toString() + from.toString();
  15311. if (!this._offsetsCache[keyOffset]) {
  15312. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15313. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15314. switch (this.dataType) {
  15315. case Animation.ANIMATIONTYPE_FLOAT:
  15316. this._offsetsCache[keyOffset] = toValue - fromValue;
  15317. break;
  15318. case Animation.ANIMATIONTYPE_QUATERNION:
  15319. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15320. break;
  15321. case Animation.ANIMATIONTYPE_VECTOR3:
  15322. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15323. case Animation.ANIMATIONTYPE_VECTOR2:
  15324. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15325. case Animation.ANIMATIONTYPE_COLOR3:
  15326. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15327. default:
  15328. break;
  15329. }
  15330. this._highLimitsCache[keyOffset] = toValue;
  15331. }
  15332. highLimitValue = this._highLimitsCache[keyOffset];
  15333. offsetValue = this._offsetsCache[keyOffset];
  15334. }
  15335. }
  15336. if (offsetValue === undefined) {
  15337. switch (this.dataType) {
  15338. case Animation.ANIMATIONTYPE_FLOAT:
  15339. offsetValue = 0;
  15340. break;
  15341. case Animation.ANIMATIONTYPE_QUATERNION:
  15342. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  15343. break;
  15344. case Animation.ANIMATIONTYPE_VECTOR3:
  15345. offsetValue = BABYLON.Vector3.Zero();
  15346. break;
  15347. case Animation.ANIMATIONTYPE_VECTOR2:
  15348. offsetValue = BABYLON.Vector2.Zero();
  15349. break;
  15350. case Animation.ANIMATIONTYPE_COLOR3:
  15351. offsetValue = BABYLON.Color3.Black();
  15352. }
  15353. }
  15354. // Compute value
  15355. var repeatCount = (ratio / range) >> 0;
  15356. var currentFrame = returnValue ? from + ratio % range : to;
  15357. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  15358. // Set value
  15359. if (this.targetPropertyPath.length > 1) {
  15360. var property = this._target[this.targetPropertyPath[0]];
  15361. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  15362. property = property[this.targetPropertyPath[index]];
  15363. }
  15364. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  15365. }
  15366. else {
  15367. this._target[this.targetPropertyPath[0]] = currentValue;
  15368. }
  15369. if (this._target.markAsDirty) {
  15370. this._target.markAsDirty(this.targetProperty);
  15371. }
  15372. if (!returnValue) {
  15373. this._stopped = true;
  15374. }
  15375. return returnValue;
  15376. };
  15377. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  15378. get: function () {
  15379. return Animation._ANIMATIONTYPE_FLOAT;
  15380. },
  15381. enumerable: true,
  15382. configurable: true
  15383. });
  15384. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  15385. get: function () {
  15386. return Animation._ANIMATIONTYPE_VECTOR3;
  15387. },
  15388. enumerable: true,
  15389. configurable: true
  15390. });
  15391. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  15392. get: function () {
  15393. return Animation._ANIMATIONTYPE_VECTOR2;
  15394. },
  15395. enumerable: true,
  15396. configurable: true
  15397. });
  15398. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  15399. get: function () {
  15400. return Animation._ANIMATIONTYPE_QUATERNION;
  15401. },
  15402. enumerable: true,
  15403. configurable: true
  15404. });
  15405. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  15406. get: function () {
  15407. return Animation._ANIMATIONTYPE_MATRIX;
  15408. },
  15409. enumerable: true,
  15410. configurable: true
  15411. });
  15412. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  15413. get: function () {
  15414. return Animation._ANIMATIONTYPE_COLOR3;
  15415. },
  15416. enumerable: true,
  15417. configurable: true
  15418. });
  15419. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  15420. get: function () {
  15421. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  15422. },
  15423. enumerable: true,
  15424. configurable: true
  15425. });
  15426. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  15427. get: function () {
  15428. return Animation._ANIMATIONLOOPMODE_CYCLE;
  15429. },
  15430. enumerable: true,
  15431. configurable: true
  15432. });
  15433. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  15434. get: function () {
  15435. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  15436. },
  15437. enumerable: true,
  15438. configurable: true
  15439. });
  15440. // Statics
  15441. Animation._ANIMATIONTYPE_FLOAT = 0;
  15442. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  15443. Animation._ANIMATIONTYPE_QUATERNION = 2;
  15444. Animation._ANIMATIONTYPE_MATRIX = 3;
  15445. Animation._ANIMATIONTYPE_COLOR3 = 4;
  15446. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  15447. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  15448. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  15449. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  15450. return Animation;
  15451. })();
  15452. BABYLON.Animation = Animation;
  15453. })(BABYLON || (BABYLON = {}));
  15454. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  15455. (function (BABYLON) {
  15456. var Animatable = (function () {
  15457. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  15458. if (fromFrame === void 0) { fromFrame = 0; }
  15459. if (toFrame === void 0) { toFrame = 100; }
  15460. if (loopAnimation === void 0) { loopAnimation = false; }
  15461. if (speedRatio === void 0) { speedRatio = 1.0; }
  15462. this.target = target;
  15463. this.fromFrame = fromFrame;
  15464. this.toFrame = toFrame;
  15465. this.loopAnimation = loopAnimation;
  15466. this.speedRatio = speedRatio;
  15467. this.onAnimationEnd = onAnimationEnd;
  15468. this._animations = new Array();
  15469. this._paused = false;
  15470. this.animationStarted = false;
  15471. if (animations) {
  15472. this.appendAnimations(target, animations);
  15473. }
  15474. this._scene = scene;
  15475. scene._activeAnimatables.push(this);
  15476. }
  15477. // Methods
  15478. Animatable.prototype.appendAnimations = function (target, animations) {
  15479. for (var index = 0; index < animations.length; index++) {
  15480. var animation = animations[index];
  15481. animation._target = target;
  15482. this._animations.push(animation);
  15483. }
  15484. };
  15485. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  15486. var animations = this._animations;
  15487. for (var index = 0; index < animations.length; index++) {
  15488. if (animations[index].targetProperty === property) {
  15489. return animations[index];
  15490. }
  15491. }
  15492. return null;
  15493. };
  15494. Animatable.prototype.pause = function () {
  15495. if (this._paused) {
  15496. return;
  15497. }
  15498. this._paused = true;
  15499. };
  15500. Animatable.prototype.restart = function () {
  15501. this._paused = false;
  15502. };
  15503. Animatable.prototype.stop = function () {
  15504. var index = this._scene._activeAnimatables.indexOf(this);
  15505. if (index > -1) {
  15506. this._scene._activeAnimatables.splice(index, 1);
  15507. }
  15508. if (this.onAnimationEnd) {
  15509. this.onAnimationEnd();
  15510. }
  15511. };
  15512. Animatable.prototype._animate = function (delay) {
  15513. if (this._paused) {
  15514. if (!this._pausedDelay) {
  15515. this._pausedDelay = delay;
  15516. }
  15517. return true;
  15518. }
  15519. if (!this._localDelayOffset) {
  15520. this._localDelayOffset = delay;
  15521. }
  15522. else if (this._pausedDelay) {
  15523. this._localDelayOffset += delay - this._pausedDelay;
  15524. this._pausedDelay = null;
  15525. }
  15526. // Animating
  15527. var running = false;
  15528. var animations = this._animations;
  15529. for (var index = 0; index < animations.length; index++) {
  15530. var animation = animations[index];
  15531. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  15532. running = running || isRunning;
  15533. }
  15534. if (!running && this.onAnimationEnd) {
  15535. this.onAnimationEnd();
  15536. }
  15537. return running;
  15538. };
  15539. return Animatable;
  15540. })();
  15541. BABYLON.Animatable = Animatable;
  15542. })(BABYLON || (BABYLON = {}));
  15543. //# sourceMappingURL=babylon.animatable.js.map
  15544. var BABYLON;
  15545. (function (BABYLON) {
  15546. var EasingFunction = (function () {
  15547. function EasingFunction() {
  15548. // Properties
  15549. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  15550. }
  15551. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  15552. get: function () {
  15553. return EasingFunction._EASINGMODE_EASEIN;
  15554. },
  15555. enumerable: true,
  15556. configurable: true
  15557. });
  15558. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  15559. get: function () {
  15560. return EasingFunction._EASINGMODE_EASEOUT;
  15561. },
  15562. enumerable: true,
  15563. configurable: true
  15564. });
  15565. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  15566. get: function () {
  15567. return EasingFunction._EASINGMODE_EASEINOUT;
  15568. },
  15569. enumerable: true,
  15570. configurable: true
  15571. });
  15572. EasingFunction.prototype.setEasingMode = function (easingMode) {
  15573. var n = Math.min(Math.max(easingMode, 0), 2);
  15574. this._easingMode = n;
  15575. };
  15576. EasingFunction.prototype.getEasingMode = function () {
  15577. return this._easingMode;
  15578. };
  15579. EasingFunction.prototype.easeInCore = function (gradient) {
  15580. throw new Error('You must implement this method');
  15581. };
  15582. EasingFunction.prototype.ease = function (gradient) {
  15583. switch (this._easingMode) {
  15584. case EasingFunction.EASINGMODE_EASEIN:
  15585. return this.easeInCore(gradient);
  15586. case EasingFunction.EASINGMODE_EASEOUT:
  15587. return (1 - this.easeInCore(1 - gradient));
  15588. }
  15589. if (gradient >= 0.5) {
  15590. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  15591. }
  15592. return (this.easeInCore(gradient * 2) * 0.5);
  15593. };
  15594. //Statics
  15595. EasingFunction._EASINGMODE_EASEIN = 0;
  15596. EasingFunction._EASINGMODE_EASEOUT = 1;
  15597. EasingFunction._EASINGMODE_EASEINOUT = 2;
  15598. return EasingFunction;
  15599. })();
  15600. BABYLON.EasingFunction = EasingFunction;
  15601. var CircleEase = (function (_super) {
  15602. __extends(CircleEase, _super);
  15603. function CircleEase() {
  15604. _super.apply(this, arguments);
  15605. }
  15606. CircleEase.prototype.easeInCore = function (gradient) {
  15607. gradient = Math.max(0, Math.min(1, gradient));
  15608. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  15609. };
  15610. return CircleEase;
  15611. })(EasingFunction);
  15612. BABYLON.CircleEase = CircleEase;
  15613. var BackEase = (function (_super) {
  15614. __extends(BackEase, _super);
  15615. function BackEase(amplitude) {
  15616. if (amplitude === void 0) { amplitude = 1; }
  15617. _super.call(this);
  15618. this.amplitude = amplitude;
  15619. }
  15620. BackEase.prototype.easeInCore = function (gradient) {
  15621. var num = Math.max(0, this.amplitude);
  15622. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  15623. };
  15624. return BackEase;
  15625. })(EasingFunction);
  15626. BABYLON.BackEase = BackEase;
  15627. var BounceEase = (function (_super) {
  15628. __extends(BounceEase, _super);
  15629. function BounceEase(bounces, bounciness) {
  15630. if (bounces === void 0) { bounces = 3; }
  15631. if (bounciness === void 0) { bounciness = 2; }
  15632. _super.call(this);
  15633. this.bounces = bounces;
  15634. this.bounciness = bounciness;
  15635. }
  15636. BounceEase.prototype.easeInCore = function (gradient) {
  15637. var y = Math.max(0.0, this.bounces);
  15638. var bounciness = this.bounciness;
  15639. if (bounciness <= 1.0) {
  15640. bounciness = 1.001;
  15641. }
  15642. var num9 = Math.pow(bounciness, y);
  15643. var num5 = 1.0 - bounciness;
  15644. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  15645. var num15 = gradient * num4;
  15646. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  15647. var num3 = Math.floor(num65);
  15648. var num13 = num3 + 1.0;
  15649. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  15650. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  15651. var num7 = (num8 + num12) * 0.5;
  15652. var num6 = gradient - num7;
  15653. var num2 = num7 - num8;
  15654. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  15655. };
  15656. return BounceEase;
  15657. })(EasingFunction);
  15658. BABYLON.BounceEase = BounceEase;
  15659. var CubicEase = (function (_super) {
  15660. __extends(CubicEase, _super);
  15661. function CubicEase() {
  15662. _super.apply(this, arguments);
  15663. }
  15664. CubicEase.prototype.easeInCore = function (gradient) {
  15665. return (gradient * gradient * gradient);
  15666. };
  15667. return CubicEase;
  15668. })(EasingFunction);
  15669. BABYLON.CubicEase = CubicEase;
  15670. var ElasticEase = (function (_super) {
  15671. __extends(ElasticEase, _super);
  15672. function ElasticEase(oscillations, springiness) {
  15673. if (oscillations === void 0) { oscillations = 3; }
  15674. if (springiness === void 0) { springiness = 3; }
  15675. _super.call(this);
  15676. this.oscillations = oscillations;
  15677. this.springiness = springiness;
  15678. }
  15679. ElasticEase.prototype.easeInCore = function (gradient) {
  15680. var num2;
  15681. var num3 = Math.max(0.0, this.oscillations);
  15682. var num = Math.max(0.0, this.springiness);
  15683. if (num == 0) {
  15684. num2 = gradient;
  15685. }
  15686. else {
  15687. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  15688. }
  15689. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  15690. };
  15691. return ElasticEase;
  15692. })(EasingFunction);
  15693. BABYLON.ElasticEase = ElasticEase;
  15694. var ExponentialEase = (function (_super) {
  15695. __extends(ExponentialEase, _super);
  15696. function ExponentialEase(exponent) {
  15697. if (exponent === void 0) { exponent = 2; }
  15698. _super.call(this);
  15699. this.exponent = exponent;
  15700. }
  15701. ExponentialEase.prototype.easeInCore = function (gradient) {
  15702. if (this.exponent <= 0) {
  15703. return gradient;
  15704. }
  15705. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  15706. };
  15707. return ExponentialEase;
  15708. })(EasingFunction);
  15709. BABYLON.ExponentialEase = ExponentialEase;
  15710. var PowerEase = (function (_super) {
  15711. __extends(PowerEase, _super);
  15712. function PowerEase(power) {
  15713. if (power === void 0) { power = 2; }
  15714. _super.call(this);
  15715. this.power = power;
  15716. }
  15717. PowerEase.prototype.easeInCore = function (gradient) {
  15718. var y = Math.max(0.0, this.power);
  15719. return Math.pow(gradient, y);
  15720. };
  15721. return PowerEase;
  15722. })(EasingFunction);
  15723. BABYLON.PowerEase = PowerEase;
  15724. var QuadraticEase = (function (_super) {
  15725. __extends(QuadraticEase, _super);
  15726. function QuadraticEase() {
  15727. _super.apply(this, arguments);
  15728. }
  15729. QuadraticEase.prototype.easeInCore = function (gradient) {
  15730. return (gradient * gradient);
  15731. };
  15732. return QuadraticEase;
  15733. })(EasingFunction);
  15734. BABYLON.QuadraticEase = QuadraticEase;
  15735. var QuarticEase = (function (_super) {
  15736. __extends(QuarticEase, _super);
  15737. function QuarticEase() {
  15738. _super.apply(this, arguments);
  15739. }
  15740. QuarticEase.prototype.easeInCore = function (gradient) {
  15741. return (gradient * gradient * gradient * gradient);
  15742. };
  15743. return QuarticEase;
  15744. })(EasingFunction);
  15745. BABYLON.QuarticEase = QuarticEase;
  15746. var QuinticEase = (function (_super) {
  15747. __extends(QuinticEase, _super);
  15748. function QuinticEase() {
  15749. _super.apply(this, arguments);
  15750. }
  15751. QuinticEase.prototype.easeInCore = function (gradient) {
  15752. return (gradient * gradient * gradient * gradient * gradient);
  15753. };
  15754. return QuinticEase;
  15755. })(EasingFunction);
  15756. BABYLON.QuinticEase = QuinticEase;
  15757. var SineEase = (function (_super) {
  15758. __extends(SineEase, _super);
  15759. function SineEase() {
  15760. _super.apply(this, arguments);
  15761. }
  15762. SineEase.prototype.easeInCore = function (gradient) {
  15763. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  15764. };
  15765. return SineEase;
  15766. })(EasingFunction);
  15767. BABYLON.SineEase = SineEase;
  15768. var BezierCurveEase = (function (_super) {
  15769. __extends(BezierCurveEase, _super);
  15770. function BezierCurveEase(x1, y1, x2, y2) {
  15771. if (x1 === void 0) { x1 = 0; }
  15772. if (y1 === void 0) { y1 = 0; }
  15773. if (x2 === void 0) { x2 = 1; }
  15774. if (y2 === void 0) { y2 = 1; }
  15775. _super.call(this);
  15776. this.x1 = x1;
  15777. this.y1 = y1;
  15778. this.x2 = x2;
  15779. this.y2 = y2;
  15780. }
  15781. BezierCurveEase.prototype.easeInCore = function (gradient) {
  15782. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  15783. };
  15784. return BezierCurveEase;
  15785. })(EasingFunction);
  15786. BABYLON.BezierCurveEase = BezierCurveEase;
  15787. })(BABYLON || (BABYLON = {}));
  15788. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  15789. (function (BABYLON) {
  15790. var Octree = (function () {
  15791. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  15792. if (maxDepth === void 0) { maxDepth = 2; }
  15793. this.maxDepth = maxDepth;
  15794. this.dynamicContent = new Array();
  15795. this._maxBlockCapacity = maxBlockCapacity || 64;
  15796. this._selectionContent = new BABYLON.SmartArray(1024);
  15797. this._creationFunc = creationFunc;
  15798. }
  15799. // Methods
  15800. Octree.prototype.update = function (worldMin, worldMax, entries) {
  15801. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  15802. };
  15803. Octree.prototype.addMesh = function (entry) {
  15804. for (var index = 0; index < this.blocks.length; index++) {
  15805. var block = this.blocks[index];
  15806. block.addEntry(entry);
  15807. }
  15808. };
  15809. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  15810. this._selectionContent.reset();
  15811. for (var index = 0; index < this.blocks.length; index++) {
  15812. var block = this.blocks[index];
  15813. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  15814. }
  15815. if (allowDuplicate) {
  15816. this._selectionContent.concat(this.dynamicContent);
  15817. }
  15818. else {
  15819. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15820. }
  15821. return this._selectionContent;
  15822. };
  15823. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  15824. this._selectionContent.reset();
  15825. for (var index = 0; index < this.blocks.length; index++) {
  15826. var block = this.blocks[index];
  15827. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  15828. }
  15829. if (allowDuplicate) {
  15830. this._selectionContent.concat(this.dynamicContent);
  15831. }
  15832. else {
  15833. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15834. }
  15835. return this._selectionContent;
  15836. };
  15837. Octree.prototype.intersectsRay = function (ray) {
  15838. this._selectionContent.reset();
  15839. for (var index = 0; index < this.blocks.length; index++) {
  15840. var block = this.blocks[index];
  15841. block.intersectsRay(ray, this._selectionContent);
  15842. }
  15843. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15844. return this._selectionContent;
  15845. };
  15846. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  15847. target.blocks = new Array();
  15848. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  15849. for (var x = 0; x < 2; x++) {
  15850. for (var y = 0; y < 2; y++) {
  15851. for (var z = 0; z < 2; z++) {
  15852. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  15853. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  15854. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  15855. block.addEntries(entries);
  15856. target.blocks.push(block);
  15857. }
  15858. }
  15859. }
  15860. };
  15861. Octree.CreationFuncForMeshes = function (entry, block) {
  15862. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15863. block.entries.push(entry);
  15864. }
  15865. };
  15866. Octree.CreationFuncForSubMeshes = function (entry, block) {
  15867. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15868. block.entries.push(entry);
  15869. }
  15870. };
  15871. return Octree;
  15872. })();
  15873. BABYLON.Octree = Octree;
  15874. })(BABYLON || (BABYLON = {}));
  15875. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  15876. (function (BABYLON) {
  15877. var OctreeBlock = (function () {
  15878. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  15879. this.entries = new Array();
  15880. this._boundingVectors = new Array();
  15881. this._capacity = capacity;
  15882. this._depth = depth;
  15883. this._maxDepth = maxDepth;
  15884. this._creationFunc = creationFunc;
  15885. this._minPoint = minPoint;
  15886. this._maxPoint = maxPoint;
  15887. this._boundingVectors.push(minPoint.clone());
  15888. this._boundingVectors.push(maxPoint.clone());
  15889. this._boundingVectors.push(minPoint.clone());
  15890. this._boundingVectors[2].x = maxPoint.x;
  15891. this._boundingVectors.push(minPoint.clone());
  15892. this._boundingVectors[3].y = maxPoint.y;
  15893. this._boundingVectors.push(minPoint.clone());
  15894. this._boundingVectors[4].z = maxPoint.z;
  15895. this._boundingVectors.push(maxPoint.clone());
  15896. this._boundingVectors[5].z = minPoint.z;
  15897. this._boundingVectors.push(maxPoint.clone());
  15898. this._boundingVectors[6].x = minPoint.x;
  15899. this._boundingVectors.push(maxPoint.clone());
  15900. this._boundingVectors[7].y = minPoint.y;
  15901. }
  15902. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  15903. // Property
  15904. get: function () {
  15905. return this._capacity;
  15906. },
  15907. enumerable: true,
  15908. configurable: true
  15909. });
  15910. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  15911. get: function () {
  15912. return this._minPoint;
  15913. },
  15914. enumerable: true,
  15915. configurable: true
  15916. });
  15917. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  15918. get: function () {
  15919. return this._maxPoint;
  15920. },
  15921. enumerable: true,
  15922. configurable: true
  15923. });
  15924. // Methods
  15925. OctreeBlock.prototype.addEntry = function (entry) {
  15926. if (this.blocks) {
  15927. for (var index = 0; index < this.blocks.length; index++) {
  15928. var block = this.blocks[index];
  15929. block.addEntry(entry);
  15930. }
  15931. return;
  15932. }
  15933. this._creationFunc(entry, this);
  15934. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  15935. this.createInnerBlocks();
  15936. }
  15937. };
  15938. OctreeBlock.prototype.addEntries = function (entries) {
  15939. for (var index = 0; index < entries.length; index++) {
  15940. var mesh = entries[index];
  15941. this.addEntry(mesh);
  15942. }
  15943. };
  15944. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  15945. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  15946. if (this.blocks) {
  15947. for (var index = 0; index < this.blocks.length; index++) {
  15948. var block = this.blocks[index];
  15949. block.select(frustumPlanes, selection, allowDuplicate);
  15950. }
  15951. return;
  15952. }
  15953. if (allowDuplicate) {
  15954. selection.concat(this.entries);
  15955. }
  15956. else {
  15957. selection.concatWithNoDuplicate(this.entries);
  15958. }
  15959. }
  15960. };
  15961. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  15962. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  15963. if (this.blocks) {
  15964. for (var index = 0; index < this.blocks.length; index++) {
  15965. var block = this.blocks[index];
  15966. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  15967. }
  15968. return;
  15969. }
  15970. if (allowDuplicate) {
  15971. selection.concat(this.entries);
  15972. }
  15973. else {
  15974. selection.concatWithNoDuplicate(this.entries);
  15975. }
  15976. }
  15977. };
  15978. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  15979. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  15980. if (this.blocks) {
  15981. for (var index = 0; index < this.blocks.length; index++) {
  15982. var block = this.blocks[index];
  15983. block.intersectsRay(ray, selection);
  15984. }
  15985. return;
  15986. }
  15987. selection.concatWithNoDuplicate(this.entries);
  15988. }
  15989. };
  15990. OctreeBlock.prototype.createInnerBlocks = function () {
  15991. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  15992. };
  15993. return OctreeBlock;
  15994. })();
  15995. BABYLON.OctreeBlock = OctreeBlock;
  15996. })(BABYLON || (BABYLON = {}));
  15997. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  15998. (function (BABYLON) {
  15999. var Bone = (function () {
  16000. function Bone(name, skeleton, parentBone, matrix) {
  16001. this.name = name;
  16002. this.children = new Array();
  16003. this.animations = new Array();
  16004. this._worldTransform = new BABYLON.Matrix();
  16005. this._absoluteTransform = new BABYLON.Matrix();
  16006. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  16007. this._skeleton = skeleton;
  16008. this._matrix = matrix;
  16009. this._baseMatrix = matrix;
  16010. skeleton.bones.push(this);
  16011. if (parentBone) {
  16012. this._parent = parentBone;
  16013. parentBone.children.push(this);
  16014. }
  16015. else {
  16016. this._parent = null;
  16017. }
  16018. this._updateDifferenceMatrix();
  16019. }
  16020. // Members
  16021. Bone.prototype.getParent = function () {
  16022. return this._parent;
  16023. };
  16024. Bone.prototype.getLocalMatrix = function () {
  16025. return this._matrix;
  16026. };
  16027. Bone.prototype.getBaseMatrix = function () {
  16028. return this._baseMatrix;
  16029. };
  16030. Bone.prototype.getWorldMatrix = function () {
  16031. return this._worldTransform;
  16032. };
  16033. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16034. return this._invertedAbsoluteTransform;
  16035. };
  16036. Bone.prototype.getAbsoluteMatrix = function () {
  16037. var matrix = this._matrix.clone();
  16038. var parent = this._parent;
  16039. while (parent) {
  16040. matrix = matrix.multiply(parent.getLocalMatrix());
  16041. parent = parent.getParent();
  16042. }
  16043. return matrix;
  16044. };
  16045. // Methods
  16046. Bone.prototype.updateMatrix = function (matrix) {
  16047. this._matrix = matrix;
  16048. this._skeleton._markAsDirty();
  16049. this._updateDifferenceMatrix();
  16050. };
  16051. Bone.prototype._updateDifferenceMatrix = function () {
  16052. if (this._parent) {
  16053. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16054. }
  16055. else {
  16056. this._absoluteTransform.copyFrom(this._matrix);
  16057. }
  16058. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16059. for (var index = 0; index < this.children.length; index++) {
  16060. this.children[index]._updateDifferenceMatrix();
  16061. }
  16062. };
  16063. Bone.prototype.markAsDirty = function () {
  16064. this._skeleton._markAsDirty();
  16065. };
  16066. return Bone;
  16067. })();
  16068. BABYLON.Bone = Bone;
  16069. })(BABYLON || (BABYLON = {}));
  16070. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16071. (function (BABYLON) {
  16072. var Skeleton = (function () {
  16073. function Skeleton(name, id, scene) {
  16074. this.name = name;
  16075. this.id = id;
  16076. this.bones = new Array();
  16077. this._isDirty = true;
  16078. this._identity = BABYLON.Matrix.Identity();
  16079. this.bones = [];
  16080. this._scene = scene;
  16081. scene.skeletons.push(this);
  16082. }
  16083. // Members
  16084. Skeleton.prototype.getTransformMatrices = function () {
  16085. return this._transformMatrices;
  16086. };
  16087. // Methods
  16088. Skeleton.prototype._markAsDirty = function () {
  16089. this._isDirty = true;
  16090. };
  16091. Skeleton.prototype.prepare = function () {
  16092. if (!this._isDirty) {
  16093. return;
  16094. }
  16095. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16096. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16097. }
  16098. for (var index = 0; index < this.bones.length; index++) {
  16099. var bone = this.bones[index];
  16100. var parentBone = bone.getParent();
  16101. if (parentBone) {
  16102. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16103. }
  16104. else {
  16105. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16106. }
  16107. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16108. }
  16109. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16110. this._isDirty = false;
  16111. };
  16112. Skeleton.prototype.getAnimatables = function () {
  16113. if (!this._animatables || this._animatables.length != this.bones.length) {
  16114. this._animatables = [];
  16115. for (var index = 0; index < this.bones.length; index++) {
  16116. this._animatables.push(this.bones[index]);
  16117. }
  16118. }
  16119. return this._animatables;
  16120. };
  16121. Skeleton.prototype.clone = function (name, id) {
  16122. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  16123. for (var index = 0; index < this.bones.length; index++) {
  16124. var source = this.bones[index];
  16125. var parentBone = null;
  16126. if (source.getParent()) {
  16127. var parentIndex = this.bones.indexOf(source.getParent());
  16128. parentBone = result.bones[parentIndex];
  16129. }
  16130. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16131. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16132. }
  16133. return result;
  16134. };
  16135. return Skeleton;
  16136. })();
  16137. BABYLON.Skeleton = Skeleton;
  16138. })(BABYLON || (BABYLON = {}));
  16139. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16140. (function (BABYLON) {
  16141. var PostProcess = (function () {
  16142. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  16143. this.name = name;
  16144. this.width = -1;
  16145. this.height = -1;
  16146. this._reusable = false;
  16147. this._textures = new BABYLON.SmartArray(2);
  16148. this._currentRenderTextureInd = 0;
  16149. if (camera != null) {
  16150. this._camera = camera;
  16151. this._scene = camera.getScene();
  16152. camera.attachPostProcess(this);
  16153. this._engine = this._scene.getEngine();
  16154. }
  16155. else {
  16156. this._engine = engine;
  16157. }
  16158. this._renderRatio = ratio;
  16159. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16160. this._reusable = reusable || false;
  16161. samplers = samplers || [];
  16162. samplers.push("textureSampler");
  16163. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  16164. }
  16165. PostProcess.prototype.isReusable = function () {
  16166. return this._reusable;
  16167. };
  16168. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16169. camera = camera || this._camera;
  16170. var scene = camera.getScene();
  16171. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16172. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16173. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16174. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16175. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16176. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16177. if (this._textures.length > 0) {
  16178. for (var i = 0; i < this._textures.length; i++) {
  16179. this._engine._releaseTexture(this._textures.data[i]);
  16180. }
  16181. this._textures.reset();
  16182. }
  16183. this.width = desiredWidth;
  16184. this.height = desiredHeight;
  16185. 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 }));
  16186. if (this._reusable) {
  16187. 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 }));
  16188. }
  16189. if (this.onSizeChanged) {
  16190. this.onSizeChanged();
  16191. }
  16192. }
  16193. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16194. if (this.onActivate) {
  16195. this.onActivate(camera);
  16196. }
  16197. // Clear
  16198. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16199. if (this._reusable) {
  16200. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16201. }
  16202. };
  16203. PostProcess.prototype.apply = function () {
  16204. // Check
  16205. if (!this._effect.isReady())
  16206. return null;
  16207. // States
  16208. this._engine.enableEffect(this._effect);
  16209. this._engine.setState(false);
  16210. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16211. this._engine.setDepthBuffer(false);
  16212. this._engine.setDepthWrite(false);
  16213. // Texture
  16214. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16215. // Parameters
  16216. if (this.onApply) {
  16217. this.onApply(this._effect);
  16218. }
  16219. return this._effect;
  16220. };
  16221. PostProcess.prototype.dispose = function (camera) {
  16222. camera = camera || this._camera;
  16223. if (this._textures.length > 0) {
  16224. for (var i = 0; i < this._textures.length; i++) {
  16225. this._engine._releaseTexture(this._textures.data[i]);
  16226. }
  16227. this._textures.reset();
  16228. }
  16229. camera.detachPostProcess(this);
  16230. var index = camera._postProcesses.indexOf(this);
  16231. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16232. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16233. }
  16234. };
  16235. return PostProcess;
  16236. })();
  16237. BABYLON.PostProcess = PostProcess;
  16238. })(BABYLON || (BABYLON = {}));
  16239. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16240. (function (BABYLON) {
  16241. var PostProcessManager = (function () {
  16242. function PostProcessManager(scene) {
  16243. this._vertexDeclaration = [2];
  16244. this._vertexStrideSize = 2 * 4;
  16245. this._scene = scene;
  16246. // VBO
  16247. var vertices = [];
  16248. vertices.push(1, 1);
  16249. vertices.push(-1, 1);
  16250. vertices.push(-1, -1);
  16251. vertices.push(1, -1);
  16252. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16253. // Indices
  16254. var indices = [];
  16255. indices.push(0);
  16256. indices.push(1);
  16257. indices.push(2);
  16258. indices.push(0);
  16259. indices.push(2);
  16260. indices.push(3);
  16261. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16262. }
  16263. // Methods
  16264. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16265. var postProcesses = this._scene.activeCamera._postProcesses;
  16266. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16267. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16268. return false;
  16269. }
  16270. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16271. return true;
  16272. };
  16273. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  16274. var postProcesses = this._scene.activeCamera._postProcesses;
  16275. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16276. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16277. return;
  16278. }
  16279. var engine = this._scene.getEngine();
  16280. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  16281. if (index < postProcessesTakenIndices.length - 1) {
  16282. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  16283. }
  16284. else {
  16285. if (targetTexture) {
  16286. engine.bindFramebuffer(targetTexture);
  16287. }
  16288. else {
  16289. engine.restoreDefaultFramebuffer();
  16290. }
  16291. }
  16292. if (doNotPresent) {
  16293. break;
  16294. }
  16295. var pp = postProcesses[postProcessesTakenIndices[index]];
  16296. var effect = pp.apply();
  16297. if (effect) {
  16298. if (pp.onBeforeRender) {
  16299. pp.onBeforeRender(effect);
  16300. }
  16301. // VBOs
  16302. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16303. // Draw order
  16304. engine.draw(true, 0, 6);
  16305. }
  16306. }
  16307. // Restore depth buffer
  16308. engine.setDepthBuffer(true);
  16309. engine.setDepthWrite(true);
  16310. };
  16311. PostProcessManager.prototype.dispose = function () {
  16312. if (this._vertexBuffer) {
  16313. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16314. this._vertexBuffer = null;
  16315. }
  16316. if (this._indexBuffer) {
  16317. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16318. this._indexBuffer = null;
  16319. }
  16320. };
  16321. return PostProcessManager;
  16322. })();
  16323. BABYLON.PostProcessManager = PostProcessManager;
  16324. })(BABYLON || (BABYLON = {}));
  16325. //# sourceMappingURL=babylon.postProcessManager.js.map
  16326. var BABYLON;
  16327. (function (BABYLON) {
  16328. var PassPostProcess = (function (_super) {
  16329. __extends(PassPostProcess, _super);
  16330. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16331. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  16332. }
  16333. return PassPostProcess;
  16334. })(BABYLON.PostProcess);
  16335. BABYLON.PassPostProcess = PassPostProcess;
  16336. })(BABYLON || (BABYLON = {}));
  16337. //# sourceMappingURL=babylon.passPostProcess.js.map
  16338. var BABYLON;
  16339. (function (BABYLON) {
  16340. var BlurPostProcess = (function (_super) {
  16341. __extends(BlurPostProcess, _super);
  16342. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  16343. var _this = this;
  16344. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  16345. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  16346. this.direction = direction;
  16347. this.blurWidth = blurWidth;
  16348. this.onApply = function (effect) {
  16349. effect.setFloat2("screenSize", _this.width, _this.height);
  16350. effect.setVector2("direction", _this.direction);
  16351. effect.setFloat("blurWidth", _this.blurWidth);
  16352. };
  16353. }
  16354. return BlurPostProcess;
  16355. })(BABYLON.PostProcess);
  16356. BABYLON.BlurPostProcess = BlurPostProcess;
  16357. })(BABYLON || (BABYLON = {}));
  16358. //# sourceMappingURL=babylon.blurPostProcess.js.map
  16359. var BABYLON;
  16360. (function (BABYLON) {
  16361. var FilterPostProcess = (function (_super) {
  16362. __extends(FilterPostProcess, _super);
  16363. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  16364. var _this = this;
  16365. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  16366. this.kernelMatrix = kernelMatrix;
  16367. this.onApply = function (effect) {
  16368. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  16369. };
  16370. }
  16371. return FilterPostProcess;
  16372. })(BABYLON.PostProcess);
  16373. BABYLON.FilterPostProcess = FilterPostProcess;
  16374. })(BABYLON || (BABYLON = {}));
  16375. //# sourceMappingURL=babylon.filterPostProcess.js.map
  16376. var BABYLON;
  16377. (function (BABYLON) {
  16378. var RefractionPostProcess = (function (_super) {
  16379. __extends(RefractionPostProcess, _super);
  16380. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  16381. var _this = this;
  16382. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  16383. this.color = color;
  16384. this.depth = depth;
  16385. this.colorLevel = colorLevel;
  16386. this.onActivate = function (cam) {
  16387. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  16388. };
  16389. this.onApply = function (effect) {
  16390. effect.setColor3("baseColor", _this.color);
  16391. effect.setFloat("depth", _this.depth);
  16392. effect.setFloat("colorLevel", _this.colorLevel);
  16393. effect.setTexture("refractionSampler", _this._refRexture);
  16394. };
  16395. }
  16396. // Methods
  16397. RefractionPostProcess.prototype.dispose = function (camera) {
  16398. if (this._refRexture) {
  16399. this._refRexture.dispose();
  16400. }
  16401. _super.prototype.dispose.call(this, camera);
  16402. };
  16403. return RefractionPostProcess;
  16404. })(BABYLON.PostProcess);
  16405. BABYLON.RefractionPostProcess = RefractionPostProcess;
  16406. })(BABYLON || (BABYLON = {}));
  16407. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  16408. var BABYLON;
  16409. (function (BABYLON) {
  16410. var BlackAndWhitePostProcess = (function (_super) {
  16411. __extends(BlackAndWhitePostProcess, _super);
  16412. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16413. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  16414. }
  16415. return BlackAndWhitePostProcess;
  16416. })(BABYLON.PostProcess);
  16417. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  16418. })(BABYLON || (BABYLON = {}));
  16419. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  16420. var BABYLON;
  16421. (function (BABYLON) {
  16422. var ConvolutionPostProcess = (function (_super) {
  16423. __extends(ConvolutionPostProcess, _super);
  16424. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  16425. var _this = this;
  16426. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  16427. this.kernel = kernel;
  16428. this.onApply = function (effect) {
  16429. effect.setFloat2("screenSize", _this.width, _this.height);
  16430. effect.setArray("kernel", _this.kernel);
  16431. };
  16432. }
  16433. // Statics
  16434. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  16435. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  16436. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  16437. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  16438. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  16439. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  16440. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  16441. return ConvolutionPostProcess;
  16442. })(BABYLON.PostProcess);
  16443. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  16444. })(BABYLON || (BABYLON = {}));
  16445. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  16446. var BABYLON;
  16447. (function (BABYLON) {
  16448. var FxaaPostProcess = (function (_super) {
  16449. __extends(FxaaPostProcess, _super);
  16450. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16451. var _this = this;
  16452. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  16453. this.onSizeChanged = function () {
  16454. _this.texelWidth = 1.0 / _this.width;
  16455. _this.texelHeight = 1.0 / _this.height;
  16456. };
  16457. this.onApply = function (effect) {
  16458. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  16459. };
  16460. }
  16461. return FxaaPostProcess;
  16462. })(BABYLON.PostProcess);
  16463. BABYLON.FxaaPostProcess = FxaaPostProcess;
  16464. })(BABYLON || (BABYLON = {}));
  16465. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  16466. (function (BABYLON) {
  16467. var LensFlare = (function () {
  16468. function LensFlare(size, position, color, imgUrl, system) {
  16469. this.size = size;
  16470. this.position = position;
  16471. this.dispose = function () {
  16472. if (this.texture) {
  16473. this.texture.dispose();
  16474. }
  16475. // Remove from scene
  16476. var index = this._system.lensFlares.indexOf(this);
  16477. this._system.lensFlares.splice(index, 1);
  16478. };
  16479. this.color = color || new BABYLON.Color3(1, 1, 1);
  16480. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  16481. this._system = system;
  16482. system.lensFlares.push(this);
  16483. }
  16484. return LensFlare;
  16485. })();
  16486. BABYLON.LensFlare = LensFlare;
  16487. })(BABYLON || (BABYLON = {}));
  16488. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  16489. (function (BABYLON) {
  16490. var LensFlareSystem = (function () {
  16491. function LensFlareSystem(name, emitter, scene) {
  16492. this.name = name;
  16493. this.lensFlares = new Array();
  16494. this.borderLimit = 300;
  16495. this._vertexDeclaration = [2];
  16496. this._vertexStrideSize = 2 * 4;
  16497. this._isEnabled = true;
  16498. this._scene = scene;
  16499. this._emitter = emitter;
  16500. scene.lensFlareSystems.push(this);
  16501. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  16502. // VBO
  16503. var vertices = [];
  16504. vertices.push(1, 1);
  16505. vertices.push(-1, 1);
  16506. vertices.push(-1, -1);
  16507. vertices.push(1, -1);
  16508. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16509. // Indices
  16510. var indices = [];
  16511. indices.push(0);
  16512. indices.push(1);
  16513. indices.push(2);
  16514. indices.push(0);
  16515. indices.push(2);
  16516. indices.push(3);
  16517. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16518. // Effects
  16519. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  16520. }
  16521. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  16522. get: function () {
  16523. return this._isEnabled;
  16524. },
  16525. set: function (value) {
  16526. this._isEnabled = value;
  16527. },
  16528. enumerable: true,
  16529. configurable: true
  16530. });
  16531. LensFlareSystem.prototype.getScene = function () {
  16532. return this._scene;
  16533. };
  16534. LensFlareSystem.prototype.getEmitter = function () {
  16535. return this._emitter;
  16536. };
  16537. LensFlareSystem.prototype.getEmitterPosition = function () {
  16538. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  16539. };
  16540. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  16541. var position = this.getEmitterPosition();
  16542. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  16543. this._positionX = position.x;
  16544. this._positionY = position.y;
  16545. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  16546. if (position.z > 0) {
  16547. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  16548. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  16549. return true;
  16550. }
  16551. }
  16552. return false;
  16553. };
  16554. LensFlareSystem.prototype._isVisible = function () {
  16555. if (!this._isEnabled) {
  16556. return false;
  16557. }
  16558. var emitterPosition = this.getEmitterPosition();
  16559. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  16560. var distance = direction.length();
  16561. direction.normalize();
  16562. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  16563. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  16564. return !pickInfo.hit || pickInfo.distance > distance;
  16565. };
  16566. LensFlareSystem.prototype.render = function () {
  16567. if (!this._effect.isReady())
  16568. return false;
  16569. var engine = this._scene.getEngine();
  16570. var viewport = this._scene.activeCamera.viewport;
  16571. var globalViewport = viewport.toGlobal(engine);
  16572. // Position
  16573. if (!this.computeEffectivePosition(globalViewport)) {
  16574. return false;
  16575. }
  16576. // Visibility
  16577. if (!this._isVisible()) {
  16578. return false;
  16579. }
  16580. // Intensity
  16581. var awayX;
  16582. var awayY;
  16583. if (this._positionX < this.borderLimit + globalViewport.x) {
  16584. awayX = this.borderLimit + globalViewport.x - this._positionX;
  16585. }
  16586. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  16587. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  16588. }
  16589. else {
  16590. awayX = 0;
  16591. }
  16592. if (this._positionY < this.borderLimit + globalViewport.y) {
  16593. awayY = this.borderLimit + globalViewport.y - this._positionY;
  16594. }
  16595. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  16596. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  16597. }
  16598. else {
  16599. awayY = 0;
  16600. }
  16601. var away = (awayX > awayY) ? awayX : awayY;
  16602. if (away > this.borderLimit) {
  16603. away = this.borderLimit;
  16604. }
  16605. var intensity = 1.0 - (away / this.borderLimit);
  16606. if (intensity < 0) {
  16607. return false;
  16608. }
  16609. if (intensity > 1.0) {
  16610. intensity = 1.0;
  16611. }
  16612. // Position
  16613. var centerX = globalViewport.x + globalViewport.width / 2;
  16614. var centerY = globalViewport.y + globalViewport.height / 2;
  16615. var distX = centerX - this._positionX;
  16616. var distY = centerY - this._positionY;
  16617. // Effects
  16618. engine.enableEffect(this._effect);
  16619. engine.setState(false);
  16620. engine.setDepthBuffer(false);
  16621. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16622. // VBOs
  16623. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16624. for (var index = 0; index < this.lensFlares.length; index++) {
  16625. var flare = this.lensFlares[index];
  16626. var x = centerX - (distX * flare.position);
  16627. var y = centerY - (distY * flare.position);
  16628. var cw = flare.size;
  16629. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  16630. var cx = 2 * (x / globalViewport.width) - 1.0;
  16631. var cy = 1.0 - 2 * (y / globalViewport.height);
  16632. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  16633. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  16634. // Texture
  16635. this._effect.setTexture("textureSampler", flare.texture);
  16636. // Color
  16637. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  16638. // Draw order
  16639. engine.draw(true, 0, 6);
  16640. }
  16641. engine.setDepthBuffer(true);
  16642. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16643. return true;
  16644. };
  16645. LensFlareSystem.prototype.dispose = function () {
  16646. if (this._vertexBuffer) {
  16647. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16648. this._vertexBuffer = null;
  16649. }
  16650. if (this._indexBuffer) {
  16651. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16652. this._indexBuffer = null;
  16653. }
  16654. while (this.lensFlares.length) {
  16655. this.lensFlares[0].dispose();
  16656. }
  16657. // Remove from scene
  16658. var index = this._scene.lensFlareSystems.indexOf(this);
  16659. this._scene.lensFlareSystems.splice(index, 1);
  16660. };
  16661. return LensFlareSystem;
  16662. })();
  16663. BABYLON.LensFlareSystem = LensFlareSystem;
  16664. })(BABYLON || (BABYLON = {}));
  16665. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  16666. (function (BABYLON) {
  16667. var IntersectionInfo = (function () {
  16668. function IntersectionInfo(bu, bv, distance) {
  16669. this.bu = bu;
  16670. this.bv = bv;
  16671. this.distance = distance;
  16672. this.faceId = 0;
  16673. }
  16674. return IntersectionInfo;
  16675. })();
  16676. BABYLON.IntersectionInfo = IntersectionInfo;
  16677. var PickingInfo = (function () {
  16678. function PickingInfo() {
  16679. this.hit = false;
  16680. this.distance = 0;
  16681. this.pickedPoint = null;
  16682. this.pickedMesh = null;
  16683. this.bu = 0;
  16684. this.bv = 0;
  16685. this.faceId = -1;
  16686. }
  16687. // Methods
  16688. PickingInfo.prototype.getNormal = function () {
  16689. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16690. return null;
  16691. }
  16692. var indices = this.pickedMesh.getIndices();
  16693. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16694. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  16695. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  16696. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  16697. normal0 = normal0.scale(this.bu);
  16698. normal1 = normal1.scale(this.bv);
  16699. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  16700. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  16701. };
  16702. PickingInfo.prototype.getTextureCoordinates = function () {
  16703. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16704. return null;
  16705. }
  16706. var indices = this.pickedMesh.getIndices();
  16707. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16708. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  16709. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  16710. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  16711. uv0 = uv0.scale(this.bu);
  16712. uv1 = uv1.scale(this.bv);
  16713. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  16714. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  16715. };
  16716. return PickingInfo;
  16717. })();
  16718. BABYLON.PickingInfo = PickingInfo;
  16719. })(BABYLON || (BABYLON = {}));
  16720. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  16721. (function (BABYLON) {
  16722. var FilesInput = (function () {
  16723. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  16724. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  16725. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  16726. this.engine = p_engine;
  16727. this.canvas = p_canvas;
  16728. this.currentScene = p_scene;
  16729. this.sceneLoadedCallback = p_sceneLoadedCallback;
  16730. this.progressCallback = p_progressCallback;
  16731. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  16732. this.textureLoadingCallback = p_textureLoadingCallback;
  16733. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  16734. }
  16735. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  16736. var _this = this;
  16737. if (p_elementToMonitor) {
  16738. this.elementToMonitor = p_elementToMonitor;
  16739. this.elementToMonitor.addEventListener("dragenter", function (e) {
  16740. _this.drag(e);
  16741. }, false);
  16742. this.elementToMonitor.addEventListener("dragover", function (e) {
  16743. _this.drag(e);
  16744. }, false);
  16745. this.elementToMonitor.addEventListener("drop", function (e) {
  16746. _this.drop(e);
  16747. }, false);
  16748. }
  16749. };
  16750. FilesInput.prototype.renderFunction = function () {
  16751. if (this.additionnalRenderLoopLogicCallback) {
  16752. this.additionnalRenderLoopLogicCallback();
  16753. }
  16754. if (this.currentScene) {
  16755. if (this.textureLoadingCallback) {
  16756. var remaining = this.currentScene.getWaitingItemsCount();
  16757. if (remaining > 0) {
  16758. this.textureLoadingCallback(remaining);
  16759. }
  16760. }
  16761. this.currentScene.render();
  16762. }
  16763. };
  16764. FilesInput.prototype.drag = function (e) {
  16765. e.stopPropagation();
  16766. e.preventDefault();
  16767. };
  16768. FilesInput.prototype.drop = function (eventDrop) {
  16769. eventDrop.stopPropagation();
  16770. eventDrop.preventDefault();
  16771. this.loadFiles(eventDrop);
  16772. };
  16773. FilesInput.prototype.loadFiles = function (event) {
  16774. var _this = this;
  16775. var that = this;
  16776. if (this.startingProcessingFilesCallback)
  16777. this.startingProcessingFilesCallback();
  16778. var sceneFileToLoad;
  16779. var filesToLoad;
  16780. // Handling data transfer via drag'n'drop
  16781. if (event && event.dataTransfer && event.dataTransfer.files) {
  16782. filesToLoad = event.dataTransfer.files;
  16783. }
  16784. // Handling files from input files
  16785. if (event && event.target && event.target.files) {
  16786. filesToLoad = event.target.files;
  16787. }
  16788. if (filesToLoad && filesToLoad.length > 0) {
  16789. for (var i = 0; i < filesToLoad.length; i++) {
  16790. switch (filesToLoad[i].type) {
  16791. case "image/jpeg":
  16792. case "image/png":
  16793. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  16794. break;
  16795. case "image/targa":
  16796. case "image/vnd.ms-dds":
  16797. case "audio/wav":
  16798. case "audio/x-wav":
  16799. case "audio/mpeg":
  16800. case "audio/mpeg3":
  16801. case "audio/x-mpeg-3":
  16802. case "audio/ogg":
  16803. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  16804. break;
  16805. default:
  16806. 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) {
  16807. sceneFileToLoad = filesToLoad[i];
  16808. }
  16809. break;
  16810. }
  16811. }
  16812. // If a ".babylon" file has been provided
  16813. if (sceneFileToLoad) {
  16814. if (this.currentScene) {
  16815. this.engine.stopRenderLoop();
  16816. this.currentScene.dispose();
  16817. }
  16818. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  16819. that.currentScene = newScene;
  16820. // Wait for textures and shaders to be ready
  16821. that.currentScene.executeWhenReady(function () {
  16822. // Attach camera to canvas inputs
  16823. if (that.currentScene.activeCamera) {
  16824. that.currentScene.activeCamera.attachControl(that.canvas);
  16825. }
  16826. if (that.sceneLoadedCallback) {
  16827. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  16828. }
  16829. that.engine.runRenderLoop(function () {
  16830. that.renderFunction();
  16831. });
  16832. });
  16833. }, function (progress) {
  16834. if (_this.progressCallback) {
  16835. _this.progressCallback(progress);
  16836. }
  16837. });
  16838. }
  16839. else {
  16840. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  16841. }
  16842. }
  16843. };
  16844. FilesInput.FilesTextures = new Array();
  16845. FilesInput.FilesToLoad = new Array();
  16846. return FilesInput;
  16847. })();
  16848. BABYLON.FilesInput = FilesInput;
  16849. })(BABYLON || (BABYLON = {}));
  16850. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  16851. (function (BABYLON) {
  16852. var OimoJSPlugin = (function () {
  16853. function OimoJSPlugin() {
  16854. this._registeredMeshes = [];
  16855. /**
  16856. * Update the body position according to the mesh position
  16857. * @param mesh
  16858. */
  16859. this.updateBodyPosition = function (mesh) {
  16860. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16861. var registeredMesh = this._registeredMeshes[index];
  16862. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16863. var body = registeredMesh.body.body;
  16864. mesh.computeWorldMatrix(true);
  16865. var center = mesh.getBoundingInfo().boundingBox.center;
  16866. body.setPosition(center.x, center.y, center.z);
  16867. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  16868. return;
  16869. }
  16870. // Case where the parent has been updated
  16871. if (registeredMesh.mesh.parent === mesh) {
  16872. mesh.computeWorldMatrix(true);
  16873. registeredMesh.mesh.computeWorldMatrix(true);
  16874. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  16875. var absoluteRotation = mesh.rotation;
  16876. body = registeredMesh.body.body;
  16877. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  16878. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  16879. return;
  16880. }
  16881. }
  16882. };
  16883. }
  16884. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  16885. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  16886. };
  16887. OimoJSPlugin.prototype.initialize = function (iterations) {
  16888. this._world = new OIMO.World();
  16889. this._world.clear();
  16890. };
  16891. OimoJSPlugin.prototype.setGravity = function (gravity) {
  16892. this._world.gravity = gravity;
  16893. };
  16894. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  16895. var body = null;
  16896. this.unregisterMesh(mesh);
  16897. mesh.computeWorldMatrix(true);
  16898. switch (impostor) {
  16899. case BABYLON.PhysicsEngine.SphereImpostor:
  16900. var initialRotation = null;
  16901. if (mesh.rotationQuaternion) {
  16902. initialRotation = mesh.rotationQuaternion.clone();
  16903. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16904. mesh.computeWorldMatrix(true);
  16905. }
  16906. var bbox = mesh.getBoundingInfo().boundingBox;
  16907. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16908. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16909. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16910. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16911. // The delta between the mesh position and the mesh bounding box center
  16912. var deltaPosition = mesh.position.subtract(bbox.center);
  16913. // Transform delta position with the rotation
  16914. if (initialRotation) {
  16915. var m = new BABYLON.Matrix();
  16916. initialRotation.toRotationMatrix(m);
  16917. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16918. }
  16919. body = new OIMO.Body({
  16920. type: 'sphere',
  16921. size: [size],
  16922. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16923. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16924. move: options.mass != 0,
  16925. config: [options.mass, options.friction, options.restitution],
  16926. world: this._world
  16927. });
  16928. // Restore rotation
  16929. if (initialRotation) {
  16930. body.setQuaternion(initialRotation);
  16931. }
  16932. this._registeredMeshes.push({
  16933. mesh: mesh,
  16934. body: body,
  16935. delta: deltaPosition
  16936. });
  16937. break;
  16938. case BABYLON.PhysicsEngine.PlaneImpostor:
  16939. case BABYLON.PhysicsEngine.BoxImpostor:
  16940. initialRotation = null;
  16941. if (mesh.rotationQuaternion) {
  16942. initialRotation = mesh.rotationQuaternion.clone();
  16943. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16944. mesh.computeWorldMatrix(true);
  16945. }
  16946. bbox = mesh.getBoundingInfo().boundingBox;
  16947. var min = bbox.minimumWorld;
  16948. var max = bbox.maximumWorld;
  16949. var box = max.subtract(min);
  16950. var sizeX = this._checkWithEpsilon(box.x);
  16951. var sizeY = this._checkWithEpsilon(box.y);
  16952. var sizeZ = this._checkWithEpsilon(box.z);
  16953. // The delta between the mesh position and the mesh boudning box center
  16954. deltaPosition = mesh.position.subtract(bbox.center);
  16955. // Transform delta position with the rotation
  16956. if (initialRotation) {
  16957. m = new BABYLON.Matrix();
  16958. initialRotation.toRotationMatrix(m);
  16959. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16960. }
  16961. body = new OIMO.Body({
  16962. type: 'box',
  16963. size: [sizeX, sizeY, sizeZ],
  16964. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16965. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16966. move: options.mass != 0,
  16967. config: [options.mass, options.friction, options.restitution],
  16968. world: this._world
  16969. });
  16970. if (initialRotation) {
  16971. body.setQuaternion(initialRotation);
  16972. }
  16973. this._registeredMeshes.push({
  16974. mesh: mesh,
  16975. body: body,
  16976. delta: deltaPosition
  16977. });
  16978. break;
  16979. }
  16980. return body;
  16981. };
  16982. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  16983. var types = [], sizes = [], positions = [], rotations = [];
  16984. var initialMesh = parts[0].mesh;
  16985. for (var index = 0; index < parts.length; index++) {
  16986. var part = parts[index];
  16987. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  16988. types.push(bodyParameters.type);
  16989. sizes.push.apply(sizes, bodyParameters.size);
  16990. positions.push.apply(positions, bodyParameters.pos);
  16991. rotations.push.apply(rotations, bodyParameters.rot);
  16992. }
  16993. var body = new OIMO.Body({
  16994. type: types,
  16995. size: sizes,
  16996. pos: positions,
  16997. rot: rotations,
  16998. move: options.mass != 0,
  16999. config: [options.mass, options.friction, options.restitution],
  17000. world: this._world
  17001. });
  17002. this._registeredMeshes.push({
  17003. mesh: initialMesh,
  17004. body: body
  17005. });
  17006. return body;
  17007. };
  17008. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  17009. var bodyParameters = null;
  17010. var mesh = part.mesh;
  17011. // We need the bounding box/sphere info to compute the physics body
  17012. mesh.computeWorldMatrix();
  17013. switch (part.impostor) {
  17014. case BABYLON.PhysicsEngine.SphereImpostor:
  17015. var bbox = mesh.getBoundingInfo().boundingBox;
  17016. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17017. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17018. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17019. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17020. bodyParameters = {
  17021. type: 'sphere',
  17022. /* bug with oimo : sphere needs 3 sizes in this case */
  17023. size: [size, -1, -1],
  17024. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17025. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17026. };
  17027. break;
  17028. case BABYLON.PhysicsEngine.PlaneImpostor:
  17029. case BABYLON.PhysicsEngine.BoxImpostor:
  17030. bbox = mesh.getBoundingInfo().boundingBox;
  17031. var min = bbox.minimumWorld;
  17032. var max = bbox.maximumWorld;
  17033. var box = max.subtract(min);
  17034. var sizeX = this._checkWithEpsilon(box.x);
  17035. var sizeY = this._checkWithEpsilon(box.y);
  17036. var sizeZ = this._checkWithEpsilon(box.z);
  17037. var relativePosition = mesh.position;
  17038. bodyParameters = {
  17039. type: 'box',
  17040. size: [sizeX, sizeY, sizeZ],
  17041. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17042. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17043. };
  17044. break;
  17045. }
  17046. return bodyParameters;
  17047. };
  17048. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17049. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17050. var registeredMesh = this._registeredMeshes[index];
  17051. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17052. if (registeredMesh.body) {
  17053. this._world.removeRigidBody(registeredMesh.body.body);
  17054. this._unbindBody(registeredMesh.body);
  17055. }
  17056. this._registeredMeshes.splice(index, 1);
  17057. return;
  17058. }
  17059. }
  17060. };
  17061. OimoJSPlugin.prototype._unbindBody = function (body) {
  17062. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17063. var registeredMesh = this._registeredMeshes[index];
  17064. if (registeredMesh.body === body) {
  17065. registeredMesh.body = null;
  17066. }
  17067. }
  17068. };
  17069. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17070. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17071. var registeredMesh = this._registeredMeshes[index];
  17072. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17073. // Get object mass to have a behaviour similar to cannon.js
  17074. var mass = registeredMesh.body.body.massInfo.mass;
  17075. // The force is scaled with the mass of object
  17076. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17077. return;
  17078. }
  17079. }
  17080. };
  17081. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17082. var body1 = null, body2 = null;
  17083. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17084. var registeredMesh = this._registeredMeshes[index];
  17085. if (registeredMesh.mesh === mesh1) {
  17086. body1 = registeredMesh.body.body;
  17087. }
  17088. else if (registeredMesh.mesh === mesh2) {
  17089. body2 = registeredMesh.body.body;
  17090. }
  17091. }
  17092. if (!body1 || !body2) {
  17093. return false;
  17094. }
  17095. if (!options) {
  17096. options = {};
  17097. }
  17098. new OIMO.Link({
  17099. type: options.type,
  17100. body1: body1,
  17101. body2: body2,
  17102. min: options.min,
  17103. max: options.max,
  17104. axe1: options.axe1,
  17105. axe2: options.axe2,
  17106. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17107. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17108. collision: options.collision,
  17109. spring: options.spring,
  17110. world: this._world
  17111. });
  17112. return true;
  17113. };
  17114. OimoJSPlugin.prototype.dispose = function () {
  17115. this._world.clear();
  17116. while (this._registeredMeshes.length) {
  17117. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17118. }
  17119. };
  17120. OimoJSPlugin.prototype.isSupported = function () {
  17121. return OIMO !== undefined;
  17122. };
  17123. OimoJSPlugin.prototype._getLastShape = function (body) {
  17124. var lastShape = body.shapes;
  17125. while (lastShape.next) {
  17126. lastShape = lastShape.next;
  17127. }
  17128. return lastShape;
  17129. };
  17130. OimoJSPlugin.prototype.runOneStep = function (time) {
  17131. this._world.step();
  17132. // Update the position of all registered meshes
  17133. var i = this._registeredMeshes.length;
  17134. var m;
  17135. while (i--) {
  17136. var body = this._registeredMeshes[i].body.body;
  17137. var mesh = this._registeredMeshes[i].mesh;
  17138. var delta = this._registeredMeshes[i].delta;
  17139. if (!body.sleeping) {
  17140. if (body.shapes.next) {
  17141. var parentShape = this._getLastShape(body);
  17142. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17143. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17144. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17145. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17146. if (!mesh.rotationQuaternion) {
  17147. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17148. }
  17149. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17150. mesh.computeWorldMatrix();
  17151. }
  17152. else {
  17153. m = body.getMatrix();
  17154. mtx = BABYLON.Matrix.FromArray(m);
  17155. // Body position
  17156. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17157. if (!delta) {
  17158. mesh.position.x = bodyX;
  17159. mesh.position.y = bodyY;
  17160. mesh.position.z = bodyZ;
  17161. }
  17162. else {
  17163. mesh.position.x = bodyX + delta.x;
  17164. mesh.position.y = bodyY + delta.y;
  17165. mesh.position.z = bodyZ + delta.z;
  17166. }
  17167. if (!mesh.rotationQuaternion) {
  17168. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17169. }
  17170. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17171. mesh.computeWorldMatrix();
  17172. }
  17173. }
  17174. }
  17175. };
  17176. return OimoJSPlugin;
  17177. })();
  17178. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17179. })(BABYLON || (BABYLON = {}));
  17180. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17181. (function (BABYLON) {
  17182. var PhysicsEngine = (function () {
  17183. function PhysicsEngine(plugin) {
  17184. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17185. }
  17186. PhysicsEngine.prototype._initialize = function (gravity) {
  17187. this._currentPlugin.initialize();
  17188. this._setGravity(gravity);
  17189. };
  17190. PhysicsEngine.prototype._runOneStep = function (delta) {
  17191. if (delta > 0.1) {
  17192. delta = 0.1;
  17193. }
  17194. else if (delta <= 0) {
  17195. delta = 1.0 / 60.0;
  17196. }
  17197. this._currentPlugin.runOneStep(delta);
  17198. };
  17199. PhysicsEngine.prototype._setGravity = function (gravity) {
  17200. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17201. this._currentPlugin.setGravity(this.gravity);
  17202. };
  17203. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17204. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17205. };
  17206. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17207. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17208. };
  17209. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17210. this._currentPlugin.unregisterMesh(mesh);
  17211. };
  17212. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17213. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17214. };
  17215. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17216. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17217. };
  17218. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17219. this._currentPlugin.updateBodyPosition(mesh);
  17220. };
  17221. PhysicsEngine.prototype.dispose = function () {
  17222. this._currentPlugin.dispose();
  17223. };
  17224. PhysicsEngine.prototype.isSupported = function () {
  17225. return this._currentPlugin.isSupported();
  17226. };
  17227. // Statics
  17228. PhysicsEngine.NoImpostor = 0;
  17229. PhysicsEngine.SphereImpostor = 1;
  17230. PhysicsEngine.BoxImpostor = 2;
  17231. PhysicsEngine.PlaneImpostor = 3;
  17232. PhysicsEngine.MeshImpostor = 4;
  17233. PhysicsEngine.CapsuleImpostor = 5;
  17234. PhysicsEngine.ConeImpostor = 6;
  17235. PhysicsEngine.CylinderImpostor = 7;
  17236. PhysicsEngine.ConvexHullImpostor = 8;
  17237. PhysicsEngine.Epsilon = 0.001;
  17238. return PhysicsEngine;
  17239. })();
  17240. BABYLON.PhysicsEngine = PhysicsEngine;
  17241. })(BABYLON || (BABYLON = {}));
  17242. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17243. (function (BABYLON) {
  17244. var serializeLight = function (light) {
  17245. var serializationObject = {};
  17246. serializationObject.name = light.name;
  17247. serializationObject.id = light.id;
  17248. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17249. if (light instanceof BABYLON.PointLight) {
  17250. serializationObject.type = 0;
  17251. serializationObject.position = light.position.asArray();
  17252. }
  17253. else if (light instanceof BABYLON.DirectionalLight) {
  17254. serializationObject.type = 1;
  17255. var directionalLight = light;
  17256. serializationObject.position = directionalLight.position.asArray();
  17257. serializationObject.direction = directionalLight.direction.asArray();
  17258. }
  17259. else if (light instanceof BABYLON.SpotLight) {
  17260. serializationObject.type = 2;
  17261. var spotLight = light;
  17262. serializationObject.position = spotLight.position.asArray();
  17263. serializationObject.direction = spotLight.position.asArray();
  17264. serializationObject.angle = spotLight.angle;
  17265. serializationObject.exponent = spotLight.exponent;
  17266. }
  17267. else if (light instanceof BABYLON.HemisphericLight) {
  17268. serializationObject.type = 3;
  17269. var hemisphericLight = light;
  17270. serializationObject.direction = hemisphericLight.direction.asArray();
  17271. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17272. }
  17273. if (light.intensity) {
  17274. serializationObject.intensity = light.intensity;
  17275. }
  17276. serializationObject.range = light.range;
  17277. serializationObject.diffuse = light.diffuse.asArray();
  17278. serializationObject.specular = light.specular.asArray();
  17279. return serializationObject;
  17280. };
  17281. var serializeFresnelParameter = function (fresnelParameter) {
  17282. var serializationObject = {};
  17283. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17284. serializationObject.leftColor = fresnelParameter.leftColor;
  17285. serializationObject.rightColor = fresnelParameter.rightColor;
  17286. serializationObject.bias = fresnelParameter.bias;
  17287. serializationObject.power = fresnelParameter.power;
  17288. return serializationObject;
  17289. };
  17290. var serializeCamera = function (camera) {
  17291. var serializationObject = {};
  17292. serializationObject.name = camera.name;
  17293. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  17294. serializationObject.id = camera.id;
  17295. serializationObject.position = camera.position.asArray();
  17296. // Parent
  17297. if (camera.parent) {
  17298. serializationObject.parentId = camera.parent.id;
  17299. }
  17300. // Target
  17301. serializationObject.rotation = camera.rotation.asArray();
  17302. // Locked target
  17303. if (camera.lockedTarget && camera.lockedTarget.id) {
  17304. serializationObject.lockedTargetId = camera.lockedTarget.id;
  17305. }
  17306. serializationObject.fov = camera.fov;
  17307. serializationObject.minZ = camera.minZ;
  17308. serializationObject.maxZ = camera.maxZ;
  17309. serializationObject.speed = camera.speed;
  17310. serializationObject.inertia = camera.inertia;
  17311. serializationObject.checkCollisions = camera.checkCollisions;
  17312. serializationObject.applyGravity = camera.applyGravity;
  17313. if (camera.ellipsoid) {
  17314. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  17315. }
  17316. // Animations
  17317. appendAnimations(camera, serializationObject);
  17318. // Layer mask
  17319. serializationObject.layerMask = camera.layerMask;
  17320. return serializationObject;
  17321. };
  17322. var appendAnimations = function (source, destination) {
  17323. if (source.animations) {
  17324. destination.animations = [];
  17325. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  17326. var animation = source.animations[animationIndex];
  17327. destination.animations.push(serializeAnimation(animation));
  17328. }
  17329. }
  17330. };
  17331. var serializeAnimation = function (animation) {
  17332. var serializationObject = {};
  17333. serializationObject.name = animation.name;
  17334. serializationObject.property = animation.targetProperty;
  17335. serializationObject.framePerSecond = animation.framePerSecond;
  17336. serializationObject.dataType = animation.dataType;
  17337. serializationObject.loopBehavior = animation.loopMode;
  17338. var dataType = animation.dataType;
  17339. serializationObject.keys = [];
  17340. var keys = animation.getKeys();
  17341. for (var index = 0; index < keys.length; index++) {
  17342. var animationKey = keys[index];
  17343. var key = {};
  17344. key.frame = animationKey.frame;
  17345. switch (dataType) {
  17346. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17347. key.values = [animationKey.value];
  17348. break;
  17349. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17350. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17351. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17352. key.values = animationKey.value.asArray();
  17353. break;
  17354. }
  17355. serializationObject.keys.push(key);
  17356. }
  17357. return serializationObject;
  17358. };
  17359. var serializeMultiMaterial = function (material) {
  17360. var serializationObject = {};
  17361. serializationObject.name = material.name;
  17362. serializationObject.id = material.id;
  17363. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17364. serializationObject.materials = [];
  17365. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  17366. var subMat = material.subMaterials[matIndex];
  17367. if (subMat) {
  17368. serializationObject.materials.push(subMat.id);
  17369. }
  17370. else {
  17371. serializationObject.materials.push(null);
  17372. }
  17373. }
  17374. return serializationObject;
  17375. };
  17376. var serializeMaterial = function (material) {
  17377. var serializationObject = {};
  17378. serializationObject.name = material.name;
  17379. serializationObject.ambient = material.ambientColor.asArray();
  17380. serializationObject.diffuse = material.diffuseColor.asArray();
  17381. serializationObject.specular = material.specularColor.asArray();
  17382. serializationObject.specularPower = material.specularPower;
  17383. serializationObject.emissive = material.emissiveColor.asArray();
  17384. serializationObject.alpha = material.alpha;
  17385. serializationObject.id = material.id;
  17386. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17387. serializationObject.backFaceCulling = material.backFaceCulling;
  17388. if (material.diffuseTexture) {
  17389. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  17390. }
  17391. if (material.diffuseFresnelParameters) {
  17392. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  17393. }
  17394. if (material.ambientTexture) {
  17395. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  17396. }
  17397. if (material.opacityTexture) {
  17398. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  17399. }
  17400. if (material.opacityFresnelParameters) {
  17401. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  17402. }
  17403. if (material.reflectionTexture) {
  17404. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  17405. }
  17406. if (material.reflectionFresnelParameters) {
  17407. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  17408. }
  17409. if (material.emissiveTexture) {
  17410. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  17411. }
  17412. if (material.emissiveFresnelParameters) {
  17413. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  17414. }
  17415. if (material.specularTexture) {
  17416. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  17417. }
  17418. if (material.bumpTexture) {
  17419. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  17420. }
  17421. return serializationObject;
  17422. };
  17423. var serializeTexture = function (texture) {
  17424. var serializationObject = {};
  17425. if (!texture.name) {
  17426. return null;
  17427. }
  17428. if (texture instanceof BABYLON.CubeTexture) {
  17429. serializationObject.name = texture.name;
  17430. serializationObject.hasAlpha = texture.hasAlpha;
  17431. serializationObject.level = texture.level;
  17432. serializationObject.coordinatesMode = texture.coordinatesMode;
  17433. return serializationObject;
  17434. }
  17435. if (texture instanceof BABYLON.MirrorTexture) {
  17436. var mirrorTexture = texture;
  17437. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  17438. serializationObject.renderList = [];
  17439. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  17440. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  17441. }
  17442. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  17443. }
  17444. else if (texture instanceof BABYLON.RenderTargetTexture) {
  17445. var renderTargetTexture = texture;
  17446. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  17447. serializationObject.renderList = [];
  17448. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  17449. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  17450. }
  17451. }
  17452. var regularTexture = texture;
  17453. serializationObject.name = texture.name;
  17454. serializationObject.hasAlpha = texture.hasAlpha;
  17455. serializationObject.level = texture.level;
  17456. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  17457. serializationObject.coordinatesMode = texture.coordinatesMode;
  17458. serializationObject.uOffset = regularTexture.uOffset;
  17459. serializationObject.vOffset = regularTexture.vOffset;
  17460. serializationObject.uScale = regularTexture.uScale;
  17461. serializationObject.vScale = regularTexture.vScale;
  17462. serializationObject.uAng = regularTexture.uAng;
  17463. serializationObject.vAng = regularTexture.vAng;
  17464. serializationObject.wAng = regularTexture.wAng;
  17465. serializationObject.wrapU = texture.wrapU;
  17466. serializationObject.wrapV = texture.wrapV;
  17467. // Animations
  17468. appendAnimations(texture, serializationObject);
  17469. return serializationObject;
  17470. };
  17471. var serializeSkeleton = function (skeleton) {
  17472. var serializationObject = {};
  17473. serializationObject.name = skeleton.name;
  17474. serializationObject.id = skeleton.id;
  17475. serializationObject.bones = [];
  17476. for (var index = 0; index < skeleton.bones.length; index++) {
  17477. var bone = skeleton.bones[index];
  17478. var serializedBone = {
  17479. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  17480. name: bone.name,
  17481. matrix: bone.getLocalMatrix().toArray()
  17482. };
  17483. serializationObject.bones.push(serializedBone);
  17484. if (bone.animations && bone.animations.length > 0) {
  17485. serializedBone.animation = serializeAnimation(bone.animations[0]);
  17486. }
  17487. }
  17488. return serializationObject;
  17489. };
  17490. var serializeParticleSystem = function (particleSystem) {
  17491. var serializationObject = {};
  17492. serializationObject.emitterId = particleSystem.emitter.id;
  17493. serializationObject.capacity = particleSystem.getCapacity();
  17494. if (particleSystem.particleTexture) {
  17495. serializationObject.textureName = particleSystem.particleTexture.name;
  17496. }
  17497. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  17498. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  17499. serializationObject.minSize = particleSystem.minSize;
  17500. serializationObject.maxSize = particleSystem.maxSize;
  17501. serializationObject.minLifeTime = particleSystem.minLifeTime;
  17502. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  17503. serializationObject.emitRate = particleSystem.emitRate;
  17504. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  17505. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  17506. serializationObject.gravity = particleSystem.gravity.asArray();
  17507. serializationObject.direction1 = particleSystem.direction1.asArray();
  17508. serializationObject.direction2 = particleSystem.direction2.asArray();
  17509. serializationObject.color1 = particleSystem.color1.asArray();
  17510. serializationObject.color2 = particleSystem.color2.asArray();
  17511. serializationObject.colorDead = particleSystem.colorDead.asArray();
  17512. serializationObject.updateSpeed = particleSystem.updateSpeed;
  17513. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  17514. serializationObject.textureMask = particleSystem.textureMask.asArray();
  17515. serializationObject.blendMode = particleSystem.blendMode;
  17516. return serializationObject;
  17517. };
  17518. var serializeLensFlareSystem = function (lensFlareSystem) {
  17519. var serializationObject = {};
  17520. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  17521. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  17522. serializationObject.flares = [];
  17523. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  17524. var flare = lensFlareSystem.lensFlares[index];
  17525. serializationObject.flares.push({
  17526. size: flare.size,
  17527. position: flare.position,
  17528. color: flare.color.asArray(),
  17529. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  17530. });
  17531. }
  17532. return serializationObject;
  17533. };
  17534. var serializeShadowGenerator = function (light) {
  17535. var serializationObject = {};
  17536. var shadowGenerator = light.getShadowGenerator();
  17537. serializationObject.lightId = light.id;
  17538. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  17539. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  17540. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  17541. serializationObject.renderList = [];
  17542. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  17543. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  17544. serializationObject.renderList.push(mesh.id);
  17545. }
  17546. return serializationObject;
  17547. };
  17548. var serializedGeometries = [];
  17549. var serializeGeometry = function (geometry, serializationGeometries) {
  17550. if (serializedGeometries[geometry.id]) {
  17551. return;
  17552. }
  17553. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  17554. serializationGeometries.boxes.push(serializeBox(geometry));
  17555. }
  17556. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  17557. serializationGeometries.spheres.push(serializeSphere(geometry));
  17558. }
  17559. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  17560. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  17561. }
  17562. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  17563. serializationGeometries.toruses.push(serializeTorus(geometry));
  17564. }
  17565. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  17566. serializationGeometries.grounds.push(serializeGround(geometry));
  17567. }
  17568. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  17569. serializationGeometries.planes.push(serializePlane(geometry));
  17570. }
  17571. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  17572. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  17573. }
  17574. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  17575. throw new Error("Unknow primitive type");
  17576. }
  17577. else {
  17578. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  17579. }
  17580. serializedGeometries[geometry.id] = true;
  17581. };
  17582. var serializeGeometryBase = function (geometry) {
  17583. var serializationObject = {};
  17584. serializationObject.id = geometry.id;
  17585. if (BABYLON.Tags.HasTags(geometry)) {
  17586. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  17587. }
  17588. return serializationObject;
  17589. };
  17590. var serializeVertexData = function (vertexData) {
  17591. var serializationObject = serializeGeometryBase(vertexData);
  17592. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17593. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17594. }
  17595. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17596. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17597. }
  17598. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17599. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17600. }
  17601. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17602. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17603. }
  17604. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17605. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17606. }
  17607. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17608. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17609. serializationObject.matricesIndices._isExpanded = true;
  17610. }
  17611. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17612. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17613. }
  17614. serializationObject.indices = vertexData.getIndices();
  17615. return serializationObject;
  17616. };
  17617. var serializePrimitive = function (primitive) {
  17618. var serializationObject = serializeGeometryBase(primitive);
  17619. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  17620. return serializationObject;
  17621. };
  17622. var serializeBox = function (box) {
  17623. var serializationObject = serializePrimitive(box);
  17624. serializationObject.size = box.size;
  17625. return serializationObject;
  17626. };
  17627. var serializeSphere = function (sphere) {
  17628. var serializationObject = serializePrimitive(sphere);
  17629. serializationObject.segments = sphere.segments;
  17630. serializationObject.diameter = sphere.diameter;
  17631. return serializationObject;
  17632. };
  17633. var serializeCylinder = function (cylinder) {
  17634. var serializationObject = serializePrimitive(cylinder);
  17635. serializationObject.height = cylinder.height;
  17636. serializationObject.diameterTop = cylinder.diameterTop;
  17637. serializationObject.diameterBottom = cylinder.diameterBottom;
  17638. serializationObject.tessellation = cylinder.tessellation;
  17639. return serializationObject;
  17640. };
  17641. var serializeTorus = function (torus) {
  17642. var serializationObject = serializePrimitive(torus);
  17643. serializationObject.diameter = torus.diameter;
  17644. serializationObject.thickness = torus.thickness;
  17645. serializationObject.tessellation = torus.tessellation;
  17646. return serializationObject;
  17647. };
  17648. var serializeGround = function (ground) {
  17649. var serializationObject = serializePrimitive(ground);
  17650. serializationObject.width = ground.width;
  17651. serializationObject.height = ground.height;
  17652. serializationObject.subdivisions = ground.subdivisions;
  17653. return serializationObject;
  17654. };
  17655. var serializePlane = function (plane) {
  17656. var serializationObject = serializePrimitive(plane);
  17657. serializationObject.size = plane.size;
  17658. return serializationObject;
  17659. };
  17660. var serializeTorusKnot = function (torusKnot) {
  17661. var serializationObject = serializePrimitive(torusKnot);
  17662. serializationObject.radius = torusKnot.radius;
  17663. serializationObject.tube = torusKnot.tube;
  17664. serializationObject.radialSegments = torusKnot.radialSegments;
  17665. serializationObject.tubularSegments = torusKnot.tubularSegments;
  17666. serializationObject.p = torusKnot.p;
  17667. serializationObject.q = torusKnot.q;
  17668. return serializationObject;
  17669. };
  17670. var serializeMesh = function (mesh, serializationScene) {
  17671. var serializationObject = {};
  17672. serializationObject.name = mesh.name;
  17673. serializationObject.id = mesh.id;
  17674. if (BABYLON.Tags.HasTags(mesh)) {
  17675. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  17676. }
  17677. serializationObject.position = mesh.position.asArray();
  17678. if (mesh.rotationQuaternion) {
  17679. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  17680. }
  17681. else if (mesh.rotation) {
  17682. serializationObject.rotation = mesh.rotation.asArray();
  17683. }
  17684. serializationObject.scaling = mesh.scaling.asArray();
  17685. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  17686. serializationObject.isEnabled = mesh.isEnabled();
  17687. serializationObject.isVisible = mesh.isVisible;
  17688. serializationObject.infiniteDistance = mesh.infiniteDistance;
  17689. serializationObject.pickable = mesh.isPickable;
  17690. serializationObject.receiveShadows = mesh.receiveShadows;
  17691. serializationObject.billboardMode = mesh.billboardMode;
  17692. serializationObject.visibility = mesh.visibility;
  17693. serializationObject.checkCollisions = mesh.checkCollisions;
  17694. // Parent
  17695. if (mesh.parent) {
  17696. serializationObject.parentId = mesh.parent.id;
  17697. }
  17698. // Geometry
  17699. var geometry = mesh._geometry;
  17700. if (geometry) {
  17701. var geometryId = geometry.id;
  17702. serializationObject.geometryId = geometryId;
  17703. if (!mesh.getScene().getGeometryByID(geometryId)) {
  17704. // 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
  17705. serializeGeometry(geometry, serializationScene.geometries);
  17706. }
  17707. // SubMeshes
  17708. serializationObject.subMeshes = [];
  17709. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17710. var subMesh = mesh.subMeshes[subIndex];
  17711. serializationObject.subMeshes.push({
  17712. materialIndex: subMesh.materialIndex,
  17713. verticesStart: subMesh.verticesStart,
  17714. verticesCount: subMesh.verticesCount,
  17715. indexStart: subMesh.indexStart,
  17716. indexCount: subMesh.indexCount
  17717. });
  17718. }
  17719. }
  17720. // Material
  17721. if (mesh.material) {
  17722. serializationObject.materialId = mesh.material.id;
  17723. }
  17724. else {
  17725. mesh.material = null;
  17726. }
  17727. // Skeleton
  17728. if (mesh.skeleton) {
  17729. serializationObject.skeletonId = mesh.skeleton.id;
  17730. }
  17731. // Physics
  17732. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  17733. serializationObject.physicsMass = mesh.getPhysicsMass();
  17734. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  17735. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  17736. switch (mesh.getPhysicsImpostor()) {
  17737. case BABYLON.PhysicsEngine.BoxImpostor:
  17738. serializationObject.physicsImpostor = 1;
  17739. break;
  17740. case BABYLON.PhysicsEngine.SphereImpostor:
  17741. serializationObject.physicsImpostor = 2;
  17742. break;
  17743. }
  17744. }
  17745. // Instances
  17746. serializationObject.instances = [];
  17747. for (var index = 0; index < mesh.instances.length; index++) {
  17748. var instance = mesh.instances[index];
  17749. var serializationInstance = {
  17750. name: instance.name,
  17751. position: instance.position,
  17752. rotation: instance.rotation,
  17753. rotationQuaternion: instance.rotationQuaternion,
  17754. scaling: instance.scaling
  17755. };
  17756. serializationObject.instances.push(serializationInstance);
  17757. // Animations
  17758. appendAnimations(instance, serializationInstance);
  17759. }
  17760. // Animations
  17761. appendAnimations(mesh, serializationObject);
  17762. // Layer mask
  17763. serializationObject.layerMask = mesh.layerMask;
  17764. return serializationObject;
  17765. };
  17766. var SceneSerializer = (function () {
  17767. function SceneSerializer() {
  17768. }
  17769. SceneSerializer.Serialize = function (scene) {
  17770. var serializationObject = {};
  17771. // Scene
  17772. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  17773. serializationObject.autoClear = scene.autoClear;
  17774. serializationObject.clearColor = scene.clearColor.asArray();
  17775. serializationObject.ambientColor = scene.ambientColor.asArray();
  17776. serializationObject.gravity = scene.gravity.asArray();
  17777. // Fog
  17778. if (scene.fogMode && scene.fogMode !== 0) {
  17779. serializationObject.fogMode = scene.fogMode;
  17780. serializationObject.fogColor = scene.fogColor.asArray();
  17781. serializationObject.fogStart = scene.fogStart;
  17782. serializationObject.fogEnd = scene.fogEnd;
  17783. serializationObject.fogDensity = scene.fogDensity;
  17784. }
  17785. // Lights
  17786. serializationObject.lights = [];
  17787. for (var index = 0; index < scene.lights.length; index++) {
  17788. var light = scene.lights[index];
  17789. serializationObject.lights.push(serializeLight(light));
  17790. }
  17791. // Cameras
  17792. serializationObject.cameras = [];
  17793. for (index = 0; index < scene.cameras.length; index++) {
  17794. var camera = scene.cameras[index];
  17795. if (camera instanceof BABYLON.FreeCamera) {
  17796. serializationObject.cameras.push(serializeCamera(camera));
  17797. }
  17798. }
  17799. if (scene.activeCamera) {
  17800. serializationObject.activeCameraID = scene.activeCamera.id;
  17801. }
  17802. // Materials
  17803. serializationObject.materials = [];
  17804. serializationObject.multiMaterials = [];
  17805. for (index = 0; index < scene.materials.length; index++) {
  17806. var material = scene.materials[index];
  17807. if (material instanceof BABYLON.StandardMaterial) {
  17808. serializationObject.materials.push(serializeMaterial(material));
  17809. }
  17810. else if (material instanceof BABYLON.MultiMaterial) {
  17811. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  17812. }
  17813. }
  17814. // Skeletons
  17815. serializationObject.skeletons = [];
  17816. for (index = 0; index < scene.skeletons.length; index++) {
  17817. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  17818. }
  17819. // Geometries
  17820. serializationObject.geometries = {};
  17821. serializationObject.geometries.boxes = [];
  17822. serializationObject.geometries.spheres = [];
  17823. serializationObject.geometries.cylinders = [];
  17824. serializationObject.geometries.toruses = [];
  17825. serializationObject.geometries.grounds = [];
  17826. serializationObject.geometries.planes = [];
  17827. serializationObject.geometries.torusKnots = [];
  17828. serializationObject.geometries.vertexData = [];
  17829. serializedGeometries = [];
  17830. var geometries = scene.getGeometries();
  17831. for (var index = 0; index < geometries.length; index++) {
  17832. var geometry = geometries[index];
  17833. if (geometry.isReady()) {
  17834. serializeGeometry(geometry, serializationObject.geometries);
  17835. }
  17836. }
  17837. // Meshes
  17838. serializationObject.meshes = [];
  17839. for (index = 0; index < scene.meshes.length; index++) {
  17840. var abstractMesh = scene.meshes[index];
  17841. if (abstractMesh instanceof BABYLON.Mesh) {
  17842. var mesh = abstractMesh;
  17843. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  17844. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  17845. }
  17846. }
  17847. }
  17848. // Particles Systems
  17849. serializationObject.particleSystems = [];
  17850. for (index = 0; index < scene.particleSystems.length; index++) {
  17851. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  17852. }
  17853. // Lens flares
  17854. serializationObject.lensFlareSystems = [];
  17855. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  17856. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  17857. }
  17858. // Shadows
  17859. serializationObject.shadowGenerators = [];
  17860. for (index = 0; index < scene.lights.length; index++) {
  17861. light = scene.lights[index];
  17862. if (light.getShadowGenerator()) {
  17863. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  17864. }
  17865. }
  17866. return serializationObject;
  17867. };
  17868. return SceneSerializer;
  17869. })();
  17870. BABYLON.SceneSerializer = SceneSerializer;
  17871. })(BABYLON || (BABYLON = {}));
  17872. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  17873. (function (BABYLON) {
  17874. var SceneLoader = (function () {
  17875. function SceneLoader() {
  17876. }
  17877. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17878. get: function () {
  17879. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17880. },
  17881. set: function (value) {
  17882. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17883. },
  17884. enumerable: true,
  17885. configurable: true
  17886. });
  17887. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17888. get: function () {
  17889. return SceneLoader._ShowLoadingScreen;
  17890. },
  17891. set: function (value) {
  17892. SceneLoader._ShowLoadingScreen = value;
  17893. },
  17894. enumerable: true,
  17895. configurable: true
  17896. });
  17897. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17898. var dotPosition = sceneFilename.lastIndexOf(".");
  17899. var queryStringPosition = sceneFilename.indexOf("?");
  17900. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17901. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17902. var plugin = this._registeredPlugins[index];
  17903. if (plugin.extensions.indexOf(extension) !== -1) {
  17904. return plugin;
  17905. }
  17906. }
  17907. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17908. };
  17909. // Public functions
  17910. SceneLoader.RegisterPlugin = function (plugin) {
  17911. plugin.extensions = plugin.extensions.toLowerCase();
  17912. SceneLoader._registeredPlugins.push(plugin);
  17913. };
  17914. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17915. var manifestChecked = function (success) {
  17916. scene.database = database;
  17917. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17918. var importMeshFromData = function (data) {
  17919. var meshes = [];
  17920. var particleSystems = [];
  17921. var skeletons = [];
  17922. try {
  17923. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17924. if (onerror) {
  17925. onerror(scene, 'unable to load the scene');
  17926. }
  17927. return;
  17928. }
  17929. }
  17930. catch (e) {
  17931. if (onerror) {
  17932. onerror(scene, e);
  17933. }
  17934. return;
  17935. }
  17936. if (onsuccess) {
  17937. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17938. onsuccess(meshes, particleSystems, skeletons);
  17939. }
  17940. };
  17941. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17942. // Direct load
  17943. importMeshFromData(sceneFilename.substr(5));
  17944. return;
  17945. }
  17946. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17947. importMeshFromData(data);
  17948. }, progressCallBack, database);
  17949. };
  17950. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17951. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17952. };
  17953. /**
  17954. * Load a scene
  17955. * @param rootUrl a string that defines the root url for scene and resources
  17956. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17957. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17958. */
  17959. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17960. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17961. };
  17962. /**
  17963. * Append a scene
  17964. * @param rootUrl a string that defines the root url for scene and resources
  17965. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17966. * @param scene is the instance of BABYLON.Scene to append to
  17967. */
  17968. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17969. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17970. var database;
  17971. if (SceneLoader.ShowLoadingScreen) {
  17972. scene.getEngine().displayLoadingUI();
  17973. }
  17974. var loadSceneFromData = function (data) {
  17975. scene.database = database;
  17976. if (!plugin.load(scene, data, rootUrl)) {
  17977. if (onerror) {
  17978. onerror(scene);
  17979. }
  17980. scene.getEngine().hideLoadingUI();
  17981. return;
  17982. }
  17983. if (onsuccess) {
  17984. onsuccess(scene);
  17985. }
  17986. if (SceneLoader.ShowLoadingScreen) {
  17987. scene.executeWhenReady(function () {
  17988. scene.getEngine().hideLoadingUI();
  17989. });
  17990. }
  17991. };
  17992. var manifestChecked = function (success) {
  17993. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17994. };
  17995. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17996. // Direct load
  17997. loadSceneFromData(sceneFilename.substr(5));
  17998. return;
  17999. }
  18000. if (rootUrl.indexOf("file:") === -1) {
  18001. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18002. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18003. }
  18004. else {
  18005. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18006. }
  18007. };
  18008. // Flags
  18009. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18010. SceneLoader._ShowLoadingScreen = true;
  18011. // Members
  18012. SceneLoader._registeredPlugins = new Array();
  18013. return SceneLoader;
  18014. })();
  18015. BABYLON.SceneLoader = SceneLoader;
  18016. ;
  18017. })(BABYLON || (BABYLON = {}));
  18018. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18019. (function (BABYLON) {
  18020. var Internals;
  18021. (function (Internals) {
  18022. var checkColors4 = function (colors, count) {
  18023. // Check if color3 was used
  18024. if (colors.length === count * 3) {
  18025. var colors4 = [];
  18026. for (var index = 0; index < colors.length; index += 3) {
  18027. var newIndex = (index / 3) * 4;
  18028. colors4[newIndex] = colors[index];
  18029. colors4[newIndex + 1] = colors[index + 1];
  18030. colors4[newIndex + 2] = colors[index + 2];
  18031. colors4[newIndex + 3] = 1.0;
  18032. }
  18033. return colors4;
  18034. }
  18035. return colors;
  18036. };
  18037. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18038. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18039. texture.name = parsedTexture.name;
  18040. texture.hasAlpha = parsedTexture.hasAlpha;
  18041. texture.level = parsedTexture.level;
  18042. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18043. return texture;
  18044. };
  18045. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18046. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18047. return null;
  18048. }
  18049. if (parsedTexture.isCube) {
  18050. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18051. }
  18052. var texture;
  18053. if (parsedTexture.mirrorPlane) {
  18054. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18055. texture._waitingRenderList = parsedTexture.renderList;
  18056. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18057. }
  18058. else if (parsedTexture.isRenderTarget) {
  18059. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18060. texture._waitingRenderList = parsedTexture.renderList;
  18061. }
  18062. else {
  18063. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18064. }
  18065. texture.name = parsedTexture.name;
  18066. texture.hasAlpha = parsedTexture.hasAlpha;
  18067. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18068. texture.level = parsedTexture.level;
  18069. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18070. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18071. texture.uOffset = parsedTexture.uOffset;
  18072. texture.vOffset = parsedTexture.vOffset;
  18073. texture.uScale = parsedTexture.uScale;
  18074. texture.vScale = parsedTexture.vScale;
  18075. texture.uAng = parsedTexture.uAng;
  18076. texture.vAng = parsedTexture.vAng;
  18077. texture.wAng = parsedTexture.wAng;
  18078. texture.wrapU = parsedTexture.wrapU;
  18079. texture.wrapV = parsedTexture.wrapV;
  18080. // Animations
  18081. if (parsedTexture.animations) {
  18082. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18083. var parsedAnimation = parsedTexture.animations[animationIndex];
  18084. texture.animations.push(parseAnimation(parsedAnimation));
  18085. }
  18086. }
  18087. return texture;
  18088. };
  18089. var parseSkeleton = function (parsedSkeleton, scene) {
  18090. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18091. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18092. var parsedBone = parsedSkeleton.bones[index];
  18093. var parentBone = null;
  18094. if (parsedBone.parentBoneIndex > -1) {
  18095. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18096. }
  18097. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18098. if (parsedBone.animation) {
  18099. bone.animations.push(parseAnimation(parsedBone.animation));
  18100. }
  18101. }
  18102. return skeleton;
  18103. };
  18104. var parseFresnelParameters = function (parsedFresnelParameters) {
  18105. var fresnelParameters = new BABYLON.FresnelParameters();
  18106. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18107. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18108. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18109. fresnelParameters.bias = parsedFresnelParameters.bias;
  18110. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18111. return fresnelParameters;
  18112. };
  18113. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18114. var material;
  18115. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18116. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18117. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18118. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18119. material.specularPower = parsedMaterial.specularPower;
  18120. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18121. material.alpha = parsedMaterial.alpha;
  18122. material.id = parsedMaterial.id;
  18123. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18124. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18125. material.wireframe = parsedMaterial.wireframe;
  18126. if (parsedMaterial.diffuseTexture) {
  18127. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18128. }
  18129. if (parsedMaterial.diffuseFresnelParameters) {
  18130. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18131. }
  18132. if (parsedMaterial.ambientTexture) {
  18133. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18134. }
  18135. if (parsedMaterial.opacityTexture) {
  18136. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18137. }
  18138. if (parsedMaterial.opacityFresnelParameters) {
  18139. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18140. }
  18141. if (parsedMaterial.reflectionTexture) {
  18142. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18143. }
  18144. if (parsedMaterial.reflectionFresnelParameters) {
  18145. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18146. }
  18147. if (parsedMaterial.emissiveTexture) {
  18148. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18149. }
  18150. if (parsedMaterial.emissiveFresnelParameters) {
  18151. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18152. }
  18153. if (parsedMaterial.specularTexture) {
  18154. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18155. }
  18156. if (parsedMaterial.bumpTexture) {
  18157. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18158. }
  18159. return material;
  18160. };
  18161. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18162. for (var index = 0; index < parsedData.materials.length; index++) {
  18163. var parsedMaterial = parsedData.materials[index];
  18164. if (parsedMaterial.id === id) {
  18165. return parseMaterial(parsedMaterial, scene, rootUrl);
  18166. }
  18167. }
  18168. return null;
  18169. };
  18170. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18171. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18172. multiMaterial.id = parsedMultiMaterial.id;
  18173. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18174. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18175. var subMatId = parsedMultiMaterial.materials[matIndex];
  18176. if (subMatId) {
  18177. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18178. }
  18179. else {
  18180. multiMaterial.subMaterials.push(null);
  18181. }
  18182. }
  18183. return multiMaterial;
  18184. };
  18185. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18186. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18187. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18188. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18189. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18190. var parsedFlare = parsedLensFlareSystem.flares[index];
  18191. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18192. }
  18193. return lensFlareSystem;
  18194. };
  18195. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18196. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18197. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18198. if (parsedParticleSystem.textureName) {
  18199. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18200. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18201. }
  18202. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18203. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18204. particleSystem.minSize = parsedParticleSystem.minSize;
  18205. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18206. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18207. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18208. particleSystem.emitter = emitter;
  18209. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18210. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18211. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18212. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18213. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18214. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18215. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18216. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18217. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18218. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18219. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18220. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18221. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18222. particleSystem.start();
  18223. return particleSystem;
  18224. };
  18225. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18226. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18227. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18228. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18229. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18230. shadowGenerator.getShadowMap().renderList.push(mesh);
  18231. }
  18232. if (parsedShadowGenerator.usePoissonSampling) {
  18233. shadowGenerator.usePoissonSampling = true;
  18234. }
  18235. else {
  18236. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  18237. }
  18238. return shadowGenerator;
  18239. };
  18240. var parseAnimation = function (parsedAnimation) {
  18241. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18242. var dataType = parsedAnimation.dataType;
  18243. var keys = [];
  18244. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18245. var key = parsedAnimation.keys[index];
  18246. var data;
  18247. switch (dataType) {
  18248. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18249. data = key.values[0];
  18250. break;
  18251. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18252. data = BABYLON.Quaternion.FromArray(key.values);
  18253. break;
  18254. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18255. data = BABYLON.Matrix.FromArray(key.values);
  18256. break;
  18257. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18258. default:
  18259. data = BABYLON.Vector3.FromArray(key.values);
  18260. break;
  18261. }
  18262. keys.push({
  18263. frame: key.frame,
  18264. value: data
  18265. });
  18266. }
  18267. animation.setKeys(keys);
  18268. return animation;
  18269. };
  18270. var parseLight = function (parsedLight, scene) {
  18271. var light;
  18272. switch (parsedLight.type) {
  18273. case 0:
  18274. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18275. break;
  18276. case 1:
  18277. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18278. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18279. break;
  18280. case 2:
  18281. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18282. break;
  18283. case 3:
  18284. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18285. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18286. break;
  18287. }
  18288. light.id = parsedLight.id;
  18289. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18290. if (parsedLight.intensity !== undefined) {
  18291. light.intensity = parsedLight.intensity;
  18292. }
  18293. if (parsedLight.range) {
  18294. light.range = parsedLight.range;
  18295. }
  18296. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18297. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18298. if (parsedLight.excludedMeshesIds) {
  18299. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18300. }
  18301. // Parent
  18302. if (parsedLight.parentId) {
  18303. light._waitingParentId = parsedLight.parentId;
  18304. }
  18305. if (parsedLight.includedOnlyMeshesIds) {
  18306. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18307. }
  18308. // Animations
  18309. if (parsedLight.animations) {
  18310. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18311. var parsedAnimation = parsedLight.animations[animationIndex];
  18312. light.animations.push(parseAnimation(parsedAnimation));
  18313. }
  18314. }
  18315. if (parsedLight.autoAnimate) {
  18316. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18317. }
  18318. };
  18319. var parseCamera = function (parsedCamera, scene) {
  18320. var camera;
  18321. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18322. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18323. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18324. var alpha = parsedCamera.alpha;
  18325. var beta = parsedCamera.beta;
  18326. var radius = parsedCamera.radius;
  18327. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18328. var eye_space = parsedCamera.eye_space;
  18329. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18330. }
  18331. else {
  18332. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18333. }
  18334. }
  18335. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18336. eye_space = parsedCamera.eye_space;
  18337. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18338. }
  18339. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18340. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18341. }
  18342. else if (parsedCamera.type === "FollowCamera") {
  18343. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18344. camera.heightOffset = parsedCamera.heightOffset;
  18345. camera.radius = parsedCamera.radius;
  18346. camera.rotationOffset = parsedCamera.rotationOffset;
  18347. if (lockedTargetMesh)
  18348. camera.target = lockedTargetMesh;
  18349. }
  18350. else if (parsedCamera.type === "GamepadCamera") {
  18351. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18352. }
  18353. else if (parsedCamera.type === "OculusCamera") {
  18354. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  18355. }
  18356. else if (parsedCamera.type === "OculusGamepadCamera") {
  18357. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  18358. }
  18359. else if (parsedCamera.type === "TouchCamera") {
  18360. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  18361. }
  18362. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  18363. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  18364. }
  18365. else if (parsedCamera.type === "WebVRCamera") {
  18366. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  18367. }
  18368. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  18369. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  18370. }
  18371. else {
  18372. // Free Camera is the default value
  18373. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  18374. }
  18375. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  18376. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  18377. camera.lockedTarget = lockedTargetMesh;
  18378. }
  18379. camera.id = parsedCamera.id;
  18380. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  18381. // Parent
  18382. if (parsedCamera.parentId) {
  18383. camera._waitingParentId = parsedCamera.parentId;
  18384. }
  18385. // Target
  18386. if (parsedCamera.target) {
  18387. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18388. }
  18389. else {
  18390. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  18391. }
  18392. camera.fov = parsedCamera.fov;
  18393. camera.minZ = parsedCamera.minZ;
  18394. camera.maxZ = parsedCamera.maxZ;
  18395. camera.speed = parsedCamera.speed;
  18396. camera.inertia = parsedCamera.inertia;
  18397. camera.checkCollisions = parsedCamera.checkCollisions;
  18398. camera.applyGravity = parsedCamera.applyGravity;
  18399. if (parsedCamera.ellipsoid) {
  18400. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  18401. }
  18402. // Animations
  18403. if (parsedCamera.animations) {
  18404. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18405. var parsedAnimation = parsedCamera.animations[animationIndex];
  18406. camera.animations.push(parseAnimation(parsedAnimation));
  18407. }
  18408. }
  18409. if (parsedCamera.autoAnimate) {
  18410. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  18411. }
  18412. // Layer Mask
  18413. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  18414. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  18415. }
  18416. else {
  18417. camera.layerMask = 0xFFFFFFFF;
  18418. }
  18419. return camera;
  18420. };
  18421. var parseGeometry = function (parsedGeometry, scene) {
  18422. var id = parsedGeometry.id;
  18423. return scene.getGeometryByID(id);
  18424. };
  18425. var parseBox = function (parsedBox, scene) {
  18426. if (parseGeometry(parsedBox, scene)) {
  18427. return null; // null since geometry could be something else than a box...
  18428. }
  18429. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  18430. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  18431. scene.pushGeometry(box, true);
  18432. return box;
  18433. };
  18434. var parseSphere = function (parsedSphere, scene) {
  18435. if (parseGeometry(parsedSphere, scene)) {
  18436. return null; // null since geometry could be something else than a sphere...
  18437. }
  18438. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18439. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18440. scene.pushGeometry(sphere, true);
  18441. return sphere;
  18442. };
  18443. var parseCylinder = function (parsedCylinder, scene) {
  18444. if (parseGeometry(parsedCylinder, scene)) {
  18445. return null; // null since geometry could be something else than a cylinder...
  18446. }
  18447. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18448. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18449. scene.pushGeometry(cylinder, true);
  18450. return cylinder;
  18451. };
  18452. var parseTorus = function (parsedTorus, scene) {
  18453. if (parseGeometry(parsedTorus, scene)) {
  18454. return null; // null since geometry could be something else than a torus...
  18455. }
  18456. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18457. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18458. scene.pushGeometry(torus, true);
  18459. return torus;
  18460. };
  18461. var parseGround = function (parsedGround, scene) {
  18462. if (parseGeometry(parsedGround, scene)) {
  18463. return null; // null since geometry could be something else than a ground...
  18464. }
  18465. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18466. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18467. scene.pushGeometry(ground, true);
  18468. return ground;
  18469. };
  18470. var parsePlane = function (parsedPlane, scene) {
  18471. if (parseGeometry(parsedPlane, scene)) {
  18472. return null; // null since geometry could be something else than a plane...
  18473. }
  18474. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18475. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18476. scene.pushGeometry(plane, true);
  18477. return plane;
  18478. };
  18479. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18480. if (parseGeometry(parsedTorusKnot, scene)) {
  18481. return null; // null since geometry could be something else than a torusKnot...
  18482. }
  18483. 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);
  18484. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18485. scene.pushGeometry(torusKnot, true);
  18486. return torusKnot;
  18487. };
  18488. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18489. if (parseGeometry(parsedVertexData, scene)) {
  18490. return null; // null since geometry could be a primitive
  18491. }
  18492. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18493. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18494. if (parsedVertexData.delayLoadingFile) {
  18495. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18496. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18497. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18498. geometry._delayInfo = [];
  18499. if (parsedVertexData.hasUVs) {
  18500. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18501. }
  18502. if (parsedVertexData.hasUVs2) {
  18503. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18504. }
  18505. if (parsedVertexData.hasColors) {
  18506. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18507. }
  18508. if (parsedVertexData.hasMatricesIndices) {
  18509. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18510. }
  18511. if (parsedVertexData.hasMatricesWeights) {
  18512. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18513. }
  18514. geometry._delayLoadingFunction = importVertexData;
  18515. }
  18516. else {
  18517. importVertexData(parsedVertexData, geometry);
  18518. }
  18519. scene.pushGeometry(geometry, true);
  18520. return geometry;
  18521. };
  18522. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18523. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18524. mesh.id = parsedMesh.id;
  18525. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18526. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18527. if (parsedMesh.rotationQuaternion) {
  18528. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18529. }
  18530. else if (parsedMesh.rotation) {
  18531. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18532. }
  18533. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18534. if (parsedMesh.localMatrix) {
  18535. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18536. }
  18537. else if (parsedMesh.pivotMatrix) {
  18538. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18539. }
  18540. mesh.setEnabled(parsedMesh.isEnabled);
  18541. mesh.isVisible = parsedMesh.isVisible;
  18542. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18543. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18544. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18545. if (parsedMesh.applyFog !== undefined) {
  18546. mesh.applyFog = parsedMesh.applyFog;
  18547. }
  18548. if (parsedMesh.pickable !== undefined) {
  18549. mesh.isPickable = parsedMesh.pickable;
  18550. }
  18551. if (parsedMesh.alphaIndex !== undefined) {
  18552. mesh.alphaIndex = parsedMesh.alphaIndex;
  18553. }
  18554. mesh.receiveShadows = parsedMesh.receiveShadows;
  18555. mesh.billboardMode = parsedMesh.billboardMode;
  18556. if (parsedMesh.visibility !== undefined) {
  18557. mesh.visibility = parsedMesh.visibility;
  18558. }
  18559. mesh.checkCollisions = parsedMesh.checkCollisions;
  18560. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18561. // Parent
  18562. if (parsedMesh.parentId) {
  18563. mesh._waitingParentId = parsedMesh.parentId;
  18564. }
  18565. // Actions
  18566. if (parsedMesh.actions !== undefined) {
  18567. mesh._waitingActions = parsedMesh.actions;
  18568. }
  18569. // Geometry
  18570. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18571. if (parsedMesh.delayLoadingFile) {
  18572. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18573. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18574. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18575. if (parsedMesh._binaryInfo) {
  18576. mesh._binaryInfo = parsedMesh._binaryInfo;
  18577. }
  18578. mesh._delayInfo = [];
  18579. if (parsedMesh.hasUVs) {
  18580. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18581. }
  18582. if (parsedMesh.hasUVs2) {
  18583. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18584. }
  18585. if (parsedMesh.hasColors) {
  18586. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18587. }
  18588. if (parsedMesh.hasMatricesIndices) {
  18589. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18590. }
  18591. if (parsedMesh.hasMatricesWeights) {
  18592. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18593. }
  18594. mesh._delayLoadingFunction = importGeometry;
  18595. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18596. mesh._checkDelayState();
  18597. }
  18598. }
  18599. else {
  18600. importGeometry(parsedMesh, mesh);
  18601. }
  18602. // Material
  18603. if (parsedMesh.materialId) {
  18604. mesh.setMaterialByID(parsedMesh.materialId);
  18605. }
  18606. else {
  18607. mesh.material = null;
  18608. }
  18609. // Skeleton
  18610. if (parsedMesh.skeletonId > -1) {
  18611. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18612. }
  18613. // Physics
  18614. if (parsedMesh.physicsImpostor) {
  18615. if (!scene.isPhysicsEnabled()) {
  18616. scene.enablePhysics();
  18617. }
  18618. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18619. }
  18620. // Animations
  18621. if (parsedMesh.animations) {
  18622. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18623. var parsedAnimation = parsedMesh.animations[animationIndex];
  18624. mesh.animations.push(parseAnimation(parsedAnimation));
  18625. }
  18626. }
  18627. if (parsedMesh.autoAnimate) {
  18628. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18629. }
  18630. // Layer Mask
  18631. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18632. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18633. }
  18634. else {
  18635. mesh.layerMask = 0xFFFFFFFF;
  18636. }
  18637. // Instances
  18638. if (parsedMesh.instances) {
  18639. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18640. var parsedInstance = parsedMesh.instances[index];
  18641. var instance = mesh.createInstance(parsedInstance.name);
  18642. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18643. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18644. if (parsedInstance.rotationQuaternion) {
  18645. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18646. }
  18647. else if (parsedInstance.rotation) {
  18648. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18649. }
  18650. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18651. instance.checkCollisions = mesh.checkCollisions;
  18652. if (parsedMesh.animations) {
  18653. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18654. parsedAnimation = parsedMesh.animations[animationIndex];
  18655. instance.animations.push(parseAnimation(parsedAnimation));
  18656. }
  18657. }
  18658. }
  18659. }
  18660. return mesh;
  18661. };
  18662. var parseActions = function (parsedActions, object, scene) {
  18663. var actionManager = new BABYLON.ActionManager(scene);
  18664. if (object === null)
  18665. scene.actionManager = actionManager;
  18666. else
  18667. object.actionManager = actionManager;
  18668. // instanciate a new object
  18669. var instanciate = function (name, params) {
  18670. var newInstance = Object.create(BABYLON[name].prototype);
  18671. newInstance.constructor.apply(newInstance, params);
  18672. return newInstance;
  18673. };
  18674. var parseParameter = function (name, value, target, propertyPath) {
  18675. if (propertyPath === null) {
  18676. // String, boolean or float
  18677. var floatValue = parseFloat(value);
  18678. if (value === "true" || value === "false")
  18679. return value === "true";
  18680. else
  18681. return isNaN(floatValue) ? value : floatValue;
  18682. }
  18683. var effectiveTarget = propertyPath.split(".");
  18684. var values = value.split(",");
  18685. for (var i = 0; i < effectiveTarget.length; i++) {
  18686. target = target[effectiveTarget[i]];
  18687. }
  18688. // Return appropriate value with its type
  18689. if (target instanceof Boolean)
  18690. return values[0] === "true";
  18691. if (target instanceof String)
  18692. return values[0];
  18693. // Parameters with multiple values such as Vector3 etc.
  18694. var split = new Array();
  18695. for (var i = 0; i < values.length; i++)
  18696. split.push(parseFloat(values[i]));
  18697. if (target instanceof BABYLON.Vector3)
  18698. return BABYLON.Vector3.FromArray(split);
  18699. if (target instanceof BABYLON.Vector4)
  18700. return BABYLON.Vector4.FromArray(split);
  18701. if (target instanceof BABYLON.Color3)
  18702. return BABYLON.Color3.FromArray(split);
  18703. if (target instanceof BABYLON.Color4)
  18704. return BABYLON.Color4.FromArray(split);
  18705. return parseFloat(values[0]);
  18706. };
  18707. // traverse graph per trigger
  18708. var traverse = function (parsedAction, trigger, condition, action) {
  18709. var parameters = new Array();
  18710. var target = null;
  18711. var propertyPath = null;
  18712. // Parameters
  18713. if (parsedAction.type === 2)
  18714. parameters.push(actionManager);
  18715. else
  18716. parameters.push(trigger);
  18717. for (var i = 0; i < parsedAction.properties.length; i++) {
  18718. var value = parsedAction.properties[i].value;
  18719. var name = parsedAction.properties[i].name;
  18720. if (name === "target")
  18721. value = target = scene.getNodeByName(value);
  18722. else if (name === "parent")
  18723. value = scene.getNodeByName(value);
  18724. else if (name !== "propertyPath") {
  18725. if (parsedAction.type === 2 && name === "operator")
  18726. value = BABYLON.ValueCondition[value];
  18727. else
  18728. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  18729. }
  18730. else {
  18731. propertyPath = value;
  18732. }
  18733. parameters.push(value);
  18734. }
  18735. parameters.push(condition);
  18736. // If interpolate value action
  18737. if (parsedAction.name === "InterpolateValueAction") {
  18738. var param = parameters[parameters.length - 2];
  18739. parameters[parameters.length - 1] = param;
  18740. parameters[parameters.length - 2] = condition;
  18741. }
  18742. // Action or condition(s)
  18743. var newAction = instanciate(parsedAction.name, parameters);
  18744. if (newAction instanceof BABYLON.Condition) {
  18745. condition = newAction;
  18746. newAction = action;
  18747. }
  18748. else {
  18749. condition = null;
  18750. if (action)
  18751. action.then(newAction);
  18752. else
  18753. actionManager.registerAction(newAction);
  18754. }
  18755. for (var i = 0; i < parsedAction.children.length; i++)
  18756. traverse(parsedAction.children[i], trigger, condition, newAction);
  18757. };
  18758. for (var i = 0; i < parsedActions.children.length; i++) {
  18759. var triggerParams;
  18760. var trigger = parsedActions.children[i];
  18761. if (trigger.properties.length > 0) {
  18762. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  18763. }
  18764. else
  18765. triggerParams = BABYLON.ActionManager[trigger.name];
  18766. for (var j = 0; j < trigger.children.length; j++)
  18767. traverse(trigger.children[j], triggerParams, null, null);
  18768. }
  18769. };
  18770. var parseSound = function (parsedSound, scene, rootUrl) {
  18771. var soundName = parsedSound.name;
  18772. var soundUrl = rootUrl + soundName;
  18773. var options = {
  18774. autoplay: parsedSound.autoplay,
  18775. loop: parsedSound.loop,
  18776. volume: parsedSound.volume,
  18777. spatialSound: parsedSound.spatialSound,
  18778. maxDistance: parsedSound.maxDistance,
  18779. rolloffFactor: parsedSound.rolloffFactor,
  18780. refDistance: parsedSound.refDistance,
  18781. distanceModel: parsedSound.distanceModel,
  18782. panningModel: parsedSound.panningModel,
  18783. playbackRate: parsedSound.playbackRate
  18784. };
  18785. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  18786. scene._removePendingData(newSound);
  18787. }, options);
  18788. scene._addPendingData(newSound);
  18789. if (parsedSound.position) {
  18790. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  18791. newSound.setPosition(soundPosition);
  18792. }
  18793. if (parsedSound.isDirectional) {
  18794. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  18795. if (parsedSound.localDirectionToMesh) {
  18796. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  18797. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  18798. }
  18799. }
  18800. if (parsedSound.connectedMeshId) {
  18801. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  18802. if (connectedMesh) {
  18803. newSound.attachToMesh(connectedMesh);
  18804. }
  18805. }
  18806. };
  18807. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18808. names = (names instanceof Array) ? names : [names];
  18809. for (var i in names) {
  18810. if (mesh.name === names[i]) {
  18811. hierarchyIds.push(mesh.id);
  18812. return true;
  18813. }
  18814. }
  18815. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18816. hierarchyIds.push(mesh.id);
  18817. return true;
  18818. }
  18819. return false;
  18820. };
  18821. var importVertexData = function (parsedVertexData, geometry) {
  18822. var vertexData = new BABYLON.VertexData();
  18823. // positions
  18824. var positions = parsedVertexData.positions;
  18825. if (positions) {
  18826. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18827. }
  18828. // normals
  18829. var normals = parsedVertexData.normals;
  18830. if (normals) {
  18831. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18832. }
  18833. // uvs
  18834. var uvs = parsedVertexData.uvs;
  18835. if (uvs) {
  18836. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18837. }
  18838. // uv2s
  18839. var uv2s = parsedVertexData.uv2s;
  18840. if (uv2s) {
  18841. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18842. }
  18843. // colors
  18844. var colors = parsedVertexData.colors;
  18845. if (colors) {
  18846. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18847. }
  18848. // matricesIndices
  18849. var matricesIndices = parsedVertexData.matricesIndices;
  18850. if (matricesIndices) {
  18851. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  18852. }
  18853. // matricesWeights
  18854. var matricesWeights = parsedVertexData.matricesWeights;
  18855. if (matricesWeights) {
  18856. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  18857. }
  18858. // indices
  18859. var indices = parsedVertexData.indices;
  18860. if (indices) {
  18861. vertexData.indices = indices;
  18862. }
  18863. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  18864. };
  18865. var importGeometry = function (parsedGeometry, mesh) {
  18866. var scene = mesh.getScene();
  18867. // Geometry
  18868. var geometryId = parsedGeometry.geometryId;
  18869. if (geometryId) {
  18870. var geometry = scene.getGeometryByID(geometryId);
  18871. if (geometry) {
  18872. geometry.applyToMesh(mesh);
  18873. }
  18874. }
  18875. else if (parsedGeometry instanceof ArrayBuffer) {
  18876. var binaryInfo = mesh._binaryInfo;
  18877. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  18878. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  18879. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  18880. }
  18881. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18882. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18883. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18884. }
  18885. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18886. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18887. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18888. }
  18889. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18890. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18891. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18892. }
  18893. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18894. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18895. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18896. }
  18897. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18898. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18899. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18900. }
  18901. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18902. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18903. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18904. }
  18905. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18906. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18907. mesh.setIndices(indicesData);
  18908. }
  18909. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18910. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18911. mesh.subMeshes = [];
  18912. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18913. var materialIndex = subMeshesData[(i * 5) + 0];
  18914. var verticesStart = subMeshesData[(i * 5) + 1];
  18915. var verticesCount = subMeshesData[(i * 5) + 2];
  18916. var indexStart = subMeshesData[(i * 5) + 3];
  18917. var indexCount = subMeshesData[(i * 5) + 4];
  18918. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18919. }
  18920. }
  18921. }
  18922. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18923. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18924. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18925. if (parsedGeometry.uvs) {
  18926. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  18927. }
  18928. if (parsedGeometry.uvs2) {
  18929. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  18930. }
  18931. if (parsedGeometry.colors) {
  18932. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  18933. }
  18934. if (parsedGeometry.matricesIndices) {
  18935. if (!parsedGeometry.matricesIndices._isExpanded) {
  18936. var floatIndices = [];
  18937. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  18938. var matricesIndex = parsedGeometry.matricesIndices[i];
  18939. floatIndices.push(matricesIndex & 0x000000FF);
  18940. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  18941. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  18942. floatIndices.push(matricesIndex >> 24);
  18943. }
  18944. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  18945. }
  18946. else {
  18947. delete parsedGeometry.matricesIndices._isExpanded;
  18948. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  18949. }
  18950. }
  18951. if (parsedGeometry.matricesWeights) {
  18952. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  18953. }
  18954. mesh.setIndices(parsedGeometry.indices);
  18955. // SubMeshes
  18956. if (parsedGeometry.subMeshes) {
  18957. mesh.subMeshes = [];
  18958. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  18959. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  18960. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  18961. }
  18962. }
  18963. }
  18964. // Flat shading
  18965. if (mesh._shouldGenerateFlatShading) {
  18966. mesh.convertToFlatShadedMesh();
  18967. delete mesh._shouldGenerateFlatShading;
  18968. }
  18969. // Update
  18970. mesh.computeWorldMatrix(true);
  18971. // Octree
  18972. if (scene._selectionOctree) {
  18973. scene._selectionOctree.addMesh(mesh);
  18974. }
  18975. };
  18976. BABYLON.SceneLoader.RegisterPlugin({
  18977. extensions: ".babylon",
  18978. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  18979. var parsedData = JSON.parse(data);
  18980. var loadedSkeletonsIds = [];
  18981. var loadedMaterialsIds = [];
  18982. var hierarchyIds = [];
  18983. for (var index = 0; index < parsedData.meshes.length; index++) {
  18984. var parsedMesh = parsedData.meshes[index];
  18985. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  18986. if (meshesNames instanceof Array) {
  18987. // Remove found mesh name from list.
  18988. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  18989. }
  18990. // Material ?
  18991. if (parsedMesh.materialId) {
  18992. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  18993. if (!materialFound) {
  18994. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  18995. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  18996. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  18997. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18998. var subMatId = parsedMultiMaterial.materials[matIndex];
  18999. loadedMaterialsIds.push(subMatId);
  19000. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19001. }
  19002. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19003. parseMultiMaterial(parsedMultiMaterial, scene);
  19004. materialFound = true;
  19005. break;
  19006. }
  19007. }
  19008. }
  19009. if (!materialFound) {
  19010. loadedMaterialsIds.push(parsedMesh.materialId);
  19011. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19012. }
  19013. }
  19014. // Skeleton ?
  19015. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19016. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19017. if (!skeletonAlreadyLoaded) {
  19018. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19019. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19020. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19021. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19022. loadedSkeletonsIds.push(parsedSkeleton.id);
  19023. }
  19024. }
  19025. }
  19026. }
  19027. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19028. meshes.push(mesh);
  19029. }
  19030. }
  19031. for (index = 0; index < scene.meshes.length; index++) {
  19032. var currentMesh = scene.meshes[index];
  19033. if (currentMesh._waitingParentId) {
  19034. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19035. currentMesh._waitingParentId = undefined;
  19036. }
  19037. }
  19038. // Particles
  19039. if (parsedData.particleSystems) {
  19040. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19041. var parsedParticleSystem = parsedData.particleSystems[index];
  19042. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19043. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19044. }
  19045. }
  19046. }
  19047. return true;
  19048. },
  19049. load: function (scene, data, rootUrl) {
  19050. var parsedData = JSON.parse(data);
  19051. // Scene
  19052. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19053. scene.autoClear = parsedData.autoClear;
  19054. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19055. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19056. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19057. // Fog
  19058. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19059. scene.fogMode = parsedData.fogMode;
  19060. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19061. scene.fogStart = parsedData.fogStart;
  19062. scene.fogEnd = parsedData.fogEnd;
  19063. scene.fogDensity = parsedData.fogDensity;
  19064. }
  19065. for (var index = 0; index < parsedData.lights.length; index++) {
  19066. var parsedLight = parsedData.lights[index];
  19067. parseLight(parsedLight, scene);
  19068. }
  19069. // Materials
  19070. if (parsedData.materials) {
  19071. for (index = 0; index < parsedData.materials.length; index++) {
  19072. var parsedMaterial = parsedData.materials[index];
  19073. parseMaterial(parsedMaterial, scene, rootUrl);
  19074. }
  19075. }
  19076. if (parsedData.multiMaterials) {
  19077. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19078. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19079. parseMultiMaterial(parsedMultiMaterial, scene);
  19080. }
  19081. }
  19082. // Skeletons
  19083. if (parsedData.skeletons) {
  19084. for (index = 0; index < parsedData.skeletons.length; index++) {
  19085. var parsedSkeleton = parsedData.skeletons[index];
  19086. parseSkeleton(parsedSkeleton, scene);
  19087. }
  19088. }
  19089. // Geometries
  19090. var geometries = parsedData.geometries;
  19091. if (geometries) {
  19092. // Boxes
  19093. var boxes = geometries.boxes;
  19094. if (boxes) {
  19095. for (index = 0; index < boxes.length; index++) {
  19096. var parsedBox = boxes[index];
  19097. parseBox(parsedBox, scene);
  19098. }
  19099. }
  19100. // Spheres
  19101. var spheres = geometries.spheres;
  19102. if (spheres) {
  19103. for (index = 0; index < spheres.length; index++) {
  19104. var parsedSphere = spheres[index];
  19105. parseSphere(parsedSphere, scene);
  19106. }
  19107. }
  19108. // Cylinders
  19109. var cylinders = geometries.cylinders;
  19110. if (cylinders) {
  19111. for (index = 0; index < cylinders.length; index++) {
  19112. var parsedCylinder = cylinders[index];
  19113. parseCylinder(parsedCylinder, scene);
  19114. }
  19115. }
  19116. // Toruses
  19117. var toruses = geometries.toruses;
  19118. if (toruses) {
  19119. for (index = 0; index < toruses.length; index++) {
  19120. var parsedTorus = toruses[index];
  19121. parseTorus(parsedTorus, scene);
  19122. }
  19123. }
  19124. // Grounds
  19125. var grounds = geometries.grounds;
  19126. if (grounds) {
  19127. for (index = 0; index < grounds.length; index++) {
  19128. var parsedGround = grounds[index];
  19129. parseGround(parsedGround, scene);
  19130. }
  19131. }
  19132. // Planes
  19133. var planes = geometries.planes;
  19134. if (planes) {
  19135. for (index = 0; index < planes.length; index++) {
  19136. var parsedPlane = planes[index];
  19137. parsePlane(parsedPlane, scene);
  19138. }
  19139. }
  19140. // TorusKnots
  19141. var torusKnots = geometries.torusKnots;
  19142. if (torusKnots) {
  19143. for (index = 0; index < torusKnots.length; index++) {
  19144. var parsedTorusKnot = torusKnots[index];
  19145. parseTorusKnot(parsedTorusKnot, scene);
  19146. }
  19147. }
  19148. // VertexData
  19149. var vertexData = geometries.vertexData;
  19150. if (vertexData) {
  19151. for (index = 0; index < vertexData.length; index++) {
  19152. var parsedVertexData = vertexData[index];
  19153. parseVertexData(parsedVertexData, scene, rootUrl);
  19154. }
  19155. }
  19156. }
  19157. for (index = 0; index < parsedData.meshes.length; index++) {
  19158. var parsedMesh = parsedData.meshes[index];
  19159. parseMesh(parsedMesh, scene, rootUrl);
  19160. }
  19161. for (index = 0; index < parsedData.cameras.length; index++) {
  19162. var parsedCamera = parsedData.cameras[index];
  19163. parseCamera(parsedCamera, scene);
  19164. }
  19165. if (parsedData.activeCameraID) {
  19166. scene.setActiveCameraByID(parsedData.activeCameraID);
  19167. }
  19168. for (index = 0; index < scene.cameras.length; index++) {
  19169. var camera = scene.cameras[index];
  19170. if (camera._waitingParentId) {
  19171. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19172. camera._waitingParentId = undefined;
  19173. }
  19174. }
  19175. for (index = 0; index < scene.lights.length; index++) {
  19176. var light = scene.lights[index];
  19177. if (light._waitingParentId) {
  19178. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19179. light._waitingParentId = undefined;
  19180. }
  19181. }
  19182. for (index = 0; index < scene.meshes.length; index++) {
  19183. var mesh = scene.meshes[index];
  19184. if (mesh._waitingParentId) {
  19185. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19186. mesh._waitingParentId = undefined;
  19187. }
  19188. if (mesh._waitingActions) {
  19189. parseActions(mesh._waitingActions, mesh, scene);
  19190. mesh._waitingActions = undefined;
  19191. }
  19192. }
  19193. // Particles Systems
  19194. if (parsedData.particleSystems) {
  19195. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19196. var parsedParticleSystem = parsedData.particleSystems[index];
  19197. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19198. }
  19199. }
  19200. // Lens flares
  19201. if (parsedData.lensFlareSystems) {
  19202. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19203. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19204. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19205. }
  19206. }
  19207. // Shadows
  19208. if (parsedData.shadowGenerators) {
  19209. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19210. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19211. parseShadowGenerator(parsedShadowGenerator, scene);
  19212. }
  19213. }
  19214. // Sounds
  19215. if (parsedData.sounds && BABYLON.Engine.audioEngine.canUseWebAudio) {
  19216. for (index = 0; index < parsedData.sounds.length; index++) {
  19217. var parsedSound = parsedData.sounds[index];
  19218. parseSound(parsedSound, scene, rootUrl);
  19219. }
  19220. }
  19221. // Actions (scene)
  19222. if (parsedData.actions) {
  19223. parseActions(parsedData.actions, null, scene);
  19224. }
  19225. // Finish
  19226. return true;
  19227. }
  19228. });
  19229. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  19230. })(BABYLON || (BABYLON = {}));
  19231. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  19232. (function (BABYLON) {
  19233. // Unique ID when we import meshes from Babylon to CSG
  19234. var currentCSGMeshId = 0;
  19235. // # class Vertex
  19236. // Represents a vertex of a polygon. Use your own vertex class instead of this
  19237. // one to provide additional features like texture coordinates and vertex
  19238. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  19239. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  19240. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  19241. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  19242. // is not used anywhere else.
  19243. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  19244. var Vertex = (function () {
  19245. function Vertex(pos, normal, uv) {
  19246. this.pos = pos;
  19247. this.normal = normal;
  19248. this.uv = uv;
  19249. }
  19250. Vertex.prototype.clone = function () {
  19251. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  19252. };
  19253. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  19254. // orientation of a polygon is flipped.
  19255. Vertex.prototype.flip = function () {
  19256. this.normal = this.normal.scale(-1);
  19257. };
  19258. // Create a new vertex between this vertex and `other` by linearly
  19259. // interpolating all properties using a parameter of `t`. Subclasses should
  19260. // override this to interpolate additional properties.
  19261. Vertex.prototype.interpolate = function (other, t) {
  19262. 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));
  19263. };
  19264. return Vertex;
  19265. })();
  19266. // # class Plane
  19267. // Represents a plane in 3D space.
  19268. var Plane = (function () {
  19269. function Plane(normal, w) {
  19270. this.normal = normal;
  19271. this.w = w;
  19272. }
  19273. Plane.FromPoints = function (a, b, c) {
  19274. var v0 = c.subtract(a);
  19275. var v1 = b.subtract(a);
  19276. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  19277. return null;
  19278. }
  19279. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  19280. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  19281. };
  19282. Plane.prototype.clone = function () {
  19283. return new Plane(this.normal.clone(), this.w);
  19284. };
  19285. Plane.prototype.flip = function () {
  19286. this.normal.scaleInPlace(-1);
  19287. this.w = -this.w;
  19288. };
  19289. // Split `polygon` by this plane if needed, then put the polygon or polygon
  19290. // fragments in the appropriate lists. Coplanar polygons go into either
  19291. // `coplanarFront` or `coplanarBack` depending on their orientation with
  19292. // respect to this plane. Polygons in front or in back of this plane go into
  19293. // either `front` or `back`.
  19294. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  19295. var COPLANAR = 0;
  19296. var FRONT = 1;
  19297. var BACK = 2;
  19298. var SPANNING = 3;
  19299. // Classify each point as well as the entire polygon into one of the above
  19300. // four classes.
  19301. var polygonType = 0;
  19302. var types = [];
  19303. for (var i = 0; i < polygon.vertices.length; i++) {
  19304. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  19305. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  19306. polygonType |= type;
  19307. types.push(type);
  19308. }
  19309. switch (polygonType) {
  19310. case COPLANAR:
  19311. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  19312. break;
  19313. case FRONT:
  19314. front.push(polygon);
  19315. break;
  19316. case BACK:
  19317. back.push(polygon);
  19318. break;
  19319. case SPANNING:
  19320. var f = [], b = [];
  19321. for (i = 0; i < polygon.vertices.length; i++) {
  19322. var j = (i + 1) % polygon.vertices.length;
  19323. var ti = types[i], tj = types[j];
  19324. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  19325. if (ti != BACK)
  19326. f.push(vi);
  19327. if (ti != FRONT)
  19328. b.push(ti != BACK ? vi.clone() : vi);
  19329. if ((ti | tj) == SPANNING) {
  19330. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  19331. var v = vi.interpolate(vj, t);
  19332. f.push(v);
  19333. b.push(v.clone());
  19334. }
  19335. }
  19336. if (f.length >= 3) {
  19337. var poly = new Polygon(f, polygon.shared);
  19338. if (poly.plane)
  19339. front.push(poly);
  19340. }
  19341. if (b.length >= 3) {
  19342. poly = new Polygon(b, polygon.shared);
  19343. if (poly.plane)
  19344. back.push(poly);
  19345. }
  19346. break;
  19347. }
  19348. };
  19349. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  19350. // point is on the plane.
  19351. Plane.EPSILON = 1e-5;
  19352. return Plane;
  19353. })();
  19354. // # class Polygon
  19355. // Represents a convex polygon. The vertices used to initialize a polygon must
  19356. // be coplanar and form a convex loop.
  19357. //
  19358. // Each convex polygon has a `shared` property, which is shared between all
  19359. // polygons that are clones of each other or were split from the same polygon.
  19360. // This can be used to define per-polygon properties (such as surface color).
  19361. var Polygon = (function () {
  19362. function Polygon(vertices, shared) {
  19363. this.vertices = vertices;
  19364. this.shared = shared;
  19365. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  19366. }
  19367. Polygon.prototype.clone = function () {
  19368. var vertices = this.vertices.map(function (v) { return v.clone(); });
  19369. return new Polygon(vertices, this.shared);
  19370. };
  19371. Polygon.prototype.flip = function () {
  19372. this.vertices.reverse().map(function (v) {
  19373. v.flip();
  19374. });
  19375. this.plane.flip();
  19376. };
  19377. return Polygon;
  19378. })();
  19379. // # class Node
  19380. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  19381. // by picking a polygon to split along. That polygon (and all other coplanar
  19382. // polygons) are added directly to that node and the other polygons are added to
  19383. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  19384. // no distinction between internal and leaf nodes.
  19385. var Node = (function () {
  19386. function Node(polygons) {
  19387. this.plane = null;
  19388. this.front = null;
  19389. this.back = null;
  19390. this.polygons = [];
  19391. if (polygons) {
  19392. this.build(polygons);
  19393. }
  19394. }
  19395. Node.prototype.clone = function () {
  19396. var node = new Node();
  19397. node.plane = this.plane && this.plane.clone();
  19398. node.front = this.front && this.front.clone();
  19399. node.back = this.back && this.back.clone();
  19400. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  19401. return node;
  19402. };
  19403. // Convert solid space to empty space and empty space to solid space.
  19404. Node.prototype.invert = function () {
  19405. for (var i = 0; i < this.polygons.length; i++) {
  19406. this.polygons[i].flip();
  19407. }
  19408. if (this.plane) {
  19409. this.plane.flip();
  19410. }
  19411. if (this.front) {
  19412. this.front.invert();
  19413. }
  19414. if (this.back) {
  19415. this.back.invert();
  19416. }
  19417. var temp = this.front;
  19418. this.front = this.back;
  19419. this.back = temp;
  19420. };
  19421. // Recursively remove all polygons in `polygons` that are inside this BSP
  19422. // tree.
  19423. Node.prototype.clipPolygons = function (polygons) {
  19424. if (!this.plane)
  19425. return polygons.slice();
  19426. var front = [], back = [];
  19427. for (var i = 0; i < polygons.length; i++) {
  19428. this.plane.splitPolygon(polygons[i], front, back, front, back);
  19429. }
  19430. if (this.front) {
  19431. front = this.front.clipPolygons(front);
  19432. }
  19433. if (this.back) {
  19434. back = this.back.clipPolygons(back);
  19435. }
  19436. else {
  19437. back = [];
  19438. }
  19439. return front.concat(back);
  19440. };
  19441. // Remove all polygons in this BSP tree that are inside the other BSP tree
  19442. // `bsp`.
  19443. Node.prototype.clipTo = function (bsp) {
  19444. this.polygons = bsp.clipPolygons(this.polygons);
  19445. if (this.front)
  19446. this.front.clipTo(bsp);
  19447. if (this.back)
  19448. this.back.clipTo(bsp);
  19449. };
  19450. // Return a list of all polygons in this BSP tree.
  19451. Node.prototype.allPolygons = function () {
  19452. var polygons = this.polygons.slice();
  19453. if (this.front)
  19454. polygons = polygons.concat(this.front.allPolygons());
  19455. if (this.back)
  19456. polygons = polygons.concat(this.back.allPolygons());
  19457. return polygons;
  19458. };
  19459. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  19460. // new polygons are filtered down to the bottom of the tree and become new
  19461. // nodes there. Each set of polygons is partitioned using the first polygon
  19462. // (no heuristic is used to pick a good split).
  19463. Node.prototype.build = function (polygons) {
  19464. if (!polygons.length)
  19465. return;
  19466. if (!this.plane)
  19467. this.plane = polygons[0].plane.clone();
  19468. var front = [], back = [];
  19469. for (var i = 0; i < polygons.length; i++) {
  19470. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  19471. }
  19472. if (front.length) {
  19473. if (!this.front)
  19474. this.front = new Node();
  19475. this.front.build(front);
  19476. }
  19477. if (back.length) {
  19478. if (!this.back)
  19479. this.back = new Node();
  19480. this.back.build(back);
  19481. }
  19482. };
  19483. return Node;
  19484. })();
  19485. var CSG = (function () {
  19486. function CSG() {
  19487. this.polygons = new Array();
  19488. }
  19489. // Convert BABYLON.Mesh to BABYLON.CSG
  19490. CSG.FromMesh = function (mesh) {
  19491. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  19492. if (mesh instanceof BABYLON.Mesh) {
  19493. mesh.computeWorldMatrix(true);
  19494. var matrix = mesh.getWorldMatrix();
  19495. var meshPosition = mesh.position.clone();
  19496. var meshRotation = mesh.rotation.clone();
  19497. var meshScaling = mesh.scaling.clone();
  19498. }
  19499. else {
  19500. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  19501. }
  19502. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19503. var subMeshes = mesh.subMeshes;
  19504. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  19505. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  19506. vertices = [];
  19507. for (var j = 0; j < 3; j++) {
  19508. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  19509. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  19510. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  19511. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  19512. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  19513. vertex = new Vertex(position, normal, uv);
  19514. vertices.push(vertex);
  19515. }
  19516. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  19517. // To handle the case of degenerated triangle
  19518. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  19519. if (polygon.plane)
  19520. polygons.push(polygon);
  19521. }
  19522. }
  19523. var csg = CSG.FromPolygons(polygons);
  19524. csg.matrix = matrix;
  19525. csg.position = meshPosition;
  19526. csg.rotation = meshRotation;
  19527. csg.scaling = meshScaling;
  19528. currentCSGMeshId++;
  19529. return csg;
  19530. };
  19531. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  19532. CSG.FromPolygons = function (polygons) {
  19533. var csg = new BABYLON.CSG();
  19534. csg.polygons = polygons;
  19535. return csg;
  19536. };
  19537. CSG.prototype.clone = function () {
  19538. var csg = new BABYLON.CSG();
  19539. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  19540. csg.copyTransformAttributes(this);
  19541. return csg;
  19542. };
  19543. CSG.prototype.toPolygons = function () {
  19544. return this.polygons;
  19545. };
  19546. CSG.prototype.union = function (csg) {
  19547. var a = new Node(this.clone().polygons);
  19548. var b = new Node(csg.clone().polygons);
  19549. a.clipTo(b);
  19550. b.clipTo(a);
  19551. b.invert();
  19552. b.clipTo(a);
  19553. b.invert();
  19554. a.build(b.allPolygons());
  19555. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19556. };
  19557. CSG.prototype.unionInPlace = function (csg) {
  19558. var a = new Node(this.polygons);
  19559. var b = new Node(csg.polygons);
  19560. a.clipTo(b);
  19561. b.clipTo(a);
  19562. b.invert();
  19563. b.clipTo(a);
  19564. b.invert();
  19565. a.build(b.allPolygons());
  19566. this.polygons = a.allPolygons();
  19567. };
  19568. CSG.prototype.subtract = function (csg) {
  19569. var a = new Node(this.clone().polygons);
  19570. var b = new Node(csg.clone().polygons);
  19571. a.invert();
  19572. a.clipTo(b);
  19573. b.clipTo(a);
  19574. b.invert();
  19575. b.clipTo(a);
  19576. b.invert();
  19577. a.build(b.allPolygons());
  19578. a.invert();
  19579. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19580. };
  19581. CSG.prototype.subtractInPlace = function (csg) {
  19582. var a = new Node(this.polygons);
  19583. var b = new Node(csg.polygons);
  19584. a.invert();
  19585. a.clipTo(b);
  19586. b.clipTo(a);
  19587. b.invert();
  19588. b.clipTo(a);
  19589. b.invert();
  19590. a.build(b.allPolygons());
  19591. a.invert();
  19592. this.polygons = a.allPolygons();
  19593. };
  19594. CSG.prototype.intersect = function (csg) {
  19595. var a = new Node(this.clone().polygons);
  19596. var b = new Node(csg.clone().polygons);
  19597. a.invert();
  19598. b.clipTo(a);
  19599. b.invert();
  19600. a.clipTo(b);
  19601. b.clipTo(a);
  19602. a.build(b.allPolygons());
  19603. a.invert();
  19604. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19605. };
  19606. CSG.prototype.intersectInPlace = function (csg) {
  19607. var a = new Node(this.polygons);
  19608. var b = new Node(csg.polygons);
  19609. a.invert();
  19610. b.clipTo(a);
  19611. b.invert();
  19612. a.clipTo(b);
  19613. b.clipTo(a);
  19614. a.build(b.allPolygons());
  19615. a.invert();
  19616. this.polygons = a.allPolygons();
  19617. };
  19618. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  19619. // not modified.
  19620. CSG.prototype.inverse = function () {
  19621. var csg = this.clone();
  19622. csg.inverseInPlace();
  19623. return csg;
  19624. };
  19625. CSG.prototype.inverseInPlace = function () {
  19626. this.polygons.map(function (p) {
  19627. p.flip();
  19628. });
  19629. };
  19630. // This is used to keep meshes transformations so they can be restored
  19631. // when we build back a Babylon Mesh
  19632. // NB : All CSG operations are performed in world coordinates
  19633. CSG.prototype.copyTransformAttributes = function (csg) {
  19634. this.matrix = csg.matrix;
  19635. this.position = csg.position;
  19636. this.rotation = csg.rotation;
  19637. this.scaling = csg.scaling;
  19638. return this;
  19639. };
  19640. // Build Raw mesh from CSG
  19641. // Coordinates here are in world space
  19642. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  19643. var matrix = this.matrix.clone();
  19644. matrix.invert();
  19645. 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;
  19646. if (keepSubMeshes) {
  19647. // Sort Polygons, since subMeshes are indices range
  19648. polygons.sort(function (a, b) {
  19649. if (a.shared.meshId === b.shared.meshId) {
  19650. return a.shared.subMeshId - b.shared.subMeshId;
  19651. }
  19652. else {
  19653. return a.shared.meshId - b.shared.meshId;
  19654. }
  19655. });
  19656. }
  19657. for (var i = 0, il = polygons.length; i < il; i++) {
  19658. polygon = polygons[i];
  19659. // Building SubMeshes
  19660. if (!subMesh_dict[polygon.shared.meshId]) {
  19661. subMesh_dict[polygon.shared.meshId] = {};
  19662. }
  19663. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  19664. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  19665. indexStart: +Infinity,
  19666. indexEnd: -Infinity,
  19667. materialIndex: polygon.shared.materialIndex
  19668. };
  19669. }
  19670. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  19671. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  19672. polygonIndices[0] = 0;
  19673. polygonIndices[1] = j - 1;
  19674. polygonIndices[2] = j;
  19675. for (var k = 0; k < 3; k++) {
  19676. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  19677. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  19678. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  19679. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  19680. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  19681. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  19682. // Check if 2 points can be merged
  19683. 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)) {
  19684. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  19685. uvs.push(uv.x, uv.y);
  19686. normals.push(normal.x, normal.y, normal.z);
  19687. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  19688. }
  19689. indices.push(vertex_idx);
  19690. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  19691. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  19692. currentIndex++;
  19693. }
  19694. }
  19695. }
  19696. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  19697. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19698. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  19699. mesh.setIndices(indices);
  19700. if (keepSubMeshes) {
  19701. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  19702. var materialIndexOffset = 0, materialMaxIndex;
  19703. mesh.subMeshes.length = 0;
  19704. for (var m in subMesh_dict) {
  19705. materialMaxIndex = -1;
  19706. for (var sm in subMesh_dict[m]) {
  19707. subMesh_obj = subMesh_dict[m][sm];
  19708. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  19709. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  19710. }
  19711. materialIndexOffset += ++materialMaxIndex;
  19712. }
  19713. }
  19714. return mesh;
  19715. };
  19716. // Build Mesh from CSG taking material and transforms into account
  19717. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  19718. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  19719. mesh.material = material;
  19720. mesh.position.copyFrom(this.position);
  19721. mesh.rotation.copyFrom(this.rotation);
  19722. mesh.scaling.copyFrom(this.scaling);
  19723. mesh.computeWorldMatrix(true);
  19724. return mesh;
  19725. };
  19726. return CSG;
  19727. })();
  19728. BABYLON.CSG = CSG;
  19729. })(BABYLON || (BABYLON = {}));
  19730. //# sourceMappingURL=babylon.csg.js.map
  19731. var BABYLON;
  19732. (function (BABYLON) {
  19733. var OculusDistortionCorrectionPostProcess = (function (_super) {
  19734. __extends(OculusDistortionCorrectionPostProcess, _super);
  19735. //ANY
  19736. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  19737. var _this = this;
  19738. _super.call(this, name, "oculusDistortionCorrection", [
  19739. 'LensCenter',
  19740. 'Scale',
  19741. 'ScaleIn',
  19742. 'HmdWarpParam'
  19743. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  19744. this._isRightEye = isRightEye;
  19745. this._distortionFactors = cameraSettings.DistortionK;
  19746. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  19747. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  19748. this.onSizeChanged = function () {
  19749. _this.aspectRatio = _this.width * .5 / _this.height;
  19750. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  19751. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  19752. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  19753. };
  19754. this.onApply = function (effect) {
  19755. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  19756. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  19757. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  19758. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  19759. };
  19760. }
  19761. return OculusDistortionCorrectionPostProcess;
  19762. })(BABYLON.PostProcess);
  19763. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  19764. })(BABYLON || (BABYLON = {}));
  19765. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  19766. // 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
  19767. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  19768. var BABYLON;
  19769. (function (BABYLON) {
  19770. (function (JoystickAxis) {
  19771. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  19772. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  19773. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  19774. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  19775. var JoystickAxis = BABYLON.JoystickAxis;
  19776. var VirtualJoystick = (function () {
  19777. function VirtualJoystick(leftJoystick) {
  19778. var _this = this;
  19779. if (leftJoystick) {
  19780. this._leftJoystick = true;
  19781. }
  19782. else {
  19783. this._leftJoystick = false;
  19784. }
  19785. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  19786. VirtualJoystick._globalJoystickIndex++;
  19787. // By default left & right arrow keys are moving the X
  19788. // and up & down keys are moving the Y
  19789. this._axisTargetedByLeftAndRight = 0 /* X */;
  19790. this._axisTargetedByUpAndDown = 1 /* Y */;
  19791. this.reverseLeftRight = false;
  19792. this.reverseUpDown = false;
  19793. // collections of pointers
  19794. this._touches = new BABYLON.VirtualJoystick.Collection();
  19795. this.deltaPosition = BABYLON.Vector3.Zero();
  19796. this._joystickSensibility = 25;
  19797. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19798. this._rotationSpeed = 25;
  19799. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  19800. this._rotateOnAxisRelativeToMesh = false;
  19801. // injecting a canvas element on top of the canvas 3D game
  19802. if (!VirtualJoystick.vjCanvas) {
  19803. window.addEventListener("resize", function () {
  19804. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19805. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19806. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  19807. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  19808. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  19809. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  19810. }, false);
  19811. VirtualJoystick.vjCanvas = document.createElement("canvas");
  19812. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19813. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19814. VirtualJoystick.vjCanvas.width = window.innerWidth;
  19815. VirtualJoystick.vjCanvas.height = window.innerHeight;
  19816. VirtualJoystick.vjCanvas.style.width = "100%";
  19817. VirtualJoystick.vjCanvas.style.height = "100%";
  19818. VirtualJoystick.vjCanvas.style.position = "absolute";
  19819. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  19820. VirtualJoystick.vjCanvas.style.top = "0px";
  19821. VirtualJoystick.vjCanvas.style.left = "0px";
  19822. VirtualJoystick.vjCanvas.style.zIndex = "5";
  19823. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  19824. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  19825. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  19826. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19827. document.body.appendChild(VirtualJoystick.vjCanvas);
  19828. }
  19829. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  19830. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  19831. this.pressed = false;
  19832. // default joystick color
  19833. this._joystickColor = "cyan";
  19834. this._joystickPointerID = -1;
  19835. // current joystick position
  19836. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  19837. // origin joystick position
  19838. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  19839. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  19840. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  19841. _this._onPointerDown(evt);
  19842. }, false);
  19843. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  19844. _this._onPointerMove(evt);
  19845. }, false);
  19846. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  19847. _this._onPointerUp(evt);
  19848. }, false);
  19849. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  19850. _this._onPointerUp(evt);
  19851. }, false);
  19852. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  19853. evt.preventDefault(); // Disables system menu
  19854. }, false);
  19855. requestAnimationFrame(function () {
  19856. _this._drawVirtualJoystick();
  19857. });
  19858. }
  19859. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  19860. this._joystickSensibility = newJoystickSensibility;
  19861. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19862. };
  19863. VirtualJoystick.prototype._onPointerDown = function (e) {
  19864. var positionOnScreenCondition;
  19865. e.preventDefault();
  19866. if (this._leftJoystick === true) {
  19867. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  19868. }
  19869. else {
  19870. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  19871. }
  19872. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  19873. // First contact will be dedicated to the virtual joystick
  19874. this._joystickPointerID = e.pointerId;
  19875. this._joystickPointerStartPos.x = e.clientX;
  19876. this._joystickPointerStartPos.y = e.clientY;
  19877. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  19878. this._deltaJoystickVector.x = 0;
  19879. this._deltaJoystickVector.y = 0;
  19880. this.pressed = true;
  19881. this._touches.add(e.pointerId.toString(), e);
  19882. }
  19883. else {
  19884. // You can only trigger the action buttons with a joystick declared
  19885. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  19886. this._action();
  19887. this._touches.add(e.pointerId.toString(), e);
  19888. }
  19889. }
  19890. };
  19891. VirtualJoystick.prototype._onPointerMove = function (e) {
  19892. // If the current pointer is the one associated to the joystick (first touch contact)
  19893. if (this._joystickPointerID == e.pointerId) {
  19894. this._joystickPointerPos.x = e.clientX;
  19895. this._joystickPointerPos.y = e.clientY;
  19896. this._deltaJoystickVector = this._joystickPointerPos.clone();
  19897. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  19898. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  19899. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  19900. switch (this._axisTargetedByLeftAndRight) {
  19901. case 0 /* X */:
  19902. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  19903. break;
  19904. case 1 /* Y */:
  19905. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  19906. break;
  19907. case 2 /* Z */:
  19908. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  19909. break;
  19910. }
  19911. var directionUpDown = this.reverseUpDown ? 1 : -1;
  19912. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  19913. switch (this._axisTargetedByUpAndDown) {
  19914. case 0 /* X */:
  19915. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  19916. break;
  19917. case 1 /* Y */:
  19918. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  19919. break;
  19920. case 2 /* Z */:
  19921. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  19922. break;
  19923. }
  19924. }
  19925. else {
  19926. if (this._touches.item(e.pointerId.toString())) {
  19927. this._touches.item(e.pointerId.toString()).x = e.clientX;
  19928. this._touches.item(e.pointerId.toString()).y = e.clientY;
  19929. }
  19930. }
  19931. };
  19932. VirtualJoystick.prototype._onPointerUp = function (e) {
  19933. this._clearCanvas();
  19934. if (this._joystickPointerID == e.pointerId) {
  19935. this._joystickPointerID = -1;
  19936. this.pressed = false;
  19937. }
  19938. this._deltaJoystickVector.x = 0;
  19939. this._deltaJoystickVector.y = 0;
  19940. this._touches.remove(e.pointerId.toString());
  19941. };
  19942. /**
  19943. * Change the color of the virtual joystick
  19944. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  19945. */
  19946. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  19947. this._joystickColor = newColor;
  19948. };
  19949. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  19950. this._action = action;
  19951. };
  19952. // Define which axis you'd like to control for left & right
  19953. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  19954. switch (axis) {
  19955. case 0 /* X */:
  19956. case 1 /* Y */:
  19957. case 2 /* Z */:
  19958. this._axisTargetedByLeftAndRight = axis;
  19959. break;
  19960. default:
  19961. this._axisTargetedByLeftAndRight = 0 /* X */;
  19962. break;
  19963. }
  19964. };
  19965. // Define which axis you'd like to control for up & down
  19966. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  19967. switch (axis) {
  19968. case 0 /* X */:
  19969. case 1 /* Y */:
  19970. case 2 /* Z */:
  19971. this._axisTargetedByUpAndDown = axis;
  19972. break;
  19973. default:
  19974. this._axisTargetedByUpAndDown = 1 /* Y */;
  19975. break;
  19976. }
  19977. };
  19978. VirtualJoystick.prototype._clearCanvas = function () {
  19979. if (this._leftJoystick) {
  19980. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  19981. }
  19982. else {
  19983. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  19984. }
  19985. };
  19986. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  19987. var _this = this;
  19988. if (this.pressed) {
  19989. this._clearCanvas();
  19990. this._touches.forEach(function (touch) {
  19991. if (touch.pointerId === _this._joystickPointerID) {
  19992. VirtualJoystick.vjCanvasContext.beginPath();
  19993. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19994. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19995. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  19996. VirtualJoystick.vjCanvasContext.stroke();
  19997. VirtualJoystick.vjCanvasContext.beginPath();
  19998. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19999. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20000. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  20001. VirtualJoystick.vjCanvasContext.stroke();
  20002. VirtualJoystick.vjCanvasContext.beginPath();
  20003. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20004. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  20005. VirtualJoystick.vjCanvasContext.stroke();
  20006. }
  20007. else {
  20008. VirtualJoystick.vjCanvasContext.beginPath();
  20009. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  20010. VirtualJoystick.vjCanvasContext.beginPath();
  20011. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  20012. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20013. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  20014. VirtualJoystick.vjCanvasContext.stroke();
  20015. }
  20016. ;
  20017. });
  20018. }
  20019. requestAnimationFrame(function () {
  20020. _this._drawVirtualJoystick();
  20021. });
  20022. };
  20023. VirtualJoystick.prototype.releaseCanvas = function () {
  20024. if (VirtualJoystick.vjCanvas) {
  20025. document.body.removeChild(VirtualJoystick.vjCanvas);
  20026. VirtualJoystick.vjCanvas = null;
  20027. }
  20028. };
  20029. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  20030. VirtualJoystick._globalJoystickIndex = 0;
  20031. return VirtualJoystick;
  20032. })();
  20033. BABYLON.VirtualJoystick = VirtualJoystick;
  20034. })(BABYLON || (BABYLON = {}));
  20035. var BABYLON;
  20036. (function (BABYLON) {
  20037. var VirtualJoystick;
  20038. (function (VirtualJoystick) {
  20039. var Collection = (function () {
  20040. function Collection() {
  20041. this._count = 0;
  20042. this._collection = new Array();
  20043. }
  20044. Collection.prototype.Count = function () {
  20045. return this._count;
  20046. };
  20047. Collection.prototype.add = function (key, item) {
  20048. if (this._collection[key] != undefined) {
  20049. return undefined;
  20050. }
  20051. this._collection[key] = item;
  20052. return ++this._count;
  20053. };
  20054. Collection.prototype.remove = function (key) {
  20055. if (this._collection[key] == undefined) {
  20056. return undefined;
  20057. }
  20058. delete this._collection[key];
  20059. return --this._count;
  20060. };
  20061. Collection.prototype.item = function (key) {
  20062. return this._collection[key];
  20063. };
  20064. Collection.prototype.forEach = function (block) {
  20065. var key;
  20066. for (key in this._collection) {
  20067. if (this._collection.hasOwnProperty(key)) {
  20068. block(this._collection[key]);
  20069. }
  20070. }
  20071. };
  20072. return Collection;
  20073. })();
  20074. VirtualJoystick.Collection = Collection;
  20075. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20076. })(BABYLON || (BABYLON = {}));
  20077. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20078. var BABYLON;
  20079. (function (BABYLON) {
  20080. var OculusRiftDevKit2013_Metric = {
  20081. HResolution: 1280,
  20082. VResolution: 800,
  20083. HScreenSize: 0.149759993,
  20084. VScreenSize: 0.0935999975,
  20085. VScreenCenter: 0.0467999987,
  20086. EyeToScreenDistance: 0.0410000011,
  20087. LensSeparationDistance: 0.0635000020,
  20088. InterpupillaryDistance: 0.0640000030,
  20089. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20090. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20091. PostProcessScaleFactor: 1.714605507808412,
  20092. LensCenterOffset: 0.151976421
  20093. };
  20094. var _OculusInnerCamera = (function (_super) {
  20095. __extends(_OculusInnerCamera, _super);
  20096. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20097. _super.call(this, name, position, scene);
  20098. this._workMatrix = new BABYLON.Matrix();
  20099. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20100. // Constants
  20101. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20102. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20103. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20104. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20105. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20106. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20107. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20108. // Postprocess
  20109. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20110. }
  20111. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20112. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20113. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20114. return this._projectionMatrix;
  20115. };
  20116. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20117. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20118. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20119. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20120. // Computing target and final matrix
  20121. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20122. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20123. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20124. return this._viewMatrix;
  20125. };
  20126. return _OculusInnerCamera;
  20127. })(BABYLON.FreeCamera);
  20128. var OculusCamera = (function (_super) {
  20129. __extends(OculusCamera, _super);
  20130. function OculusCamera(name, position, scene) {
  20131. _super.call(this, name, position, scene);
  20132. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20133. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20134. this.subCameras.push(this._leftCamera);
  20135. this.subCameras.push(this._rightCamera);
  20136. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20137. }
  20138. OculusCamera.prototype._update = function () {
  20139. this._leftCamera.position.copyFrom(this.position);
  20140. this._rightCamera.position.copyFrom(this.position);
  20141. this._updateCamera(this._leftCamera);
  20142. this._updateCamera(this._rightCamera);
  20143. _super.prototype._update.call(this);
  20144. };
  20145. OculusCamera.prototype._updateCamera = function (camera) {
  20146. camera.minZ = this.minZ;
  20147. camera.maxZ = this.maxZ;
  20148. camera.rotation.x = this.rotation.x;
  20149. camera.rotation.y = this.rotation.y;
  20150. camera.rotation.z = this.rotation.z;
  20151. };
  20152. // Oculus events
  20153. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20154. var yaw = evt.alpha / 180 * Math.PI;
  20155. var pitch = evt.beta / 180 * Math.PI;
  20156. var roll = evt.gamma / 180 * Math.PI;
  20157. if (!this._offsetOrientation) {
  20158. this._offsetOrientation = {
  20159. yaw: yaw,
  20160. pitch: pitch,
  20161. roll: roll
  20162. };
  20163. return;
  20164. }
  20165. else {
  20166. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20167. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20168. this.rotation.z += this._offsetOrientation.roll - roll;
  20169. this._offsetOrientation.yaw = yaw;
  20170. this._offsetOrientation.pitch = pitch;
  20171. this._offsetOrientation.roll = roll;
  20172. }
  20173. };
  20174. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  20175. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20176. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20177. };
  20178. OculusCamera.prototype.detachControl = function (element) {
  20179. _super.prototype.detachControl.call(this, element);
  20180. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20181. };
  20182. return OculusCamera;
  20183. })(BABYLON.FreeCamera);
  20184. BABYLON.OculusCamera = OculusCamera;
  20185. })(BABYLON || (BABYLON = {}));
  20186. //# sourceMappingURL=babylon.oculusCamera.js.map
  20187. var BABYLON;
  20188. (function (BABYLON) {
  20189. var OculusRiftDevKit2013_Metric = {
  20190. HResolution: 1280,
  20191. VResolution: 800,
  20192. HScreenSize: 0.149759993,
  20193. VScreenSize: 0.0935999975,
  20194. VScreenCenter: 0.0467999987,
  20195. EyeToScreenDistance: 0.0410000011,
  20196. LensSeparationDistance: 0.0635000020,
  20197. InterpupillaryDistance: 0.0640000030,
  20198. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20199. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20200. PostProcessScaleFactor: 1.714605507808412,
  20201. LensCenterOffset: 0.151976421
  20202. };
  20203. var _OculusInnerGamepadCamera = (function (_super) {
  20204. __extends(_OculusInnerGamepadCamera, _super);
  20205. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  20206. _super.call(this, name, position, scene);
  20207. this._workMatrix = new BABYLON.Matrix();
  20208. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20209. // Constants
  20210. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20211. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20212. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20213. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20214. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20215. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20216. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20217. // Postprocess
  20218. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20219. }
  20220. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  20221. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20222. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20223. return this._projectionMatrix;
  20224. };
  20225. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  20226. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20227. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20228. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20229. // Computing target and final matrix
  20230. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20231. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20232. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20233. return this._viewMatrix;
  20234. };
  20235. return _OculusInnerGamepadCamera;
  20236. })(BABYLON.FreeCamera);
  20237. var OculusGamepadCamera = (function (_super) {
  20238. __extends(OculusGamepadCamera, _super);
  20239. function OculusGamepadCamera(name, position, scene) {
  20240. var _this = this;
  20241. _super.call(this, name, position, scene);
  20242. this.angularSensibility = 200;
  20243. this.moveSensibility = 75;
  20244. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  20245. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  20246. this.subCameras.push(this._leftCamera);
  20247. this.subCameras.push(this._rightCamera);
  20248. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20249. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20250. _this._onNewGameConnected(gamepad);
  20251. });
  20252. }
  20253. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20254. // Only the first gamepad can control the camera
  20255. if (gamepad.index === 0) {
  20256. this._gamepad = gamepad;
  20257. }
  20258. };
  20259. OculusGamepadCamera.prototype._update = function () {
  20260. this._leftCamera.position.copyFrom(this.position);
  20261. this._rightCamera.position.copyFrom(this.position);
  20262. this._updateCamera(this._leftCamera);
  20263. this._updateCamera(this._rightCamera);
  20264. _super.prototype._update.call(this);
  20265. };
  20266. OculusGamepadCamera.prototype._checkInputs = function () {
  20267. if (!this._gamepad) {
  20268. return;
  20269. }
  20270. var LSValues = this._gamepad.leftStick;
  20271. var normalizedLX = LSValues.x / this.moveSensibility;
  20272. var normalizedLY = LSValues.y / this.moveSensibility;
  20273. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20274. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20275. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20276. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20277. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20278. };
  20279. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  20280. camera.minZ = this.minZ;
  20281. camera.maxZ = this.maxZ;
  20282. camera.rotation.x = this.rotation.x;
  20283. camera.rotation.y = this.rotation.y;
  20284. camera.rotation.z = this.rotation.z;
  20285. };
  20286. // Oculus events
  20287. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  20288. var yaw = evt.alpha / 180 * Math.PI;
  20289. var pitch = evt.beta / 180 * Math.PI;
  20290. var roll = evt.gamma / 180 * Math.PI;
  20291. if (!this._offsetOrientation) {
  20292. this._offsetOrientation = {
  20293. yaw: yaw,
  20294. pitch: pitch,
  20295. roll: roll
  20296. };
  20297. return;
  20298. }
  20299. else {
  20300. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20301. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20302. this.rotation.z += this._offsetOrientation.roll - roll;
  20303. this._offsetOrientation.yaw = yaw;
  20304. this._offsetOrientation.pitch = pitch;
  20305. this._offsetOrientation.roll = roll;
  20306. }
  20307. };
  20308. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  20309. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20310. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20311. };
  20312. OculusGamepadCamera.prototype.detachControl = function (element) {
  20313. _super.prototype.detachControl.call(this, element);
  20314. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20315. };
  20316. OculusGamepadCamera.prototype.dispose = function () {
  20317. this._gamepads.dispose();
  20318. _super.prototype.dispose.call(this);
  20319. };
  20320. return OculusGamepadCamera;
  20321. })(BABYLON.FreeCamera);
  20322. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  20323. })(BABYLON || (BABYLON = {}));
  20324. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  20325. var BABYLON;
  20326. (function (BABYLON) {
  20327. // We're mainly based on the logic defined into the FreeCamera code
  20328. var VirtualJoysticksCamera = (function (_super) {
  20329. __extends(VirtualJoysticksCamera, _super);
  20330. function VirtualJoysticksCamera(name, position, scene) {
  20331. _super.call(this, name, position, scene);
  20332. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  20333. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  20334. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  20335. this._leftjoystick.setJoystickSensibility(0.15);
  20336. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  20337. this._rightjoystick.setAxisForUpDown(0 /* X */);
  20338. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  20339. this._rightjoystick.reverseUpDown = true;
  20340. this._rightjoystick.setJoystickSensibility(0.05);
  20341. this._rightjoystick.setJoystickColor("yellow");
  20342. }
  20343. VirtualJoysticksCamera.prototype._checkInputs = function () {
  20344. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20345. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  20346. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20347. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  20348. if (!this._leftjoystick.pressed) {
  20349. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  20350. }
  20351. if (!this._rightjoystick.pressed) {
  20352. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  20353. }
  20354. };
  20355. VirtualJoysticksCamera.prototype.dispose = function () {
  20356. this._leftjoystick.releaseCanvas();
  20357. _super.prototype.dispose.call(this);
  20358. };
  20359. return VirtualJoysticksCamera;
  20360. })(BABYLON.FreeCamera);
  20361. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  20362. })(BABYLON || (BABYLON = {}));
  20363. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  20364. var BABYLON;
  20365. (function (BABYLON) {
  20366. var ShaderMaterial = (function (_super) {
  20367. __extends(ShaderMaterial, _super);
  20368. function ShaderMaterial(name, scene, shaderPath, options) {
  20369. _super.call(this, name, scene);
  20370. this._textures = new Array();
  20371. this._floats = new Array();
  20372. this._floatsArrays = {};
  20373. this._colors3 = new Array();
  20374. this._colors4 = new Array();
  20375. this._vectors2 = new Array();
  20376. this._vectors3 = new Array();
  20377. this._matrices = new Array();
  20378. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  20379. this._shaderPath = shaderPath;
  20380. options.needAlphaBlending = options.needAlphaBlending || false;
  20381. options.needAlphaTesting = options.needAlphaTesting || false;
  20382. options.attributes = options.attributes || ["position", "normal", "uv"];
  20383. options.uniforms = options.uniforms || ["worldViewProjection"];
  20384. options.samplers = options.samplers || [];
  20385. this._options = options;
  20386. }
  20387. ShaderMaterial.prototype.needAlphaBlending = function () {
  20388. return this._options.needAlphaBlending;
  20389. };
  20390. ShaderMaterial.prototype.needAlphaTesting = function () {
  20391. return this._options.needAlphaTesting;
  20392. };
  20393. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  20394. if (this._options.uniforms.indexOf(uniformName) === -1) {
  20395. this._options.uniforms.push(uniformName);
  20396. }
  20397. };
  20398. ShaderMaterial.prototype.setTexture = function (name, texture) {
  20399. if (this._options.samplers.indexOf(name) === -1) {
  20400. this._options.samplers.push(name);
  20401. }
  20402. this._textures[name] = texture;
  20403. return this;
  20404. };
  20405. ShaderMaterial.prototype.setFloat = function (name, value) {
  20406. this._checkUniform(name);
  20407. this._floats[name] = value;
  20408. return this;
  20409. };
  20410. ShaderMaterial.prototype.setFloats = function (name, value) {
  20411. this._checkUniform(name);
  20412. this._floatsArrays[name] = value;
  20413. return this;
  20414. };
  20415. ShaderMaterial.prototype.setColor3 = function (name, value) {
  20416. this._checkUniform(name);
  20417. this._colors3[name] = value;
  20418. return this;
  20419. };
  20420. ShaderMaterial.prototype.setColor4 = function (name, value) {
  20421. this._checkUniform(name);
  20422. this._colors4[name] = value;
  20423. return this;
  20424. };
  20425. ShaderMaterial.prototype.setVector2 = function (name, value) {
  20426. this._checkUniform(name);
  20427. this._vectors2[name] = value;
  20428. return this;
  20429. };
  20430. ShaderMaterial.prototype.setVector3 = function (name, value) {
  20431. this._checkUniform(name);
  20432. this._vectors3[name] = value;
  20433. return this;
  20434. };
  20435. ShaderMaterial.prototype.setMatrix = function (name, value) {
  20436. this._checkUniform(name);
  20437. this._matrices[name] = value;
  20438. return this;
  20439. };
  20440. ShaderMaterial.prototype.isReady = function () {
  20441. var scene = this.getScene();
  20442. var engine = scene.getEngine();
  20443. if (!this.checkReadyOnEveryCall) {
  20444. if (this._renderId === scene.getRenderId()) {
  20445. return true;
  20446. }
  20447. }
  20448. var previousEffect = this._effect;
  20449. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  20450. if (!this._effect.isReady()) {
  20451. return false;
  20452. }
  20453. if (previousEffect !== this._effect) {
  20454. scene.resetCachedMaterial();
  20455. }
  20456. this._renderId = scene.getRenderId();
  20457. return true;
  20458. };
  20459. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20460. var scene = this.getScene();
  20461. if (this._options.uniforms.indexOf("world") !== -1) {
  20462. this._effect.setMatrix("world", world);
  20463. }
  20464. if (this._options.uniforms.indexOf("worldView") !== -1) {
  20465. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  20466. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  20467. }
  20468. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  20469. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  20470. }
  20471. };
  20472. ShaderMaterial.prototype.bind = function (world) {
  20473. // Std values
  20474. this.bindOnlyWorldMatrix(world);
  20475. if (this.getScene().getCachedMaterial() !== this) {
  20476. if (this._options.uniforms.indexOf("view") !== -1) {
  20477. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  20478. }
  20479. if (this._options.uniforms.indexOf("projection") !== -1) {
  20480. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  20481. }
  20482. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  20483. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  20484. }
  20485. for (var name in this._textures) {
  20486. this._effect.setTexture(name, this._textures[name]);
  20487. }
  20488. for (name in this._floats) {
  20489. this._effect.setFloat(name, this._floats[name]);
  20490. }
  20491. for (name in this._floatsArrays) {
  20492. this._effect.setArray(name, this._floatsArrays[name]);
  20493. }
  20494. for (name in this._colors3) {
  20495. this._effect.setColor3(name, this._colors3[name]);
  20496. }
  20497. for (name in this._colors4) {
  20498. var color = this._colors4[name];
  20499. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  20500. }
  20501. for (name in this._vectors2) {
  20502. this._effect.setVector2(name, this._vectors2[name]);
  20503. }
  20504. for (name in this._vectors3) {
  20505. this._effect.setVector3(name, this._vectors3[name]);
  20506. }
  20507. for (name in this._matrices) {
  20508. this._effect.setMatrix(name, this._matrices[name]);
  20509. }
  20510. }
  20511. _super.prototype.bind.call(this, world, null);
  20512. };
  20513. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  20514. for (var name in this._textures) {
  20515. this._textures[name].dispose();
  20516. }
  20517. this._textures = [];
  20518. _super.prototype.dispose.call(this, forceDisposeEffect);
  20519. };
  20520. return ShaderMaterial;
  20521. })(BABYLON.Material);
  20522. BABYLON.ShaderMaterial = ShaderMaterial;
  20523. })(BABYLON || (BABYLON = {}));
  20524. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  20525. (function (BABYLON) {
  20526. var VertexData = (function () {
  20527. function VertexData() {
  20528. }
  20529. VertexData.prototype.set = function (data, kind) {
  20530. switch (kind) {
  20531. case BABYLON.VertexBuffer.PositionKind:
  20532. this.positions = data;
  20533. break;
  20534. case BABYLON.VertexBuffer.NormalKind:
  20535. this.normals = data;
  20536. break;
  20537. case BABYLON.VertexBuffer.UVKind:
  20538. this.uvs = data;
  20539. break;
  20540. case BABYLON.VertexBuffer.UV2Kind:
  20541. this.uv2s = data;
  20542. break;
  20543. case BABYLON.VertexBuffer.ColorKind:
  20544. this.colors = data;
  20545. break;
  20546. case BABYLON.VertexBuffer.MatricesIndicesKind:
  20547. this.matricesIndices = data;
  20548. break;
  20549. case BABYLON.VertexBuffer.MatricesWeightsKind:
  20550. this.matricesWeights = data;
  20551. break;
  20552. }
  20553. };
  20554. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  20555. this._applyTo(mesh, updatable);
  20556. };
  20557. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  20558. this._applyTo(geometry, updatable);
  20559. };
  20560. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  20561. this._update(mesh);
  20562. };
  20563. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  20564. this._update(geometry);
  20565. };
  20566. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  20567. if (this.positions) {
  20568. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  20569. }
  20570. if (this.normals) {
  20571. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  20572. }
  20573. if (this.uvs) {
  20574. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  20575. }
  20576. if (this.uv2s) {
  20577. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  20578. }
  20579. if (this.colors) {
  20580. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  20581. }
  20582. if (this.matricesIndices) {
  20583. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  20584. }
  20585. if (this.matricesWeights) {
  20586. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  20587. }
  20588. if (this.indices) {
  20589. meshOrGeometry.setIndices(this.indices);
  20590. }
  20591. };
  20592. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  20593. if (this.positions) {
  20594. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  20595. }
  20596. if (this.normals) {
  20597. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  20598. }
  20599. if (this.uvs) {
  20600. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  20601. }
  20602. if (this.uv2s) {
  20603. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  20604. }
  20605. if (this.colors) {
  20606. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  20607. }
  20608. if (this.matricesIndices) {
  20609. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  20610. }
  20611. if (this.matricesWeights) {
  20612. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  20613. }
  20614. if (this.indices) {
  20615. meshOrGeometry.setIndices(this.indices);
  20616. }
  20617. };
  20618. VertexData.prototype.transform = function (matrix) {
  20619. var transformed = BABYLON.Vector3.Zero();
  20620. if (this.positions) {
  20621. var position = BABYLON.Vector3.Zero();
  20622. for (var index = 0; index < this.positions.length; index += 3) {
  20623. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  20624. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  20625. this.positions[index] = transformed.x;
  20626. this.positions[index + 1] = transformed.y;
  20627. this.positions[index + 2] = transformed.z;
  20628. }
  20629. }
  20630. if (this.normals) {
  20631. var normal = BABYLON.Vector3.Zero();
  20632. for (index = 0; index < this.normals.length; index += 3) {
  20633. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  20634. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  20635. this.normals[index] = transformed.x;
  20636. this.normals[index + 1] = transformed.y;
  20637. this.normals[index + 2] = transformed.z;
  20638. }
  20639. }
  20640. };
  20641. VertexData.prototype.merge = function (other) {
  20642. if (other.indices) {
  20643. if (!this.indices) {
  20644. this.indices = [];
  20645. }
  20646. var offset = this.positions ? this.positions.length / 3 : 0;
  20647. for (var index = 0; index < other.indices.length; index++) {
  20648. this.indices.push(other.indices[index] + offset);
  20649. }
  20650. }
  20651. if (other.positions) {
  20652. if (!this.positions) {
  20653. this.positions = [];
  20654. }
  20655. for (index = 0; index < other.positions.length; index++) {
  20656. this.positions.push(other.positions[index]);
  20657. }
  20658. }
  20659. if (other.normals) {
  20660. if (!this.normals) {
  20661. this.normals = [];
  20662. }
  20663. for (index = 0; index < other.normals.length; index++) {
  20664. this.normals.push(other.normals[index]);
  20665. }
  20666. }
  20667. if (other.uvs) {
  20668. if (!this.uvs) {
  20669. this.uvs = [];
  20670. }
  20671. for (index = 0; index < other.uvs.length; index++) {
  20672. this.uvs.push(other.uvs[index]);
  20673. }
  20674. }
  20675. if (other.uv2s) {
  20676. if (!this.uv2s) {
  20677. this.uv2s = [];
  20678. }
  20679. for (index = 0; index < other.uv2s.length; index++) {
  20680. this.uv2s.push(other.uv2s[index]);
  20681. }
  20682. }
  20683. if (other.matricesIndices) {
  20684. if (!this.matricesIndices) {
  20685. this.matricesIndices = [];
  20686. }
  20687. for (index = 0; index < other.matricesIndices.length; index++) {
  20688. this.matricesIndices.push(other.matricesIndices[index]);
  20689. }
  20690. }
  20691. if (other.matricesWeights) {
  20692. if (!this.matricesWeights) {
  20693. this.matricesWeights = [];
  20694. }
  20695. for (index = 0; index < other.matricesWeights.length; index++) {
  20696. this.matricesWeights.push(other.matricesWeights[index]);
  20697. }
  20698. }
  20699. if (other.colors) {
  20700. if (!this.colors) {
  20701. this.colors = [];
  20702. }
  20703. for (index = 0; index < other.colors.length; index++) {
  20704. this.colors.push(other.colors[index]);
  20705. }
  20706. }
  20707. };
  20708. // Statics
  20709. VertexData.ExtractFromMesh = function (mesh) {
  20710. return VertexData._ExtractFrom(mesh);
  20711. };
  20712. VertexData.ExtractFromGeometry = function (geometry) {
  20713. return VertexData._ExtractFrom(geometry);
  20714. };
  20715. VertexData._ExtractFrom = function (meshOrGeometry) {
  20716. var result = new BABYLON.VertexData();
  20717. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20718. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20719. }
  20720. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20721. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20722. }
  20723. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20724. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20725. }
  20726. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20727. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  20728. }
  20729. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20730. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  20731. }
  20732. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20733. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20734. }
  20735. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20736. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20737. }
  20738. result.indices = meshOrGeometry.getIndices();
  20739. return result;
  20740. };
  20741. VertexData.CreateBox = function (size) {
  20742. var normalsSource = [
  20743. new BABYLON.Vector3(0, 0, 1),
  20744. new BABYLON.Vector3(0, 0, -1),
  20745. new BABYLON.Vector3(1, 0, 0),
  20746. new BABYLON.Vector3(-1, 0, 0),
  20747. new BABYLON.Vector3(0, 1, 0),
  20748. new BABYLON.Vector3(0, -1, 0)
  20749. ];
  20750. var indices = [];
  20751. var positions = [];
  20752. var normals = [];
  20753. var uvs = [];
  20754. size = size || 1;
  20755. for (var index = 0; index < normalsSource.length; index++) {
  20756. var normal = normalsSource[index];
  20757. // Get two vectors perpendicular to the face normal and to each other.
  20758. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  20759. var side2 = BABYLON.Vector3.Cross(normal, side1);
  20760. // Six indices (two triangles) per face.
  20761. var verticesLength = positions.length / 3;
  20762. indices.push(verticesLength);
  20763. indices.push(verticesLength + 1);
  20764. indices.push(verticesLength + 2);
  20765. indices.push(verticesLength);
  20766. indices.push(verticesLength + 2);
  20767. indices.push(verticesLength + 3);
  20768. // Four vertices per face.
  20769. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  20770. positions.push(vertex.x, vertex.y, vertex.z);
  20771. normals.push(normal.x, normal.y, normal.z);
  20772. uvs.push(1.0, 1.0);
  20773. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  20774. positions.push(vertex.x, vertex.y, vertex.z);
  20775. normals.push(normal.x, normal.y, normal.z);
  20776. uvs.push(0.0, 1.0);
  20777. vertex = normal.add(side1).add(side2).scale(size / 2);
  20778. positions.push(vertex.x, vertex.y, vertex.z);
  20779. normals.push(normal.x, normal.y, normal.z);
  20780. uvs.push(0.0, 0.0);
  20781. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  20782. positions.push(vertex.x, vertex.y, vertex.z);
  20783. normals.push(normal.x, normal.y, normal.z);
  20784. uvs.push(1.0, 0.0);
  20785. }
  20786. // Result
  20787. var vertexData = new BABYLON.VertexData();
  20788. vertexData.indices = indices;
  20789. vertexData.positions = positions;
  20790. vertexData.normals = normals;
  20791. vertexData.uvs = uvs;
  20792. return vertexData;
  20793. };
  20794. VertexData.CreateSphere = function (segments, diameter) {
  20795. segments = segments || 32;
  20796. diameter = diameter || 1;
  20797. var radius = diameter / 2;
  20798. var totalZRotationSteps = 2 + segments;
  20799. var totalYRotationSteps = 2 * totalZRotationSteps;
  20800. var indices = [];
  20801. var positions = [];
  20802. var normals = [];
  20803. var uvs = [];
  20804. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  20805. var normalizedZ = zRotationStep / totalZRotationSteps;
  20806. var angleZ = (normalizedZ * Math.PI);
  20807. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  20808. var normalizedY = yRotationStep / totalYRotationSteps;
  20809. var angleY = normalizedY * Math.PI * 2;
  20810. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  20811. var rotationY = BABYLON.Matrix.RotationY(angleY);
  20812. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  20813. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  20814. var vertex = complete.scale(radius);
  20815. var normal = BABYLON.Vector3.Normalize(vertex);
  20816. positions.push(vertex.x, vertex.y, vertex.z);
  20817. normals.push(normal.x, normal.y, normal.z);
  20818. uvs.push(normalizedZ, normalizedY);
  20819. }
  20820. if (zRotationStep > 0) {
  20821. var verticesCount = positions.length / 3;
  20822. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  20823. indices.push((firstIndex));
  20824. indices.push((firstIndex + 1));
  20825. indices.push(firstIndex + totalYRotationSteps + 1);
  20826. indices.push((firstIndex + totalYRotationSteps + 1));
  20827. indices.push((firstIndex + 1));
  20828. indices.push((firstIndex + totalYRotationSteps + 2));
  20829. }
  20830. }
  20831. }
  20832. // Result
  20833. var vertexData = new BABYLON.VertexData();
  20834. vertexData.indices = indices;
  20835. vertexData.positions = positions;
  20836. vertexData.normals = normals;
  20837. vertexData.uvs = uvs;
  20838. return vertexData;
  20839. };
  20840. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  20841. if (subdivisions === void 0) { subdivisions = 1; }
  20842. var radiusTop = diameterTop / 2;
  20843. var radiusBottom = diameterBottom / 2;
  20844. var indices = [];
  20845. var positions = [];
  20846. var normals = [];
  20847. var uvs = [];
  20848. height = height || 1;
  20849. diameterTop = diameterTop || 0.5;
  20850. diameterBottom = diameterBottom || 1;
  20851. tessellation = tessellation || 16;
  20852. subdivisions = subdivisions || 1;
  20853. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  20854. var getCircleVector = function (i) {
  20855. var angle = (i * 2.0 * Math.PI / tessellation);
  20856. var dx = Math.cos(angle);
  20857. var dz = Math.sin(angle);
  20858. return new BABYLON.Vector3(dx, 0, dz);
  20859. };
  20860. var createCylinderCap = function (isTop) {
  20861. var radius = isTop ? radiusTop : radiusBottom;
  20862. if (radius == 0) {
  20863. return;
  20864. }
  20865. var vbase = positions.length / 3;
  20866. var offset = new BABYLON.Vector3(0, height / 2, 0);
  20867. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  20868. if (!isTop) {
  20869. offset.scaleInPlace(-1);
  20870. textureScale.x = -textureScale.x;
  20871. }
  20872. for (i = 0; i < tessellation; i++) {
  20873. var circleVector = getCircleVector(i);
  20874. var position = circleVector.scale(radius).add(offset);
  20875. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  20876. positions.push(position.x, position.y, position.z);
  20877. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20878. }
  20879. for (var i = 0; i < tessellation - 2; i++) {
  20880. if (!isTop) {
  20881. indices.push(vbase);
  20882. indices.push(vbase + (i + 2) % tessellation);
  20883. indices.push(vbase + (i + 1) % tessellation);
  20884. }
  20885. else {
  20886. indices.push(vbase);
  20887. indices.push(vbase + (i + 1) % tessellation);
  20888. indices.push(vbase + (i + 2) % tessellation);
  20889. }
  20890. }
  20891. };
  20892. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  20893. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  20894. var stride = tessellation + 1;
  20895. for (var i = 0; i <= tessellation; i++) {
  20896. var circleVector = getCircleVector(i);
  20897. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  20898. var position, radius = radiusBottom;
  20899. for (var s = 0; s <= subdivisions; s++) {
  20900. // Update variables
  20901. position = circleVector.scale(radius);
  20902. position.addInPlace(base.add(offset.scale(s)));
  20903. textureCoordinate.y += 1 / subdivisions;
  20904. radius += (radiusTop - radiusBottom) / subdivisions;
  20905. // Push in arrays
  20906. positions.push(position.x, position.y, position.z);
  20907. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20908. }
  20909. }
  20910. subdivisions += 1;
  20911. for (var s = 0; s < subdivisions - 1; s++) {
  20912. for (var i = 0; i <= tessellation; i++) {
  20913. indices.push(i * subdivisions + s);
  20914. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20915. indices.push(i * subdivisions + (s + 1));
  20916. indices.push(i * subdivisions + (s + 1));
  20917. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20918. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  20919. }
  20920. }
  20921. // Create flat triangle fan caps to seal the top and bottom.
  20922. createCylinderCap(true);
  20923. createCylinderCap(false);
  20924. // Normals
  20925. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20926. // Result
  20927. var vertexData = new BABYLON.VertexData();
  20928. vertexData.indices = indices;
  20929. vertexData.positions = positions;
  20930. vertexData.normals = normals;
  20931. vertexData.uvs = uvs;
  20932. return vertexData;
  20933. };
  20934. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  20935. var indices = [];
  20936. var positions = [];
  20937. var normals = [];
  20938. var uvs = [];
  20939. diameter = diameter || 1;
  20940. thickness = thickness || 0.5;
  20941. tessellation = tessellation || 16;
  20942. var stride = tessellation + 1;
  20943. for (var i = 0; i <= tessellation; i++) {
  20944. var u = i / tessellation;
  20945. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  20946. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  20947. for (var j = 0; j <= tessellation; j++) {
  20948. var v = 1 - j / tessellation;
  20949. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  20950. var dx = Math.cos(innerAngle);
  20951. var dy = Math.sin(innerAngle);
  20952. // Create a vertex.
  20953. var normal = new BABYLON.Vector3(dx, dy, 0);
  20954. var position = normal.scale(thickness / 2);
  20955. var textureCoordinate = new BABYLON.Vector2(u, v);
  20956. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  20957. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  20958. positions.push(position.x, position.y, position.z);
  20959. normals.push(normal.x, normal.y, normal.z);
  20960. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20961. // And create indices for two triangles.
  20962. var nextI = (i + 1) % stride;
  20963. var nextJ = (j + 1) % stride;
  20964. indices.push(i * stride + j);
  20965. indices.push(i * stride + nextJ);
  20966. indices.push(nextI * stride + j);
  20967. indices.push(i * stride + nextJ);
  20968. indices.push(nextI * stride + nextJ);
  20969. indices.push(nextI * stride + j);
  20970. }
  20971. }
  20972. // Result
  20973. var vertexData = new BABYLON.VertexData();
  20974. vertexData.indices = indices;
  20975. vertexData.positions = positions;
  20976. vertexData.normals = normals;
  20977. vertexData.uvs = uvs;
  20978. return vertexData;
  20979. };
  20980. VertexData.CreateLines = function (points) {
  20981. var indices = [];
  20982. var positions = [];
  20983. for (var index = 0; index < points.length; index++) {
  20984. positions.push(points[index].x, points[index].y, points[index].z);
  20985. if (index > 0) {
  20986. indices.push(index - 1);
  20987. indices.push(index);
  20988. }
  20989. }
  20990. // Result
  20991. var vertexData = new BABYLON.VertexData();
  20992. vertexData.indices = indices;
  20993. vertexData.positions = positions;
  20994. return vertexData;
  20995. };
  20996. VertexData.CreateGround = function (width, height, subdivisions) {
  20997. var indices = [];
  20998. var positions = [];
  20999. var normals = [];
  21000. var uvs = [];
  21001. var row, col;
  21002. width = width || 1;
  21003. height = height || 1;
  21004. subdivisions = subdivisions || 1;
  21005. for (row = 0; row <= subdivisions; row++) {
  21006. for (col = 0; col <= subdivisions; col++) {
  21007. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21008. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21009. positions.push(position.x, position.y, position.z);
  21010. normals.push(normal.x, normal.y, normal.z);
  21011. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21012. }
  21013. }
  21014. for (row = 0; row < subdivisions; row++) {
  21015. for (col = 0; col < subdivisions; col++) {
  21016. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21017. indices.push(col + 1 + row * (subdivisions + 1));
  21018. indices.push(col + row * (subdivisions + 1));
  21019. indices.push(col + (row + 1) * (subdivisions + 1));
  21020. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21021. indices.push(col + row * (subdivisions + 1));
  21022. }
  21023. }
  21024. // Result
  21025. var vertexData = new BABYLON.VertexData();
  21026. vertexData.indices = indices;
  21027. vertexData.positions = positions;
  21028. vertexData.normals = normals;
  21029. vertexData.uvs = uvs;
  21030. return vertexData;
  21031. };
  21032. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  21033. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  21034. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  21035. var indices = [];
  21036. var positions = [];
  21037. var normals = [];
  21038. var uvs = [];
  21039. var row, col, tileRow, tileCol;
  21040. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  21041. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  21042. precision.w = (precision.w < 1) ? 1 : precision.w;
  21043. precision.h = (precision.h < 1) ? 1 : precision.h;
  21044. var tileSize = {
  21045. 'w': (xmax - xmin) / subdivisions.w,
  21046. 'h': (zmax - zmin) / subdivisions.h
  21047. };
  21048. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  21049. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  21050. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  21051. }
  21052. }
  21053. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  21054. // Indices
  21055. var base = positions.length / 3;
  21056. var rowLength = precision.w + 1;
  21057. for (row = 0; row < precision.h; row++) {
  21058. for (col = 0; col < precision.w; col++) {
  21059. var square = [
  21060. base + col + row * rowLength,
  21061. base + (col + 1) + row * rowLength,
  21062. base + (col + 1) + (row + 1) * rowLength,
  21063. base + col + (row + 1) * rowLength
  21064. ];
  21065. indices.push(square[1]);
  21066. indices.push(square[2]);
  21067. indices.push(square[3]);
  21068. indices.push(square[0]);
  21069. indices.push(square[1]);
  21070. indices.push(square[3]);
  21071. }
  21072. }
  21073. // Position, normals and uvs
  21074. var position = BABYLON.Vector3.Zero();
  21075. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21076. for (row = 0; row <= precision.h; row++) {
  21077. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  21078. for (col = 0; col <= precision.w; col++) {
  21079. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  21080. position.y = 0;
  21081. positions.push(position.x, position.y, position.z);
  21082. normals.push(normal.x, normal.y, normal.z);
  21083. uvs.push(col / precision.w, row / precision.h);
  21084. }
  21085. }
  21086. }
  21087. // Result
  21088. var vertexData = new BABYLON.VertexData();
  21089. vertexData.indices = indices;
  21090. vertexData.positions = positions;
  21091. vertexData.normals = normals;
  21092. vertexData.uvs = uvs;
  21093. return vertexData;
  21094. };
  21095. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  21096. var indices = [];
  21097. var positions = [];
  21098. var normals = [];
  21099. var uvs = [];
  21100. var row, col;
  21101. for (row = 0; row <= subdivisions; row++) {
  21102. for (col = 0; col <= subdivisions; col++) {
  21103. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21104. // Compute height
  21105. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  21106. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  21107. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  21108. var r = buffer[pos] / 255.0;
  21109. var g = buffer[pos + 1] / 255.0;
  21110. var b = buffer[pos + 2] / 255.0;
  21111. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21112. position.y = minHeight + (maxHeight - minHeight) * gradient;
  21113. // Add vertex
  21114. positions.push(position.x, position.y, position.z);
  21115. normals.push(0, 0, 0);
  21116. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21117. }
  21118. }
  21119. for (row = 0; row < subdivisions; row++) {
  21120. for (col = 0; col < subdivisions; col++) {
  21121. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21122. indices.push(col + 1 + row * (subdivisions + 1));
  21123. indices.push(col + row * (subdivisions + 1));
  21124. indices.push(col + (row + 1) * (subdivisions + 1));
  21125. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21126. indices.push(col + row * (subdivisions + 1));
  21127. }
  21128. }
  21129. // Normals
  21130. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21131. // Result
  21132. var vertexData = new BABYLON.VertexData();
  21133. vertexData.indices = indices;
  21134. vertexData.positions = positions;
  21135. vertexData.normals = normals;
  21136. vertexData.uvs = uvs;
  21137. return vertexData;
  21138. };
  21139. VertexData.CreatePlane = function (size) {
  21140. var indices = [];
  21141. var positions = [];
  21142. var normals = [];
  21143. var uvs = [];
  21144. size = size || 1;
  21145. // Vertices
  21146. var halfSize = size / 2.0;
  21147. positions.push(-halfSize, -halfSize, 0);
  21148. normals.push(0, 0, -1.0);
  21149. uvs.push(0.0, 0.0);
  21150. positions.push(halfSize, -halfSize, 0);
  21151. normals.push(0, 0, -1.0);
  21152. uvs.push(1.0, 0.0);
  21153. positions.push(halfSize, halfSize, 0);
  21154. normals.push(0, 0, -1.0);
  21155. uvs.push(1.0, 1.0);
  21156. positions.push(-halfSize, halfSize, 0);
  21157. normals.push(0, 0, -1.0);
  21158. uvs.push(0.0, 1.0);
  21159. // Indices
  21160. indices.push(0);
  21161. indices.push(1);
  21162. indices.push(2);
  21163. indices.push(0);
  21164. indices.push(2);
  21165. indices.push(3);
  21166. // Result
  21167. var vertexData = new BABYLON.VertexData();
  21168. vertexData.indices = indices;
  21169. vertexData.positions = positions;
  21170. vertexData.normals = normals;
  21171. vertexData.uvs = uvs;
  21172. return vertexData;
  21173. };
  21174. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  21175. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  21176. var indices = [];
  21177. var positions = [];
  21178. var normals = [];
  21179. var uvs = [];
  21180. radius = radius || 2;
  21181. tube = tube || 0.5;
  21182. radialSegments = radialSegments || 32;
  21183. tubularSegments = tubularSegments || 32;
  21184. p = p || 2;
  21185. q = q || 3;
  21186. // Helper
  21187. var getPos = function (angle) {
  21188. var cu = Math.cos(angle);
  21189. var su = Math.sin(angle);
  21190. var quOverP = q / p * angle;
  21191. var cs = Math.cos(quOverP);
  21192. var tx = radius * (2 + cs) * 0.5 * cu;
  21193. var ty = radius * (2 + cs) * su * 0.5;
  21194. var tz = radius * Math.sin(quOverP) * 0.5;
  21195. return new BABYLON.Vector3(tx, ty, tz);
  21196. };
  21197. for (var i = 0; i <= radialSegments; i++) {
  21198. var modI = i % radialSegments;
  21199. var u = modI / radialSegments * 2 * p * Math.PI;
  21200. var p1 = getPos(u);
  21201. var p2 = getPos(u + 0.01);
  21202. var tang = p2.subtract(p1);
  21203. var n = p2.add(p1);
  21204. var bitan = BABYLON.Vector3.Cross(tang, n);
  21205. n = BABYLON.Vector3.Cross(bitan, tang);
  21206. bitan.normalize();
  21207. n.normalize();
  21208. for (var j = 0; j < tubularSegments; j++) {
  21209. var modJ = j % tubularSegments;
  21210. var v = modJ / tubularSegments * 2 * Math.PI;
  21211. var cx = -tube * Math.cos(v);
  21212. var cy = tube * Math.sin(v);
  21213. positions.push(p1.x + cx * n.x + cy * bitan.x);
  21214. positions.push(p1.y + cx * n.y + cy * bitan.y);
  21215. positions.push(p1.z + cx * n.z + cy * bitan.z);
  21216. uvs.push(i / radialSegments);
  21217. uvs.push(j / tubularSegments);
  21218. }
  21219. }
  21220. for (i = 0; i < radialSegments; i++) {
  21221. for (j = 0; j < tubularSegments; j++) {
  21222. var jNext = (j + 1) % tubularSegments;
  21223. var a = i * tubularSegments + j;
  21224. var b = (i + 1) * tubularSegments + j;
  21225. var c = (i + 1) * tubularSegments + jNext;
  21226. var d = i * tubularSegments + jNext;
  21227. indices.push(d);
  21228. indices.push(b);
  21229. indices.push(a);
  21230. indices.push(d);
  21231. indices.push(c);
  21232. indices.push(b);
  21233. }
  21234. }
  21235. // Normals
  21236. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21237. // Result
  21238. var vertexData = new BABYLON.VertexData();
  21239. vertexData.indices = indices;
  21240. vertexData.positions = positions;
  21241. vertexData.normals = normals;
  21242. vertexData.uvs = uvs;
  21243. return vertexData;
  21244. };
  21245. // Tools
  21246. VertexData.ComputeNormals = function (positions, indices, normals) {
  21247. var positionVectors = [];
  21248. var facesOfVertices = [];
  21249. var index;
  21250. for (index = 0; index < positions.length; index += 3) {
  21251. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  21252. positionVectors.push(vector3);
  21253. facesOfVertices.push([]);
  21254. }
  21255. // Compute normals
  21256. var facesNormals = [];
  21257. for (index = 0; index < indices.length / 3; index++) {
  21258. var i1 = indices[index * 3];
  21259. var i2 = indices[index * 3 + 1];
  21260. var i3 = indices[index * 3 + 2];
  21261. var p1 = positionVectors[i1];
  21262. var p2 = positionVectors[i2];
  21263. var p3 = positionVectors[i3];
  21264. var p1p2 = p1.subtract(p2);
  21265. var p3p2 = p3.subtract(p2);
  21266. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21267. facesOfVertices[i1].push(index);
  21268. facesOfVertices[i2].push(index);
  21269. facesOfVertices[i3].push(index);
  21270. }
  21271. for (index = 0; index < positionVectors.length; index++) {
  21272. var faces = facesOfVertices[index];
  21273. var normal = BABYLON.Vector3.Zero();
  21274. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  21275. normal.addInPlace(facesNormals[faces[faceIndex]]);
  21276. }
  21277. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  21278. normals[index * 3] = normal.x;
  21279. normals[index * 3 + 1] = normal.y;
  21280. normals[index * 3 + 2] = normal.z;
  21281. }
  21282. };
  21283. return VertexData;
  21284. })();
  21285. BABYLON.VertexData = VertexData;
  21286. })(BABYLON || (BABYLON = {}));
  21287. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  21288. var BABYLON;
  21289. (function (BABYLON) {
  21290. var buildCamera = function (that, name) {
  21291. that._leftCamera.isIntermediate = true;
  21292. that.subCameras.push(that._leftCamera);
  21293. that.subCameras.push(that._rightCamera);
  21294. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  21295. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  21296. that._anaglyphPostProcess.onApply = function (effect) {
  21297. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  21298. };
  21299. that._update();
  21300. };
  21301. var AnaglyphArcRotateCamera = (function (_super) {
  21302. __extends(AnaglyphArcRotateCamera, _super);
  21303. // ANY
  21304. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  21305. _super.call(this, name, alpha, beta, radius, target, scene);
  21306. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21307. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  21308. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  21309. buildCamera(this, name);
  21310. }
  21311. AnaglyphArcRotateCamera.prototype._update = function () {
  21312. this._updateCamera(this._leftCamera);
  21313. this._updateCamera(this._rightCamera);
  21314. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  21315. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  21316. _super.prototype._update.call(this);
  21317. };
  21318. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  21319. camera.beta = this.beta;
  21320. camera.radius = this.radius;
  21321. camera.minZ = this.minZ;
  21322. camera.maxZ = this.maxZ;
  21323. camera.fov = this.fov;
  21324. camera.target = this.target;
  21325. };
  21326. return AnaglyphArcRotateCamera;
  21327. })(BABYLON.ArcRotateCamera);
  21328. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  21329. var AnaglyphFreeCamera = (function (_super) {
  21330. __extends(AnaglyphFreeCamera, _super);
  21331. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  21332. _super.call(this, name, position, scene);
  21333. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21334. this._transformMatrix = new BABYLON.Matrix();
  21335. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  21336. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  21337. buildCamera(this, name);
  21338. }
  21339. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  21340. var target = this.getTarget();
  21341. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  21342. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  21343. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  21344. };
  21345. AnaglyphFreeCamera.prototype._update = function () {
  21346. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  21347. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  21348. this._updateCamera(this._leftCamera);
  21349. this._updateCamera(this._rightCamera);
  21350. _super.prototype._update.call(this);
  21351. };
  21352. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  21353. camera.minZ = this.minZ;
  21354. camera.maxZ = this.maxZ;
  21355. camera.fov = this.fov;
  21356. camera.viewport = this.viewport;
  21357. camera.setTarget(this.getTarget());
  21358. };
  21359. return AnaglyphFreeCamera;
  21360. })(BABYLON.FreeCamera);
  21361. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  21362. })(BABYLON || (BABYLON = {}));
  21363. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  21364. var BABYLON;
  21365. (function (BABYLON) {
  21366. var AnaglyphPostProcess = (function (_super) {
  21367. __extends(AnaglyphPostProcess, _super);
  21368. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21369. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  21370. }
  21371. return AnaglyphPostProcess;
  21372. })(BABYLON.PostProcess);
  21373. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  21374. })(BABYLON || (BABYLON = {}));
  21375. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  21376. (function (BABYLON) {
  21377. var Tags = (function () {
  21378. function Tags() {
  21379. }
  21380. Tags.EnableFor = function (obj) {
  21381. obj._tags = obj._tags || {};
  21382. obj.hasTags = function () {
  21383. return Tags.HasTags(obj);
  21384. };
  21385. obj.addTags = function (tagsString) {
  21386. return Tags.AddTagsTo(obj, tagsString);
  21387. };
  21388. obj.removeTags = function (tagsString) {
  21389. return Tags.RemoveTagsFrom(obj, tagsString);
  21390. };
  21391. obj.matchesTagsQuery = function (tagsQuery) {
  21392. return Tags.MatchesQuery(obj, tagsQuery);
  21393. };
  21394. };
  21395. Tags.DisableFor = function (obj) {
  21396. delete obj._tags;
  21397. delete obj.hasTags;
  21398. delete obj.addTags;
  21399. delete obj.removeTags;
  21400. delete obj.matchesTagsQuery;
  21401. };
  21402. Tags.HasTags = function (obj) {
  21403. if (!obj._tags) {
  21404. return false;
  21405. }
  21406. return !BABYLON.Tools.IsEmpty(obj._tags);
  21407. };
  21408. Tags.GetTags = function (obj) {
  21409. if (!obj._tags) {
  21410. return null;
  21411. }
  21412. return obj._tags;
  21413. };
  21414. // the tags 'true' and 'false' are reserved and cannot be used as tags
  21415. // a tag cannot start with '||', '&&', and '!'
  21416. // it cannot contain whitespaces
  21417. Tags.AddTagsTo = function (obj, tagsString) {
  21418. if (!tagsString) {
  21419. return;
  21420. }
  21421. var tags = tagsString.split(" ");
  21422. for (var t in tags) {
  21423. Tags._AddTagTo(obj, tags[t]);
  21424. }
  21425. };
  21426. Tags._AddTagTo = function (obj, tag) {
  21427. tag = tag.trim();
  21428. if (tag === "" || tag === "true" || tag === "false") {
  21429. return;
  21430. }
  21431. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  21432. return;
  21433. }
  21434. Tags.EnableFor(obj);
  21435. obj._tags[tag] = true;
  21436. };
  21437. Tags.RemoveTagsFrom = function (obj, tagsString) {
  21438. if (!Tags.HasTags(obj)) {
  21439. return;
  21440. }
  21441. var tags = tagsString.split(" ");
  21442. for (var t in tags) {
  21443. Tags._RemoveTagFrom(obj, tags[t]);
  21444. }
  21445. };
  21446. Tags._RemoveTagFrom = function (obj, tag) {
  21447. delete obj._tags[tag];
  21448. };
  21449. Tags.MatchesQuery = function (obj, tagsQuery) {
  21450. if (tagsQuery === undefined) {
  21451. return true;
  21452. }
  21453. if (tagsQuery === "") {
  21454. return Tags.HasTags(obj);
  21455. }
  21456. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  21457. };
  21458. return Tags;
  21459. })();
  21460. BABYLON.Tags = Tags;
  21461. })(BABYLON || (BABYLON = {}));
  21462. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  21463. (function (BABYLON) {
  21464. var Internals;
  21465. (function (Internals) {
  21466. var AndOrNotEvaluator = (function () {
  21467. function AndOrNotEvaluator() {
  21468. }
  21469. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  21470. if (!query.match(/\([^\(\)]*\)/g)) {
  21471. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  21472. }
  21473. else {
  21474. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  21475. // remove parenthesis
  21476. r = r.slice(1, r.length - 1);
  21477. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  21478. });
  21479. }
  21480. if (query === "true") {
  21481. return true;
  21482. }
  21483. if (query === "false") {
  21484. return false;
  21485. }
  21486. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  21487. };
  21488. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  21489. evaluateCallback = evaluateCallback || (function (r) {
  21490. return r === "true" ? true : false;
  21491. });
  21492. var result;
  21493. var or = parenthesisContent.split("||");
  21494. for (var i in or) {
  21495. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  21496. var and = ori.split("&&");
  21497. if (and.length > 1) {
  21498. for (var j = 0; j < and.length; ++j) {
  21499. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  21500. if (andj !== "true" && andj !== "false") {
  21501. if (andj[0] === "!") {
  21502. result = !evaluateCallback(andj.substring(1));
  21503. }
  21504. else {
  21505. result = evaluateCallback(andj);
  21506. }
  21507. }
  21508. else {
  21509. result = andj === "true" ? true : false;
  21510. }
  21511. if (!result) {
  21512. ori = "false";
  21513. break;
  21514. }
  21515. }
  21516. }
  21517. if (result || ori === "true") {
  21518. result = true;
  21519. break;
  21520. }
  21521. // result equals false (or undefined)
  21522. if (ori !== "true" && ori !== "false") {
  21523. if (ori[0] === "!") {
  21524. result = !evaluateCallback(ori.substring(1));
  21525. }
  21526. else {
  21527. result = evaluateCallback(ori);
  21528. }
  21529. }
  21530. else {
  21531. result = ori === "true" ? true : false;
  21532. }
  21533. }
  21534. // the whole parenthesis scope is replaced by 'true' or 'false'
  21535. return result ? "true" : "false";
  21536. };
  21537. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  21538. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  21539. // remove whitespaces
  21540. r = r.replace(/[\s]/g, function () { return ""; });
  21541. return r.length % 2 ? "!" : "";
  21542. });
  21543. booleanString = booleanString.trim();
  21544. if (booleanString === "!true") {
  21545. booleanString = "false";
  21546. }
  21547. else if (booleanString === "!false") {
  21548. booleanString = "true";
  21549. }
  21550. return booleanString;
  21551. };
  21552. return AndOrNotEvaluator;
  21553. })();
  21554. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  21555. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21556. })(BABYLON || (BABYLON = {}));
  21557. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  21558. (function (BABYLON) {
  21559. var PostProcessRenderPass = (function () {
  21560. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  21561. this._enabled = true;
  21562. this._refCount = 0;
  21563. this._name = name;
  21564. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  21565. this.setRenderList(renderList);
  21566. this._renderTexture.onBeforeRender = beforeRender;
  21567. this._renderTexture.onAfterRender = afterRender;
  21568. this._scene = scene;
  21569. this._renderList = renderList;
  21570. }
  21571. // private
  21572. PostProcessRenderPass.prototype._incRefCount = function () {
  21573. if (this._refCount === 0) {
  21574. this._scene.customRenderTargets.push(this._renderTexture);
  21575. }
  21576. return ++this._refCount;
  21577. };
  21578. PostProcessRenderPass.prototype._decRefCount = function () {
  21579. this._refCount--;
  21580. if (this._refCount <= 0) {
  21581. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  21582. }
  21583. return this._refCount;
  21584. };
  21585. PostProcessRenderPass.prototype._update = function () {
  21586. this.setRenderList(this._renderList);
  21587. };
  21588. // public
  21589. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  21590. this._renderTexture.renderList = renderList;
  21591. };
  21592. PostProcessRenderPass.prototype.getRenderTexture = function () {
  21593. return this._renderTexture;
  21594. };
  21595. return PostProcessRenderPass;
  21596. })();
  21597. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  21598. })(BABYLON || (BABYLON = {}));
  21599. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  21600. (function (BABYLON) {
  21601. var PostProcessRenderEffect = (function () {
  21602. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  21603. this._engine = engine;
  21604. this._name = name;
  21605. this._singleInstance = singleInstance || true;
  21606. this._getPostProcess = getPostProcess;
  21607. this._cameras = [];
  21608. this._indicesForCamera = [];
  21609. this._postProcesses = {};
  21610. this._renderPasses = {};
  21611. this._renderEffectAsPasses = {};
  21612. }
  21613. PostProcessRenderEffect.prototype._update = function () {
  21614. for (var renderPassName in this._renderPasses) {
  21615. this._renderPasses[renderPassName]._update();
  21616. }
  21617. };
  21618. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  21619. this._renderPasses[renderPass._name] = renderPass;
  21620. this._linkParameters();
  21621. };
  21622. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  21623. delete this._renderPasses[renderPass._name];
  21624. this._linkParameters();
  21625. };
  21626. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  21627. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  21628. this._linkParameters();
  21629. };
  21630. PostProcessRenderEffect.prototype.getPass = function (passName) {
  21631. for (var renderPassName in this._renderPasses) {
  21632. if (renderPassName === passName) {
  21633. return this._renderPasses[passName];
  21634. }
  21635. }
  21636. };
  21637. PostProcessRenderEffect.prototype.emptyPasses = function () {
  21638. this._renderPasses = {};
  21639. this._linkParameters();
  21640. };
  21641. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  21642. var cameraKey;
  21643. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21644. for (var i = 0; i < _cam.length; i++) {
  21645. var camera = _cam[i];
  21646. var cameraName = camera.name;
  21647. if (this._singleInstance) {
  21648. cameraKey = 0;
  21649. }
  21650. else {
  21651. cameraKey = cameraName;
  21652. }
  21653. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  21654. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  21655. if (!this._indicesForCamera[cameraName]) {
  21656. this._indicesForCamera[cameraName] = [];
  21657. }
  21658. this._indicesForCamera[cameraName].push(index);
  21659. if (this._cameras.indexOf(camera) === -1) {
  21660. this._cameras[cameraName] = camera;
  21661. }
  21662. for (var passName in this._renderPasses) {
  21663. this._renderPasses[passName]._incRefCount();
  21664. }
  21665. }
  21666. this._linkParameters();
  21667. };
  21668. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  21669. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21670. for (var i = 0; i < _cam.length; i++) {
  21671. var camera = _cam[i];
  21672. var cameraName = camera.name;
  21673. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21674. var index = this._cameras.indexOf(cameraName);
  21675. this._indicesForCamera.splice(index, 1);
  21676. this._cameras.splice(index, 1);
  21677. for (var passName in this._renderPasses) {
  21678. this._renderPasses[passName]._decRefCount();
  21679. }
  21680. }
  21681. };
  21682. PostProcessRenderEffect.prototype._enable = function (cameras) {
  21683. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21684. for (var i = 0; i < _cam.length; i++) {
  21685. var camera = _cam[i];
  21686. var cameraName = camera.name;
  21687. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  21688. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  21689. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  21690. }
  21691. }
  21692. for (var passName in this._renderPasses) {
  21693. this._renderPasses[passName]._incRefCount();
  21694. }
  21695. }
  21696. };
  21697. PostProcessRenderEffect.prototype._disable = function (cameras) {
  21698. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21699. for (var i = 0; i < _cam.length; i++) {
  21700. var camera = _cam[i];
  21701. var cameraName = camera.Name;
  21702. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21703. for (var passName in this._renderPasses) {
  21704. this._renderPasses[passName]._decRefCount();
  21705. }
  21706. }
  21707. };
  21708. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  21709. if (this._singleInstance) {
  21710. return this._postProcesses[0];
  21711. }
  21712. else {
  21713. return this._postProcesses[camera.name];
  21714. }
  21715. };
  21716. PostProcessRenderEffect.prototype._linkParameters = function () {
  21717. var _this = this;
  21718. for (var index in this._postProcesses) {
  21719. if (this.applyParameters) {
  21720. this.applyParameters(this._postProcesses[index]);
  21721. }
  21722. this._postProcesses[index].onBeforeRender = function (effect) {
  21723. _this._linkTextures(effect);
  21724. };
  21725. }
  21726. };
  21727. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  21728. for (var renderPassName in this._renderPasses) {
  21729. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  21730. }
  21731. for (var renderEffectName in this._renderEffectAsPasses) {
  21732. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  21733. }
  21734. };
  21735. return PostProcessRenderEffect;
  21736. })();
  21737. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  21738. })(BABYLON || (BABYLON = {}));
  21739. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  21740. (function (BABYLON) {
  21741. var PostProcessRenderPipeline = (function () {
  21742. function PostProcessRenderPipeline(engine, name) {
  21743. this._engine = engine;
  21744. this._name = name;
  21745. this._renderEffects = {};
  21746. this._renderEffectsForIsolatedPass = {};
  21747. this._cameras = [];
  21748. }
  21749. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  21750. this._renderEffects[renderEffect._name] = renderEffect;
  21751. };
  21752. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  21753. var renderEffects = this._renderEffects[renderEffectName];
  21754. if (!renderEffects) {
  21755. return;
  21756. }
  21757. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21758. };
  21759. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  21760. var renderEffects = this._renderEffects[renderEffectName];
  21761. if (!renderEffects) {
  21762. return;
  21763. }
  21764. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21765. };
  21766. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  21767. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21768. var indicesToDelete = [];
  21769. for (var i = 0; i < _cam.length; i++) {
  21770. var camera = _cam[i];
  21771. var cameraName = camera.name;
  21772. if (this._cameras.indexOf(camera) === -1) {
  21773. this._cameras[cameraName] = camera;
  21774. }
  21775. else if (unique) {
  21776. indicesToDelete.push(i);
  21777. }
  21778. }
  21779. for (var i = 0; i < indicesToDelete.length; i++) {
  21780. cameras.splice(indicesToDelete[i], 1);
  21781. }
  21782. for (var renderEffectName in this._renderEffects) {
  21783. this._renderEffects[renderEffectName]._attachCameras(_cam);
  21784. }
  21785. };
  21786. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  21787. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21788. for (var renderEffectName in this._renderEffects) {
  21789. this._renderEffects[renderEffectName]._detachCameras(_cam);
  21790. }
  21791. for (var i = 0; i < _cam.length; i++) {
  21792. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  21793. }
  21794. };
  21795. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  21796. var _this = this;
  21797. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21798. var pass = null;
  21799. for (var renderEffectName in this._renderEffects) {
  21800. pass = this._renderEffects[renderEffectName].getPass(passName);
  21801. if (pass != null) {
  21802. break;
  21803. }
  21804. }
  21805. if (pass === null) {
  21806. return;
  21807. }
  21808. for (var renderEffectName in this._renderEffects) {
  21809. this._renderEffects[renderEffectName]._disable(_cam);
  21810. }
  21811. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  21812. for (var i = 0; i < _cam.length; i++) {
  21813. var camera = _cam[i];
  21814. var cameraName = camera.name;
  21815. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21816. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21817. });
  21818. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  21819. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  21820. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  21821. }
  21822. };
  21823. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  21824. var _this = this;
  21825. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21826. for (var i = 0; i < _cam.length; i++) {
  21827. var camera = _cam[i];
  21828. var cameraName = camera.name;
  21829. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21830. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21831. });
  21832. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  21833. }
  21834. for (var renderEffectName in this._renderEffects) {
  21835. this._renderEffects[renderEffectName]._enable(_cam);
  21836. }
  21837. };
  21838. PostProcessRenderPipeline.prototype._update = function () {
  21839. for (var renderEffectName in this._renderEffects) {
  21840. this._renderEffects[renderEffectName]._update();
  21841. }
  21842. for (var i = 0; i < this._cameras.length; i++) {
  21843. var cameraName = this._cameras[i].name;
  21844. if (this._renderEffectsForIsolatedPass[cameraName]) {
  21845. this._renderEffectsForIsolatedPass[cameraName]._update();
  21846. }
  21847. }
  21848. };
  21849. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  21850. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  21851. return PostProcessRenderPipeline;
  21852. })();
  21853. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  21854. })(BABYLON || (BABYLON = {}));
  21855. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  21856. (function (BABYLON) {
  21857. var PostProcessRenderPipelineManager = (function () {
  21858. function PostProcessRenderPipelineManager() {
  21859. this._renderPipelines = {};
  21860. }
  21861. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  21862. this._renderPipelines[renderPipeline._name] = renderPipeline;
  21863. };
  21864. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  21865. var renderPipeline = this._renderPipelines[renderPipelineName];
  21866. if (!renderPipeline) {
  21867. return;
  21868. }
  21869. renderPipeline._attachCameras(cameras, unique);
  21870. };
  21871. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  21872. var renderPipeline = this._renderPipelines[renderPipelineName];
  21873. if (!renderPipeline) {
  21874. return;
  21875. }
  21876. renderPipeline._detachCameras(cameras);
  21877. };
  21878. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21879. var renderPipeline = this._renderPipelines[renderPipelineName];
  21880. if (!renderPipeline) {
  21881. return;
  21882. }
  21883. renderPipeline._enableEffect(renderEffectName, cameras);
  21884. };
  21885. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21886. var renderPipeline = this._renderPipelines[renderPipelineName];
  21887. if (!renderPipeline) {
  21888. return;
  21889. }
  21890. renderPipeline._disableEffect(renderEffectName, cameras);
  21891. };
  21892. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  21893. var renderPipeline = this._renderPipelines[renderPipelineName];
  21894. if (!renderPipeline) {
  21895. return;
  21896. }
  21897. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  21898. };
  21899. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  21900. var renderPipeline = this._renderPipelines[renderPipelineName];
  21901. if (!renderPipeline) {
  21902. return;
  21903. }
  21904. renderPipeline._disableDisplayOnlyPass(cameras);
  21905. };
  21906. PostProcessRenderPipelineManager.prototype.update = function () {
  21907. for (var renderPipelineName in this._renderPipelines) {
  21908. this._renderPipelines[renderPipelineName]._update();
  21909. }
  21910. };
  21911. return PostProcessRenderPipelineManager;
  21912. })();
  21913. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  21914. })(BABYLON || (BABYLON = {}));
  21915. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  21916. var BABYLON;
  21917. (function (BABYLON) {
  21918. var DisplayPassPostProcess = (function (_super) {
  21919. __extends(DisplayPassPostProcess, _super);
  21920. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21921. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  21922. }
  21923. return DisplayPassPostProcess;
  21924. })(BABYLON.PostProcess);
  21925. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  21926. })(BABYLON || (BABYLON = {}));
  21927. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  21928. (function (BABYLON) {
  21929. var BoundingBoxRenderer = (function () {
  21930. function BoundingBoxRenderer(scene) {
  21931. this.frontColor = new BABYLON.Color3(1, 1, 1);
  21932. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  21933. this.showBackLines = true;
  21934. this.renderList = new BABYLON.SmartArray(32);
  21935. this._scene = scene;
  21936. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  21937. attributes: ["position"],
  21938. uniforms: ["worldViewProjection", "color"]
  21939. });
  21940. var engine = this._scene.getEngine();
  21941. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  21942. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  21943. 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]);
  21944. }
  21945. BoundingBoxRenderer.prototype.reset = function () {
  21946. this.renderList.reset();
  21947. };
  21948. BoundingBoxRenderer.prototype.render = function () {
  21949. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  21950. return;
  21951. }
  21952. var engine = this._scene.getEngine();
  21953. engine.setDepthWrite(false);
  21954. this._colorShader._preBind();
  21955. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  21956. var boundingBox = this.renderList.data[boundingBoxIndex];
  21957. var min = boundingBox.minimum;
  21958. var max = boundingBox.maximum;
  21959. var diff = max.subtract(min);
  21960. var median = min.add(diff.scale(0.5));
  21961. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  21962. // VBOs
  21963. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  21964. if (this.showBackLines) {
  21965. // Back
  21966. engine.setDepthFunctionToGreaterOrEqual();
  21967. this._scene.resetCachedMaterial();
  21968. this._colorShader.setColor4("color", this.backColor.toColor4());
  21969. this._colorShader.bind(worldMatrix);
  21970. // Draw order
  21971. engine.draw(false, 0, 24);
  21972. }
  21973. // Front
  21974. engine.setDepthFunctionToLess();
  21975. this._scene.resetCachedMaterial();
  21976. this._colorShader.setColor4("color", this.frontColor.toColor4());
  21977. this._colorShader.bind(worldMatrix);
  21978. // Draw order
  21979. engine.draw(false, 0, 24);
  21980. }
  21981. this._colorShader.unbind();
  21982. engine.setDepthFunctionToLessOrEqual();
  21983. engine.setDepthWrite(true);
  21984. };
  21985. BoundingBoxRenderer.prototype.dispose = function () {
  21986. this._colorShader.dispose();
  21987. this._vb.dispose();
  21988. this._scene.getEngine()._releaseBuffer(this._ib);
  21989. };
  21990. return BoundingBoxRenderer;
  21991. })();
  21992. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  21993. })(BABYLON || (BABYLON = {}));
  21994. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  21995. (function (BABYLON) {
  21996. var Internals;
  21997. (function (Internals) {
  21998. /*
  21999. * Based on jsTGALoader - Javascript loader for TGA file
  22000. * By Vincent Thibault
  22001. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  22002. */
  22003. var TGATools = (function () {
  22004. function TGATools() {
  22005. }
  22006. TGATools.GetTGAHeader = function (data) {
  22007. var offset = 0;
  22008. var header = {
  22009. id_length: data[offset++],
  22010. colormap_type: data[offset++],
  22011. image_type: data[offset++],
  22012. colormap_index: data[offset++] | data[offset++] << 8,
  22013. colormap_length: data[offset++] | data[offset++] << 8,
  22014. colormap_size: data[offset++],
  22015. origin: [
  22016. data[offset++] | data[offset++] << 8,
  22017. data[offset++] | data[offset++] << 8
  22018. ],
  22019. width: data[offset++] | data[offset++] << 8,
  22020. height: data[offset++] | data[offset++] << 8,
  22021. pixel_size: data[offset++],
  22022. flags: data[offset++]
  22023. };
  22024. return header;
  22025. };
  22026. TGATools.UploadContent = function (gl, data) {
  22027. // Not enough data to contain header ?
  22028. if (data.length < 19) {
  22029. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  22030. return;
  22031. }
  22032. // Read Header
  22033. var offset = 18;
  22034. var header = TGATools.GetTGAHeader(data);
  22035. // Assume it's a valid Targa file.
  22036. if (header.id_length + offset > data.length) {
  22037. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  22038. return;
  22039. }
  22040. // Skip not needed data
  22041. offset += header.id_length;
  22042. var use_rle = false;
  22043. var use_pal = false;
  22044. var use_rgb = false;
  22045. var use_grey = false;
  22046. switch (header.image_type) {
  22047. case TGATools._TYPE_RLE_INDEXED:
  22048. use_rle = true;
  22049. case TGATools._TYPE_INDEXED:
  22050. use_pal = true;
  22051. break;
  22052. case TGATools._TYPE_RLE_RGB:
  22053. use_rle = true;
  22054. case TGATools._TYPE_RGB:
  22055. use_rgb = true;
  22056. break;
  22057. case TGATools._TYPE_RLE_GREY:
  22058. use_rle = true;
  22059. case TGATools._TYPE_GREY:
  22060. use_grey = true;
  22061. break;
  22062. }
  22063. var pixel_data;
  22064. var numAlphaBits = header.flags & 0xf;
  22065. var pixel_size = header.pixel_size >> 3;
  22066. var pixel_total = header.width * header.height * pixel_size;
  22067. // Read palettes
  22068. var palettes;
  22069. if (use_pal) {
  22070. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  22071. }
  22072. // Read LRE
  22073. if (use_rle) {
  22074. pixel_data = new Uint8Array(pixel_total);
  22075. var c, count, i;
  22076. var localOffset = 0;
  22077. var pixels = new Uint8Array(pixel_size);
  22078. while (offset < pixel_total && localOffset < pixel_total) {
  22079. c = data[offset++];
  22080. count = (c & 0x7f) + 1;
  22081. // RLE pixels
  22082. if (c & 0x80) {
  22083. for (i = 0; i < pixel_size; ++i) {
  22084. pixels[i] = data[offset++];
  22085. }
  22086. for (i = 0; i < count; ++i) {
  22087. pixel_data.set(pixels, localOffset + i * pixel_size);
  22088. }
  22089. localOffset += pixel_size * count;
  22090. }
  22091. else {
  22092. count *= pixel_size;
  22093. for (i = 0; i < count; ++i) {
  22094. pixel_data[localOffset + i] = data[offset++];
  22095. }
  22096. localOffset += count;
  22097. }
  22098. }
  22099. }
  22100. else {
  22101. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  22102. }
  22103. // Load to texture
  22104. var x_start, y_start, x_step, y_step, y_end, x_end;
  22105. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  22106. default:
  22107. case TGATools._ORIGIN_UL:
  22108. x_start = 0;
  22109. x_step = 1;
  22110. x_end = header.width;
  22111. y_start = 0;
  22112. y_step = 1;
  22113. y_end = header.height;
  22114. break;
  22115. case TGATools._ORIGIN_BL:
  22116. x_start = 0;
  22117. x_step = 1;
  22118. x_end = header.width;
  22119. y_start = header.height - 1;
  22120. y_step = -1;
  22121. y_end = -1;
  22122. break;
  22123. case TGATools._ORIGIN_UR:
  22124. x_start = header.width - 1;
  22125. x_step = -1;
  22126. x_end = -1;
  22127. y_start = 0;
  22128. y_step = 1;
  22129. y_end = header.height;
  22130. break;
  22131. case TGATools._ORIGIN_BR:
  22132. x_start = header.width - 1;
  22133. x_step = -1;
  22134. x_end = -1;
  22135. y_start = header.height - 1;
  22136. y_step = -1;
  22137. y_end = -1;
  22138. break;
  22139. }
  22140. // Load the specify method
  22141. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  22142. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  22143. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  22144. };
  22145. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22146. var image = pixel_data, colormap = palettes;
  22147. var width = header.width, height = header.height;
  22148. var color, i = 0, x, y;
  22149. var imageData = new Uint8Array(width * height * 4);
  22150. for (y = y_start; y !== y_end; y += y_step) {
  22151. for (x = x_start; x !== x_end; x += x_step, i++) {
  22152. color = image[i];
  22153. imageData[(x + width * y) * 4 + 3] = 255;
  22154. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  22155. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  22156. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  22157. }
  22158. }
  22159. return imageData;
  22160. };
  22161. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22162. var image = pixel_data;
  22163. var width = header.width, height = header.height;
  22164. var color, i = 0, x, y;
  22165. var imageData = new Uint8Array(width * height * 4);
  22166. for (y = y_start; y !== y_end; y += y_step) {
  22167. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22168. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  22169. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  22170. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  22171. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  22172. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  22173. }
  22174. }
  22175. return imageData;
  22176. };
  22177. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22178. var image = pixel_data;
  22179. var width = header.width, height = header.height;
  22180. var i = 0, x, y;
  22181. var imageData = new Uint8Array(width * height * 4);
  22182. for (y = y_start; y !== y_end; y += y_step) {
  22183. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  22184. imageData[(x + width * y) * 4 + 3] = 255;
  22185. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22186. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22187. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22188. }
  22189. }
  22190. return imageData;
  22191. };
  22192. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22193. var image = pixel_data;
  22194. var width = header.width, height = header.height;
  22195. var i = 0, x, y;
  22196. var imageData = new Uint8Array(width * height * 4);
  22197. for (y = y_start; y !== y_end; y += y_step) {
  22198. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  22199. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22200. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22201. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22202. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  22203. }
  22204. }
  22205. return imageData;
  22206. };
  22207. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22208. var image = pixel_data;
  22209. var width = header.width, height = header.height;
  22210. var color, i = 0, x, y;
  22211. var imageData = new Uint8Array(width * height * 4);
  22212. for (y = y_start; y !== y_end; y += y_step) {
  22213. for (x = x_start; x !== x_end; x += x_step, i++) {
  22214. color = image[i];
  22215. imageData[(x + width * y) * 4 + 0] = color;
  22216. imageData[(x + width * y) * 4 + 1] = color;
  22217. imageData[(x + width * y) * 4 + 2] = color;
  22218. imageData[(x + width * y) * 4 + 3] = 255;
  22219. }
  22220. }
  22221. return imageData;
  22222. };
  22223. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22224. var image = pixel_data;
  22225. var width = header.width, height = header.height;
  22226. var i = 0, x, y;
  22227. var imageData = new Uint8Array(width * height * 4);
  22228. for (y = y_start; y !== y_end; y += y_step) {
  22229. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22230. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  22231. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  22232. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22233. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  22234. }
  22235. }
  22236. return imageData;
  22237. };
  22238. TGATools._TYPE_NO_DATA = 0;
  22239. TGATools._TYPE_INDEXED = 1;
  22240. TGATools._TYPE_RGB = 2;
  22241. TGATools._TYPE_GREY = 3;
  22242. TGATools._TYPE_RLE_INDEXED = 9;
  22243. TGATools._TYPE_RLE_RGB = 10;
  22244. TGATools._TYPE_RLE_GREY = 11;
  22245. TGATools._ORIGIN_MASK = 0x30;
  22246. TGATools._ORIGIN_SHIFT = 0x04;
  22247. TGATools._ORIGIN_BL = 0x00;
  22248. TGATools._ORIGIN_BR = 0x01;
  22249. TGATools._ORIGIN_UL = 0x02;
  22250. TGATools._ORIGIN_UR = 0x03;
  22251. return TGATools;
  22252. })();
  22253. Internals.TGATools = TGATools;
  22254. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22255. })(BABYLON || (BABYLON = {}));
  22256. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  22257. (function (BABYLON) {
  22258. var Internals;
  22259. (function (Internals) {
  22260. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  22261. // All values and structures referenced from:
  22262. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  22263. var DDS_MAGIC = 0x20534444;
  22264. 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;
  22265. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  22266. 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;
  22267. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  22268. function FourCCToInt32(value) {
  22269. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  22270. }
  22271. function Int32ToFourCC(value) {
  22272. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  22273. }
  22274. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  22275. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  22276. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  22277. var headerLengthInt = 31; // The header length in 32 bit ints
  22278. // Offsets into the header array
  22279. var off_magic = 0;
  22280. var off_size = 1;
  22281. var off_flags = 2;
  22282. var off_height = 3;
  22283. var off_width = 4;
  22284. var off_mipmapCount = 7;
  22285. var off_pfFlags = 20;
  22286. var off_pfFourCC = 21;
  22287. var off_RGBbpp = 22;
  22288. var off_RMask = 23;
  22289. var off_GMask = 24;
  22290. var off_BMask = 25;
  22291. var off_AMask = 26;
  22292. var off_caps1 = 27;
  22293. var off_caps2 = 28;
  22294. ;
  22295. var DDSTools = (function () {
  22296. function DDSTools() {
  22297. }
  22298. DDSTools.GetDDSInfo = function (arrayBuffer) {
  22299. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  22300. var mipmapCount = 1;
  22301. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  22302. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22303. }
  22304. return {
  22305. width: header[off_width],
  22306. height: header[off_height],
  22307. mipmapCount: mipmapCount,
  22308. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  22309. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  22310. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  22311. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  22312. };
  22313. };
  22314. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22315. var byteArray = new Uint8Array(dataLength);
  22316. var srcData = new Uint8Array(arrayBuffer);
  22317. var index = 0;
  22318. for (var y = height - 1; y >= 0; y--) {
  22319. for (var x = 0; x < width; x++) {
  22320. var srcPos = dataOffset + (x + y * width) * 4;
  22321. byteArray[index + 2] = srcData[srcPos];
  22322. byteArray[index + 1] = srcData[srcPos + 1];
  22323. byteArray[index] = srcData[srcPos + 2];
  22324. byteArray[index + 3] = srcData[srcPos + 3];
  22325. index += 4;
  22326. }
  22327. }
  22328. return byteArray;
  22329. };
  22330. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22331. var byteArray = new Uint8Array(dataLength);
  22332. var srcData = new Uint8Array(arrayBuffer);
  22333. var index = 0;
  22334. for (var y = height - 1; y >= 0; y--) {
  22335. for (var x = 0; x < width; x++) {
  22336. var srcPos = dataOffset + (x + y * width) * 3;
  22337. byteArray[index + 2] = srcData[srcPos];
  22338. byteArray[index + 1] = srcData[srcPos + 1];
  22339. byteArray[index] = srcData[srcPos + 2];
  22340. index += 3;
  22341. }
  22342. }
  22343. return byteArray;
  22344. };
  22345. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22346. var byteArray = new Uint8Array(dataLength);
  22347. var srcData = new Uint8Array(arrayBuffer);
  22348. var index = 0;
  22349. for (var y = height - 1; y >= 0; y--) {
  22350. for (var x = 0; x < width; x++) {
  22351. var srcPos = dataOffset + (x + y * width);
  22352. byteArray[index] = srcData[srcPos];
  22353. index++;
  22354. }
  22355. }
  22356. return byteArray;
  22357. };
  22358. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  22359. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  22360. if (header[off_magic] != DDS_MAGIC) {
  22361. BABYLON.Tools.Error("Invalid magic number in DDS header");
  22362. return;
  22363. }
  22364. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  22365. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  22366. return;
  22367. }
  22368. if (info.isFourCC) {
  22369. fourCC = header[off_pfFourCC];
  22370. switch (fourCC) {
  22371. case FOURCC_DXT1:
  22372. blockBytes = 8;
  22373. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  22374. break;
  22375. case FOURCC_DXT3:
  22376. blockBytes = 16;
  22377. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  22378. break;
  22379. case FOURCC_DXT5:
  22380. blockBytes = 16;
  22381. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  22382. break;
  22383. default:
  22384. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  22385. return;
  22386. }
  22387. }
  22388. mipmapCount = 1;
  22389. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  22390. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22391. }
  22392. var bpp = header[off_RGBbpp];
  22393. for (var face = 0; face < faces; face++) {
  22394. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  22395. width = header[off_width];
  22396. height = header[off_height];
  22397. dataOffset = header[off_size] + 4;
  22398. for (i = 0; i < mipmapCount; ++i) {
  22399. if (info.isRGB) {
  22400. if (bpp == 24) {
  22401. dataLength = width * height * 3;
  22402. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22403. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  22404. }
  22405. else {
  22406. dataLength = width * height * 4;
  22407. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22408. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  22409. }
  22410. }
  22411. else if (info.isLuminance) {
  22412. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  22413. var unpaddedRowSize = width;
  22414. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  22415. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  22416. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22417. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  22418. }
  22419. else {
  22420. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  22421. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  22422. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  22423. }
  22424. dataOffset += dataLength;
  22425. width *= 0.5;
  22426. height *= 0.5;
  22427. width = Math.max(1.0, width);
  22428. height = Math.max(1.0, height);
  22429. }
  22430. }
  22431. };
  22432. return DDSTools;
  22433. })();
  22434. Internals.DDSTools = DDSTools;
  22435. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22436. })(BABYLON || (BABYLON = {}));
  22437. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  22438. (function (BABYLON) {
  22439. var SmartArray = (function () {
  22440. function SmartArray(capacity) {
  22441. this.length = 0;
  22442. this._duplicateId = 0;
  22443. this.data = new Array(capacity);
  22444. this._id = SmartArray._GlobalId++;
  22445. }
  22446. SmartArray.prototype.push = function (value) {
  22447. this.data[this.length++] = value;
  22448. if (this.length > this.data.length) {
  22449. this.data.length *= 2;
  22450. }
  22451. if (!value.__smartArrayFlags) {
  22452. value.__smartArrayFlags = {};
  22453. }
  22454. value.__smartArrayFlags[this._id] = this._duplicateId;
  22455. };
  22456. SmartArray.prototype.pushNoDuplicate = function (value) {
  22457. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  22458. return;
  22459. }
  22460. this.push(value);
  22461. };
  22462. SmartArray.prototype.sort = function (compareFn) {
  22463. this.data.sort(compareFn);
  22464. };
  22465. SmartArray.prototype.reset = function () {
  22466. this.length = 0;
  22467. this._duplicateId++;
  22468. };
  22469. SmartArray.prototype.concat = function (array) {
  22470. if (array.length === 0) {
  22471. return;
  22472. }
  22473. if (this.length + array.length > this.data.length) {
  22474. this.data.length = (this.length + array.length) * 2;
  22475. }
  22476. for (var index = 0; index < array.length; index++) {
  22477. this.data[this.length++] = (array.data || array)[index];
  22478. }
  22479. };
  22480. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  22481. if (array.length === 0) {
  22482. return;
  22483. }
  22484. if (this.length + array.length > this.data.length) {
  22485. this.data.length = (this.length + array.length) * 2;
  22486. }
  22487. for (var index = 0; index < array.length; index++) {
  22488. var item = (array.data || array)[index];
  22489. this.pushNoDuplicate(item);
  22490. }
  22491. };
  22492. SmartArray.prototype.indexOf = function (value) {
  22493. var position = this.data.indexOf(value);
  22494. if (position >= this.length) {
  22495. return -1;
  22496. }
  22497. return position;
  22498. };
  22499. // Statics
  22500. SmartArray._GlobalId = 0;
  22501. return SmartArray;
  22502. })();
  22503. BABYLON.SmartArray = SmartArray;
  22504. })(BABYLON || (BABYLON = {}));
  22505. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  22506. (function (BABYLON) {
  22507. var CannonJSPlugin = (function () {
  22508. function CannonJSPlugin() {
  22509. this._registeredMeshes = [];
  22510. this._physicsMaterials = [];
  22511. this.updateBodyPosition = function (mesh) {
  22512. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22513. var registeredMesh = this._registeredMeshes[index];
  22514. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22515. var body = registeredMesh.body;
  22516. var center = mesh.getBoundingInfo().boundingBox.center;
  22517. body.position.set(center.x, center.z, center.y);
  22518. body.quaternion.x = mesh.rotationQuaternion.x;
  22519. body.quaternion.z = mesh.rotationQuaternion.y;
  22520. body.quaternion.y = mesh.rotationQuaternion.z;
  22521. body.quaternion.w = -mesh.rotationQuaternion.w;
  22522. return;
  22523. }
  22524. }
  22525. };
  22526. }
  22527. CannonJSPlugin.prototype.initialize = function (iterations) {
  22528. if (iterations === void 0) { iterations = 10; }
  22529. this._world = new CANNON.World();
  22530. this._world.broadphase = new CANNON.NaiveBroadphase();
  22531. this._world.solver.iterations = iterations;
  22532. };
  22533. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22534. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22535. };
  22536. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22537. this._world.step(delta);
  22538. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22539. var registeredMesh = this._registeredMeshes[index];
  22540. if (registeredMesh.isChild) {
  22541. continue;
  22542. }
  22543. // Body position
  22544. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22545. var deltaPos = registeredMesh.delta;
  22546. if (deltaPos) {
  22547. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22548. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22549. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22550. }
  22551. else {
  22552. registeredMesh.mesh.position.x = bodyX;
  22553. registeredMesh.mesh.position.y = bodyZ;
  22554. registeredMesh.mesh.position.z = bodyY;
  22555. }
  22556. if (!registeredMesh.mesh.rotationQuaternion) {
  22557. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22558. }
  22559. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22560. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22561. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22562. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22563. }
  22564. };
  22565. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22566. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22567. };
  22568. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22569. this.unregisterMesh(mesh);
  22570. mesh.computeWorldMatrix(true);
  22571. switch (impostor) {
  22572. case BABYLON.PhysicsEngine.SphereImpostor:
  22573. var bbox = mesh.getBoundingInfo().boundingBox;
  22574. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22575. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22576. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22577. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22578. case BABYLON.PhysicsEngine.BoxImpostor:
  22579. bbox = mesh.getBoundingInfo().boundingBox;
  22580. var min = bbox.minimumWorld;
  22581. var max = bbox.maximumWorld;
  22582. var box = max.subtract(min).scale(0.5);
  22583. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22584. case BABYLON.PhysicsEngine.PlaneImpostor:
  22585. return this._createPlane(mesh, options);
  22586. case BABYLON.PhysicsEngine.MeshImpostor:
  22587. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22588. var rawFaces = mesh.getIndices();
  22589. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22590. }
  22591. return null;
  22592. };
  22593. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22594. var shape = new CANNON.Sphere(radius);
  22595. if (!options) {
  22596. return shape;
  22597. }
  22598. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22599. };
  22600. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22601. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22602. if (!options) {
  22603. return shape;
  22604. }
  22605. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22606. };
  22607. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22608. var shape = new CANNON.Plane();
  22609. if (!options) {
  22610. return shape;
  22611. }
  22612. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22613. };
  22614. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22615. var verts = [], faces = [];
  22616. mesh.computeWorldMatrix(true);
  22617. for (var i = 0; i < rawVerts.length; i += 3) {
  22618. var transformed = BABYLON.Vector3.Zero();
  22619. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22620. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22621. }
  22622. for (var j = 0; j < rawFaces.length; j += 3) {
  22623. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22624. }
  22625. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22626. if (!options) {
  22627. return shape;
  22628. }
  22629. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22630. };
  22631. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22632. var index;
  22633. var mat;
  22634. for (index = 0; index < this._physicsMaterials.length; index++) {
  22635. mat = this._physicsMaterials[index];
  22636. if (mat.friction === friction && mat.restitution === restitution) {
  22637. return mat;
  22638. }
  22639. }
  22640. var currentMat = new CANNON.Material();
  22641. currentMat.friction = friction;
  22642. currentMat.restitution = restitution;
  22643. this._physicsMaterials.push(currentMat);
  22644. for (index = 0; index < this._physicsMaterials.length; index++) {
  22645. mat = this._physicsMaterials[index];
  22646. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22647. contactMaterial.contactEquationStiffness = 1e10;
  22648. contactMaterial.contactEquationRegularizationTime = 10;
  22649. this._world.addContactMaterial(contactMaterial);
  22650. }
  22651. return currentMat;
  22652. };
  22653. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22654. var initialRotation = null;
  22655. if (mesh.rotationQuaternion) {
  22656. initialRotation = mesh.rotationQuaternion.clone();
  22657. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22658. }
  22659. // The delta between the mesh position and the mesh bounding box center
  22660. var bbox = mesh.getBoundingInfo().boundingBox;
  22661. var deltaPosition = mesh.position.subtract(bbox.center);
  22662. var material = this._addMaterial(friction, restitution);
  22663. var body = new CANNON.RigidBody(mass, shape, material);
  22664. if (initialRotation) {
  22665. body.quaternion.x = initialRotation.x;
  22666. body.quaternion.z = initialRotation.y;
  22667. body.quaternion.y = initialRotation.z;
  22668. body.quaternion.w = -initialRotation.w;
  22669. }
  22670. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22671. this._world.add(body);
  22672. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22673. return body;
  22674. };
  22675. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22676. var compoundShape = new CANNON.Compound();
  22677. for (var index = 0; index < parts.length; index++) {
  22678. var mesh = parts[index].mesh;
  22679. var shape = this.registerMesh(mesh, parts[index].impostor);
  22680. if (index == 0) {
  22681. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22682. }
  22683. else {
  22684. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22685. }
  22686. }
  22687. var initialMesh = parts[0].mesh;
  22688. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22689. body.parts = parts;
  22690. return body;
  22691. };
  22692. CannonJSPlugin.prototype._unbindBody = function (body) {
  22693. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22694. var registeredMesh = this._registeredMeshes[index];
  22695. if (registeredMesh.body === body) {
  22696. registeredMesh.body = null;
  22697. registeredMesh.delta = 0;
  22698. }
  22699. }
  22700. };
  22701. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22702. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22703. var registeredMesh = this._registeredMeshes[index];
  22704. if (registeredMesh.mesh === mesh) {
  22705. // Remove body
  22706. if (registeredMesh.body) {
  22707. this._world.remove(registeredMesh.body);
  22708. this._unbindBody(registeredMesh.body);
  22709. }
  22710. this._registeredMeshes.splice(index, 1);
  22711. return;
  22712. }
  22713. }
  22714. };
  22715. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22716. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22717. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22718. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22719. var registeredMesh = this._registeredMeshes[index];
  22720. if (registeredMesh.mesh === mesh) {
  22721. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22722. return;
  22723. }
  22724. }
  22725. };
  22726. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22727. var body1 = null, body2 = null;
  22728. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22729. var registeredMesh = this._registeredMeshes[index];
  22730. if (registeredMesh.mesh === mesh1) {
  22731. body1 = registeredMesh.body;
  22732. }
  22733. else if (registeredMesh.mesh === mesh2) {
  22734. body2 = registeredMesh.body;
  22735. }
  22736. }
  22737. if (!body1 || !body2) {
  22738. return false;
  22739. }
  22740. 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));
  22741. this._world.addConstraint(constraint);
  22742. return true;
  22743. };
  22744. CannonJSPlugin.prototype.dispose = function () {
  22745. while (this._registeredMeshes.length) {
  22746. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22747. }
  22748. };
  22749. CannonJSPlugin.prototype.isSupported = function () {
  22750. return window.CANNON !== undefined;
  22751. };
  22752. return CannonJSPlugin;
  22753. })();
  22754. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22755. })(BABYLON || (BABYLON = {}));
  22756. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22757. var BABYLON;
  22758. (function (BABYLON) {
  22759. var Condition = (function () {
  22760. function Condition(actionManager) {
  22761. this._actionManager = actionManager;
  22762. }
  22763. Condition.prototype.isValid = function () {
  22764. return true;
  22765. };
  22766. Condition.prototype._getProperty = function (propertyPath) {
  22767. return this._actionManager._getProperty(propertyPath);
  22768. };
  22769. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  22770. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22771. };
  22772. return Condition;
  22773. })();
  22774. BABYLON.Condition = Condition;
  22775. var ValueCondition = (function (_super) {
  22776. __extends(ValueCondition, _super);
  22777. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  22778. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  22779. _super.call(this, actionManager);
  22780. this.propertyPath = propertyPath;
  22781. this.value = value;
  22782. this.operator = operator;
  22783. this._target = this._getEffectiveTarget(target, this.propertyPath);
  22784. this._property = this._getProperty(this.propertyPath);
  22785. }
  22786. Object.defineProperty(ValueCondition, "IsEqual", {
  22787. get: function () {
  22788. return ValueCondition._IsEqual;
  22789. },
  22790. enumerable: true,
  22791. configurable: true
  22792. });
  22793. Object.defineProperty(ValueCondition, "IsDifferent", {
  22794. get: function () {
  22795. return ValueCondition._IsDifferent;
  22796. },
  22797. enumerable: true,
  22798. configurable: true
  22799. });
  22800. Object.defineProperty(ValueCondition, "IsGreater", {
  22801. get: function () {
  22802. return ValueCondition._IsGreater;
  22803. },
  22804. enumerable: true,
  22805. configurable: true
  22806. });
  22807. Object.defineProperty(ValueCondition, "IsLesser", {
  22808. get: function () {
  22809. return ValueCondition._IsLesser;
  22810. },
  22811. enumerable: true,
  22812. configurable: true
  22813. });
  22814. // Methods
  22815. ValueCondition.prototype.isValid = function () {
  22816. switch (this.operator) {
  22817. case ValueCondition.IsGreater:
  22818. return this._target[this._property] > this.value;
  22819. case ValueCondition.IsLesser:
  22820. return this._target[this._property] < this.value;
  22821. case ValueCondition.IsEqual:
  22822. case ValueCondition.IsDifferent:
  22823. var check;
  22824. if (this.value.equals) {
  22825. check = this.value.equals(this._target[this._property]);
  22826. }
  22827. else {
  22828. check = this.value === this._target[this._property];
  22829. }
  22830. return this.operator === ValueCondition.IsEqual ? check : !check;
  22831. }
  22832. return false;
  22833. };
  22834. // Statics
  22835. ValueCondition._IsEqual = 0;
  22836. ValueCondition._IsDifferent = 1;
  22837. ValueCondition._IsGreater = 2;
  22838. ValueCondition._IsLesser = 3;
  22839. return ValueCondition;
  22840. })(Condition);
  22841. BABYLON.ValueCondition = ValueCondition;
  22842. var PredicateCondition = (function (_super) {
  22843. __extends(PredicateCondition, _super);
  22844. function PredicateCondition(actionManager, predicate) {
  22845. _super.call(this, actionManager);
  22846. this.predicate = predicate;
  22847. }
  22848. PredicateCondition.prototype.isValid = function () {
  22849. return this.predicate();
  22850. };
  22851. return PredicateCondition;
  22852. })(Condition);
  22853. BABYLON.PredicateCondition = PredicateCondition;
  22854. var StateCondition = (function (_super) {
  22855. __extends(StateCondition, _super);
  22856. function StateCondition(actionManager, target, value) {
  22857. _super.call(this, actionManager);
  22858. this.value = value;
  22859. this._target = target;
  22860. }
  22861. // Methods
  22862. StateCondition.prototype.isValid = function () {
  22863. return this._target.state === this.value;
  22864. };
  22865. return StateCondition;
  22866. })(Condition);
  22867. BABYLON.StateCondition = StateCondition;
  22868. })(BABYLON || (BABYLON = {}));
  22869. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  22870. (function (BABYLON) {
  22871. var Action = (function () {
  22872. function Action(triggerOptions, condition) {
  22873. this.triggerOptions = triggerOptions;
  22874. if (triggerOptions.parameter) {
  22875. this.trigger = triggerOptions.trigger;
  22876. this._triggerParameter = triggerOptions.parameter;
  22877. }
  22878. else {
  22879. this.trigger = triggerOptions;
  22880. }
  22881. this._nextActiveAction = this;
  22882. this._condition = condition;
  22883. }
  22884. // Methods
  22885. Action.prototype._prepare = function () {
  22886. };
  22887. Action.prototype.getTriggerParameter = function () {
  22888. return this._triggerParameter;
  22889. };
  22890. Action.prototype._executeCurrent = function (evt) {
  22891. if (this._condition) {
  22892. var currentRenderId = this._actionManager.getScene().getRenderId();
  22893. // We cache the current evaluation for the current frame
  22894. if (this._condition._evaluationId === currentRenderId) {
  22895. if (!this._condition._currentResult) {
  22896. return;
  22897. }
  22898. }
  22899. else {
  22900. this._condition._evaluationId = currentRenderId;
  22901. if (!this._condition.isValid()) {
  22902. this._condition._currentResult = false;
  22903. return;
  22904. }
  22905. this._condition._currentResult = true;
  22906. }
  22907. }
  22908. this._nextActiveAction.execute(evt);
  22909. if (this._nextActiveAction._child) {
  22910. if (!this._nextActiveAction._child._actionManager) {
  22911. this._nextActiveAction._child._actionManager = this._actionManager;
  22912. }
  22913. this._nextActiveAction = this._nextActiveAction._child;
  22914. }
  22915. else {
  22916. this._nextActiveAction = this;
  22917. }
  22918. };
  22919. Action.prototype.execute = function (evt) {
  22920. };
  22921. Action.prototype.then = function (action) {
  22922. this._child = action;
  22923. action._actionManager = this._actionManager;
  22924. action._prepare();
  22925. return action;
  22926. };
  22927. Action.prototype._getProperty = function (propertyPath) {
  22928. return this._actionManager._getProperty(propertyPath);
  22929. };
  22930. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  22931. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22932. };
  22933. return Action;
  22934. })();
  22935. BABYLON.Action = Action;
  22936. })(BABYLON || (BABYLON = {}));
  22937. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  22938. (function (BABYLON) {
  22939. /**
  22940. * ActionEvent is the event beint sent when an action is triggered.
  22941. */
  22942. var ActionEvent = (function () {
  22943. /**
  22944. * @constructor
  22945. * @param source The mesh that triggered the action.
  22946. * @param pointerX the X mouse cursor position at the time of the event
  22947. * @param pointerY the Y mouse cursor position at the time of the event
  22948. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  22949. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  22950. */
  22951. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  22952. this.source = source;
  22953. this.pointerX = pointerX;
  22954. this.pointerY = pointerY;
  22955. this.meshUnderPointer = meshUnderPointer;
  22956. this.sourceEvent = sourceEvent;
  22957. }
  22958. /**
  22959. * Helper function to auto-create an ActionEvent from a source mesh.
  22960. * @param source the source mesh that triggered the event
  22961. * @param evt {Event} The original (browser) event
  22962. */
  22963. ActionEvent.CreateNew = function (source, evt) {
  22964. var scene = source.getScene();
  22965. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22966. };
  22967. /**
  22968. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  22969. * @param scene the scene where the event occurred
  22970. * @param evt {Event} The original (browser) event
  22971. */
  22972. ActionEvent.CreateNewFromScene = function (scene, evt) {
  22973. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22974. };
  22975. return ActionEvent;
  22976. })();
  22977. BABYLON.ActionEvent = ActionEvent;
  22978. /**
  22979. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  22980. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  22981. */
  22982. var ActionManager = (function () {
  22983. function ActionManager(scene) {
  22984. // Members
  22985. this.actions = new Array();
  22986. this._scene = scene;
  22987. scene._actionManagers.push(this);
  22988. }
  22989. Object.defineProperty(ActionManager, "NothingTrigger", {
  22990. get: function () {
  22991. return ActionManager._NothingTrigger;
  22992. },
  22993. enumerable: true,
  22994. configurable: true
  22995. });
  22996. Object.defineProperty(ActionManager, "OnPickTrigger", {
  22997. get: function () {
  22998. return ActionManager._OnPickTrigger;
  22999. },
  23000. enumerable: true,
  23001. configurable: true
  23002. });
  23003. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  23004. get: function () {
  23005. return ActionManager._OnLeftPickTrigger;
  23006. },
  23007. enumerable: true,
  23008. configurable: true
  23009. });
  23010. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  23011. get: function () {
  23012. return ActionManager._OnRightPickTrigger;
  23013. },
  23014. enumerable: true,
  23015. configurable: true
  23016. });
  23017. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  23018. get: function () {
  23019. return ActionManager._OnCenterPickTrigger;
  23020. },
  23021. enumerable: true,
  23022. configurable: true
  23023. });
  23024. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  23025. get: function () {
  23026. return ActionManager._OnPointerOverTrigger;
  23027. },
  23028. enumerable: true,
  23029. configurable: true
  23030. });
  23031. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  23032. get: function () {
  23033. return ActionManager._OnPointerOutTrigger;
  23034. },
  23035. enumerable: true,
  23036. configurable: true
  23037. });
  23038. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  23039. get: function () {
  23040. return ActionManager._OnEveryFrameTrigger;
  23041. },
  23042. enumerable: true,
  23043. configurable: true
  23044. });
  23045. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  23046. get: function () {
  23047. return ActionManager._OnIntersectionEnterTrigger;
  23048. },
  23049. enumerable: true,
  23050. configurable: true
  23051. });
  23052. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  23053. get: function () {
  23054. return ActionManager._OnIntersectionExitTrigger;
  23055. },
  23056. enumerable: true,
  23057. configurable: true
  23058. });
  23059. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  23060. get: function () {
  23061. return ActionManager._OnKeyDownTrigger;
  23062. },
  23063. enumerable: true,
  23064. configurable: true
  23065. });
  23066. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  23067. get: function () {
  23068. return ActionManager._OnKeyUpTrigger;
  23069. },
  23070. enumerable: true,
  23071. configurable: true
  23072. });
  23073. // Methods
  23074. ActionManager.prototype.dispose = function () {
  23075. var index = this._scene._actionManagers.indexOf(this);
  23076. if (index > -1) {
  23077. this._scene._actionManagers.splice(index, 1);
  23078. }
  23079. };
  23080. ActionManager.prototype.getScene = function () {
  23081. return this._scene;
  23082. };
  23083. /**
  23084. * Does this action manager handles actions of any of the given triggers
  23085. * @param {number[]} triggers - the triggers to be tested
  23086. * @return {boolean} whether one (or more) of the triggers is handeled
  23087. */
  23088. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  23089. for (var index = 0; index < this.actions.length; index++) {
  23090. var action = this.actions[index];
  23091. if (triggers.indexOf(action.trigger) > -1) {
  23092. return true;
  23093. }
  23094. }
  23095. return false;
  23096. };
  23097. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  23098. /**
  23099. * Does this action manager has pointer triggers
  23100. * @return {boolean} whether or not it has pointer triggers
  23101. */
  23102. get: function () {
  23103. for (var index = 0; index < this.actions.length; index++) {
  23104. var action = this.actions[index];
  23105. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  23106. return true;
  23107. }
  23108. }
  23109. return false;
  23110. },
  23111. enumerable: true,
  23112. configurable: true
  23113. });
  23114. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  23115. /**
  23116. * Does this action manager has pick triggers
  23117. * @return {boolean} whether or not it has pick triggers
  23118. */
  23119. get: function () {
  23120. for (var index = 0; index < this.actions.length; index++) {
  23121. var action = this.actions[index];
  23122. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  23123. return true;
  23124. }
  23125. }
  23126. return false;
  23127. },
  23128. enumerable: true,
  23129. configurable: true
  23130. });
  23131. /**
  23132. * Registers an action to this action manager
  23133. * @param {BABYLON.Action} action - the action to be registered
  23134. * @return {BABYLON.Action} the action amended (prepared) after registration
  23135. */
  23136. ActionManager.prototype.registerAction = function (action) {
  23137. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  23138. if (this.getScene().actionManager !== this) {
  23139. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  23140. return null;
  23141. }
  23142. }
  23143. this.actions.push(action);
  23144. action._actionManager = this;
  23145. action._prepare();
  23146. return action;
  23147. };
  23148. /**
  23149. * Process a specific trigger
  23150. * @param {number} trigger - the trigger to process
  23151. * @param evt {BABYLON.ActionEvent} the event details to be processed
  23152. */
  23153. ActionManager.prototype.processTrigger = function (trigger, evt) {
  23154. for (var index = 0; index < this.actions.length; index++) {
  23155. var action = this.actions[index];
  23156. if (action.trigger === trigger) {
  23157. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  23158. var parameter = action.getTriggerParameter();
  23159. if (parameter) {
  23160. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  23161. var actualkey = String.fromCharCode(unicode).toLowerCase();
  23162. if (actualkey !== parameter.toLowerCase()) {
  23163. continue;
  23164. }
  23165. }
  23166. }
  23167. action._executeCurrent(evt);
  23168. }
  23169. }
  23170. };
  23171. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  23172. var properties = propertyPath.split(".");
  23173. for (var index = 0; index < properties.length - 1; index++) {
  23174. target = target[properties[index]];
  23175. }
  23176. return target;
  23177. };
  23178. ActionManager.prototype._getProperty = function (propertyPath) {
  23179. var properties = propertyPath.split(".");
  23180. return properties[properties.length - 1];
  23181. };
  23182. // Statics
  23183. ActionManager._NothingTrigger = 0;
  23184. ActionManager._OnPickTrigger = 1;
  23185. ActionManager._OnLeftPickTrigger = 2;
  23186. ActionManager._OnRightPickTrigger = 3;
  23187. ActionManager._OnCenterPickTrigger = 4;
  23188. ActionManager._OnPointerOverTrigger = 5;
  23189. ActionManager._OnPointerOutTrigger = 6;
  23190. ActionManager._OnEveryFrameTrigger = 7;
  23191. ActionManager._OnIntersectionEnterTrigger = 8;
  23192. ActionManager._OnIntersectionExitTrigger = 9;
  23193. ActionManager._OnKeyDownTrigger = 10;
  23194. ActionManager._OnKeyUpTrigger = 11;
  23195. return ActionManager;
  23196. })();
  23197. BABYLON.ActionManager = ActionManager;
  23198. })(BABYLON || (BABYLON = {}));
  23199. //# sourceMappingURL=babylon.actionManager.js.map
  23200. var BABYLON;
  23201. (function (BABYLON) {
  23202. var InterpolateValueAction = (function (_super) {
  23203. __extends(InterpolateValueAction, _super);
  23204. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  23205. if (duration === void 0) { duration = 1000; }
  23206. _super.call(this, triggerOptions, condition);
  23207. this.propertyPath = propertyPath;
  23208. this.value = value;
  23209. this.duration = duration;
  23210. this.stopOtherAnimations = stopOtherAnimations;
  23211. this._target = target;
  23212. }
  23213. InterpolateValueAction.prototype._prepare = function () {
  23214. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23215. this._property = this._getProperty(this.propertyPath);
  23216. };
  23217. InterpolateValueAction.prototype.execute = function () {
  23218. var scene = this._actionManager.getScene();
  23219. var keys = [
  23220. {
  23221. frame: 0,
  23222. value: this._target[this._property]
  23223. },
  23224. {
  23225. frame: 100,
  23226. value: this.value
  23227. }
  23228. ];
  23229. var dataType;
  23230. if (typeof this.value === "number") {
  23231. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  23232. }
  23233. else if (this.value instanceof BABYLON.Color3) {
  23234. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  23235. }
  23236. else if (this.value instanceof BABYLON.Vector3) {
  23237. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  23238. }
  23239. else if (this.value instanceof BABYLON.Matrix) {
  23240. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  23241. }
  23242. else if (this.value instanceof BABYLON.Quaternion) {
  23243. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  23244. }
  23245. else {
  23246. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  23247. return;
  23248. }
  23249. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  23250. animation.setKeys(keys);
  23251. if (this.stopOtherAnimations) {
  23252. scene.stopAnimation(this._target);
  23253. }
  23254. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  23255. };
  23256. return InterpolateValueAction;
  23257. })(BABYLON.Action);
  23258. BABYLON.InterpolateValueAction = InterpolateValueAction;
  23259. })(BABYLON || (BABYLON = {}));
  23260. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  23261. var BABYLON;
  23262. (function (BABYLON) {
  23263. var SwitchBooleanAction = (function (_super) {
  23264. __extends(SwitchBooleanAction, _super);
  23265. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  23266. _super.call(this, triggerOptions, condition);
  23267. this.propertyPath = propertyPath;
  23268. this._target = target;
  23269. }
  23270. SwitchBooleanAction.prototype._prepare = function () {
  23271. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23272. this._property = this._getProperty(this.propertyPath);
  23273. };
  23274. SwitchBooleanAction.prototype.execute = function () {
  23275. this._target[this._property] = !this._target[this._property];
  23276. };
  23277. return SwitchBooleanAction;
  23278. })(BABYLON.Action);
  23279. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  23280. var SetStateAction = (function (_super) {
  23281. __extends(SetStateAction, _super);
  23282. function SetStateAction(triggerOptions, target, value, condition) {
  23283. _super.call(this, triggerOptions, condition);
  23284. this.value = value;
  23285. this._target = target;
  23286. }
  23287. SetStateAction.prototype.execute = function () {
  23288. this._target.state = this.value;
  23289. };
  23290. return SetStateAction;
  23291. })(BABYLON.Action);
  23292. BABYLON.SetStateAction = SetStateAction;
  23293. var SetValueAction = (function (_super) {
  23294. __extends(SetValueAction, _super);
  23295. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  23296. _super.call(this, triggerOptions, condition);
  23297. this.propertyPath = propertyPath;
  23298. this.value = value;
  23299. this._target = target;
  23300. }
  23301. SetValueAction.prototype._prepare = function () {
  23302. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23303. this._property = this._getProperty(this.propertyPath);
  23304. };
  23305. SetValueAction.prototype.execute = function () {
  23306. this._target[this._property] = this.value;
  23307. };
  23308. return SetValueAction;
  23309. })(BABYLON.Action);
  23310. BABYLON.SetValueAction = SetValueAction;
  23311. var IncrementValueAction = (function (_super) {
  23312. __extends(IncrementValueAction, _super);
  23313. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  23314. _super.call(this, triggerOptions, condition);
  23315. this.propertyPath = propertyPath;
  23316. this.value = value;
  23317. this._target = target;
  23318. }
  23319. IncrementValueAction.prototype._prepare = function () {
  23320. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23321. this._property = this._getProperty(this.propertyPath);
  23322. if (typeof this._target[this._property] !== "number") {
  23323. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  23324. }
  23325. };
  23326. IncrementValueAction.prototype.execute = function () {
  23327. this._target[this._property] += this.value;
  23328. };
  23329. return IncrementValueAction;
  23330. })(BABYLON.Action);
  23331. BABYLON.IncrementValueAction = IncrementValueAction;
  23332. var PlayAnimationAction = (function (_super) {
  23333. __extends(PlayAnimationAction, _super);
  23334. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  23335. _super.call(this, triggerOptions, condition);
  23336. this.from = from;
  23337. this.to = to;
  23338. this.loop = loop;
  23339. this._target = target;
  23340. }
  23341. PlayAnimationAction.prototype._prepare = function () {
  23342. };
  23343. PlayAnimationAction.prototype.execute = function () {
  23344. var scene = this._actionManager.getScene();
  23345. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  23346. };
  23347. return PlayAnimationAction;
  23348. })(BABYLON.Action);
  23349. BABYLON.PlayAnimationAction = PlayAnimationAction;
  23350. var StopAnimationAction = (function (_super) {
  23351. __extends(StopAnimationAction, _super);
  23352. function StopAnimationAction(triggerOptions, target, condition) {
  23353. _super.call(this, triggerOptions, condition);
  23354. this._target = target;
  23355. }
  23356. StopAnimationAction.prototype._prepare = function () {
  23357. };
  23358. StopAnimationAction.prototype.execute = function () {
  23359. var scene = this._actionManager.getScene();
  23360. scene.stopAnimation(this._target);
  23361. };
  23362. return StopAnimationAction;
  23363. })(BABYLON.Action);
  23364. BABYLON.StopAnimationAction = StopAnimationAction;
  23365. var DoNothingAction = (function (_super) {
  23366. __extends(DoNothingAction, _super);
  23367. function DoNothingAction(triggerOptions, condition) {
  23368. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  23369. _super.call(this, triggerOptions, condition);
  23370. }
  23371. DoNothingAction.prototype.execute = function () {
  23372. };
  23373. return DoNothingAction;
  23374. })(BABYLON.Action);
  23375. BABYLON.DoNothingAction = DoNothingAction;
  23376. var CombineAction = (function (_super) {
  23377. __extends(CombineAction, _super);
  23378. function CombineAction(triggerOptions, children, condition) {
  23379. _super.call(this, triggerOptions, condition);
  23380. this.children = children;
  23381. }
  23382. CombineAction.prototype._prepare = function () {
  23383. for (var index = 0; index < this.children.length; index++) {
  23384. this.children[index]._actionManager = this._actionManager;
  23385. this.children[index]._prepare();
  23386. }
  23387. };
  23388. CombineAction.prototype.execute = function (evt) {
  23389. for (var index = 0; index < this.children.length; index++) {
  23390. this.children[index].execute(evt);
  23391. }
  23392. };
  23393. return CombineAction;
  23394. })(BABYLON.Action);
  23395. BABYLON.CombineAction = CombineAction;
  23396. var ExecuteCodeAction = (function (_super) {
  23397. __extends(ExecuteCodeAction, _super);
  23398. function ExecuteCodeAction(triggerOptions, func, condition) {
  23399. _super.call(this, triggerOptions, condition);
  23400. this.func = func;
  23401. }
  23402. ExecuteCodeAction.prototype.execute = function (evt) {
  23403. this.func(evt);
  23404. };
  23405. return ExecuteCodeAction;
  23406. })(BABYLON.Action);
  23407. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  23408. var SetParentAction = (function (_super) {
  23409. __extends(SetParentAction, _super);
  23410. function SetParentAction(triggerOptions, target, parent, condition) {
  23411. _super.call(this, triggerOptions, condition);
  23412. this._target = target;
  23413. this._parent = parent;
  23414. }
  23415. SetParentAction.prototype._prepare = function () {
  23416. };
  23417. SetParentAction.prototype.execute = function () {
  23418. if (this._target.parent === this._parent) {
  23419. return;
  23420. }
  23421. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  23422. invertParentWorldMatrix.invert();
  23423. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  23424. this._target.parent = this._parent;
  23425. };
  23426. return SetParentAction;
  23427. })(BABYLON.Action);
  23428. BABYLON.SetParentAction = SetParentAction;
  23429. })(BABYLON || (BABYLON = {}));
  23430. //# sourceMappingURL=babylon.directActions.js.map
  23431. var BABYLON;
  23432. (function (BABYLON) {
  23433. var Geometry = (function () {
  23434. function Geometry(id, scene, vertexData, updatable, mesh) {
  23435. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23436. this._totalVertices = 0;
  23437. this._indices = [];
  23438. this.id = id;
  23439. this._engine = scene.getEngine();
  23440. this._meshes = [];
  23441. this._scene = scene;
  23442. // vertexData
  23443. if (vertexData) {
  23444. this.setAllVerticesData(vertexData, updatable);
  23445. }
  23446. else {
  23447. this._totalVertices = 0;
  23448. this._indices = [];
  23449. }
  23450. // applyToMesh
  23451. if (mesh) {
  23452. this.applyToMesh(mesh);
  23453. }
  23454. }
  23455. Geometry.prototype.getScene = function () {
  23456. return this._scene;
  23457. };
  23458. Geometry.prototype.getEngine = function () {
  23459. return this._engine;
  23460. };
  23461. Geometry.prototype.isReady = function () {
  23462. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  23463. };
  23464. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  23465. vertexData.applyToGeometry(this, updatable);
  23466. };
  23467. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23468. this._vertexBuffers = this._vertexBuffers || {};
  23469. if (this._vertexBuffers[kind]) {
  23470. this._vertexBuffers[kind].dispose();
  23471. }
  23472. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  23473. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23474. stride = this._vertexBuffers[kind].getStrideSize();
  23475. this._totalVertices = data.length / stride;
  23476. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23477. var meshes = this._meshes;
  23478. var numOfMeshes = meshes.length;
  23479. for (var index = 0; index < numOfMeshes; index++) {
  23480. var mesh = meshes[index];
  23481. mesh._resetPointsArrayCache();
  23482. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23483. mesh._createGlobalSubMesh();
  23484. mesh.computeWorldMatrix(true);
  23485. }
  23486. }
  23487. };
  23488. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  23489. var vertexBuffer = this.getVertexBuffer(kind);
  23490. if (!vertexBuffer) {
  23491. return;
  23492. }
  23493. vertexBuffer.updateDirectly(data, offset);
  23494. };
  23495. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  23496. var vertexBuffer = this.getVertexBuffer(kind);
  23497. if (!vertexBuffer) {
  23498. return;
  23499. }
  23500. vertexBuffer.update(data);
  23501. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23502. var extend;
  23503. var stride = vertexBuffer.getStrideSize();
  23504. this._totalVertices = data.length / stride;
  23505. if (updateExtends) {
  23506. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23507. }
  23508. var meshes = this._meshes;
  23509. var numOfMeshes = meshes.length;
  23510. for (var index = 0; index < numOfMeshes; index++) {
  23511. var mesh = meshes[index];
  23512. mesh._resetPointsArrayCache();
  23513. if (updateExtends) {
  23514. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23515. }
  23516. }
  23517. }
  23518. };
  23519. Geometry.prototype.getTotalVertices = function () {
  23520. if (!this.isReady()) {
  23521. return 0;
  23522. }
  23523. return this._totalVertices;
  23524. };
  23525. Geometry.prototype.getVerticesData = function (kind) {
  23526. var vertexBuffer = this.getVertexBuffer(kind);
  23527. if (!vertexBuffer) {
  23528. return null;
  23529. }
  23530. return vertexBuffer.getData();
  23531. };
  23532. Geometry.prototype.getVertexBuffer = function (kind) {
  23533. if (!this.isReady()) {
  23534. return null;
  23535. }
  23536. return this._vertexBuffers[kind];
  23537. };
  23538. Geometry.prototype.getVertexBuffers = function () {
  23539. if (!this.isReady()) {
  23540. return null;
  23541. }
  23542. return this._vertexBuffers;
  23543. };
  23544. Geometry.prototype.isVerticesDataPresent = function (kind) {
  23545. if (!this._vertexBuffers) {
  23546. if (this._delayInfo) {
  23547. return this._delayInfo.indexOf(kind) !== -1;
  23548. }
  23549. return false;
  23550. }
  23551. return this._vertexBuffers[kind] !== undefined;
  23552. };
  23553. Geometry.prototype.getVerticesDataKinds = function () {
  23554. var result = [];
  23555. if (!this._vertexBuffers && this._delayInfo) {
  23556. for (var kind in this._delayInfo) {
  23557. result.push(kind);
  23558. }
  23559. }
  23560. else {
  23561. for (kind in this._vertexBuffers) {
  23562. result.push(kind);
  23563. }
  23564. }
  23565. return result;
  23566. };
  23567. Geometry.prototype.setIndices = function (indices, totalVertices) {
  23568. if (this._indexBuffer) {
  23569. this._engine._releaseBuffer(this._indexBuffer);
  23570. }
  23571. this._indices = indices;
  23572. if (this._meshes.length !== 0 && this._indices) {
  23573. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23574. }
  23575. if (totalVertices !== undefined) {
  23576. this._totalVertices = totalVertices;
  23577. }
  23578. var meshes = this._meshes;
  23579. var numOfMeshes = meshes.length;
  23580. for (var index = 0; index < numOfMeshes; index++) {
  23581. meshes[index]._createGlobalSubMesh();
  23582. }
  23583. };
  23584. Geometry.prototype.getTotalIndices = function () {
  23585. if (!this.isReady()) {
  23586. return 0;
  23587. }
  23588. return this._indices.length;
  23589. };
  23590. Geometry.prototype.getIndices = function () {
  23591. if (!this.isReady()) {
  23592. return null;
  23593. }
  23594. return this._indices;
  23595. };
  23596. Geometry.prototype.getIndexBuffer = function () {
  23597. if (!this.isReady()) {
  23598. return null;
  23599. }
  23600. return this._indexBuffer;
  23601. };
  23602. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  23603. var meshes = this._meshes;
  23604. var index = meshes.indexOf(mesh);
  23605. if (index === -1) {
  23606. return;
  23607. }
  23608. for (var kind in this._vertexBuffers) {
  23609. this._vertexBuffers[kind].dispose();
  23610. }
  23611. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  23612. this._indexBuffer = null;
  23613. }
  23614. meshes.splice(index, 1);
  23615. mesh._geometry = null;
  23616. if (meshes.length === 0 && shouldDispose) {
  23617. this.dispose();
  23618. }
  23619. };
  23620. Geometry.prototype.applyToMesh = function (mesh) {
  23621. if (mesh._geometry === this) {
  23622. return;
  23623. }
  23624. var previousGeometry = mesh._geometry;
  23625. if (previousGeometry) {
  23626. previousGeometry.releaseForMesh(mesh);
  23627. }
  23628. var meshes = this._meshes;
  23629. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  23630. mesh._geometry = this;
  23631. this._scene.pushGeometry(this);
  23632. meshes.push(mesh);
  23633. if (this.isReady()) {
  23634. this._applyToMesh(mesh);
  23635. }
  23636. else {
  23637. mesh._boundingInfo = this._boundingInfo;
  23638. }
  23639. };
  23640. Geometry.prototype._applyToMesh = function (mesh) {
  23641. var numOfMeshes = this._meshes.length;
  23642. for (var kind in this._vertexBuffers) {
  23643. if (numOfMeshes === 1) {
  23644. this._vertexBuffers[kind].create();
  23645. }
  23646. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  23647. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23648. mesh._resetPointsArrayCache();
  23649. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  23650. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23651. mesh._createGlobalSubMesh();
  23652. //bounding info was just created again, world matrix should be applied again.
  23653. mesh._updateBoundingInfo();
  23654. }
  23655. }
  23656. // indexBuffer
  23657. if (numOfMeshes === 1 && this._indices) {
  23658. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23659. }
  23660. if (this._indexBuffer) {
  23661. this._indexBuffer.references = numOfMeshes;
  23662. }
  23663. };
  23664. Geometry.prototype.load = function (scene, onLoaded) {
  23665. var _this = this;
  23666. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23667. return;
  23668. }
  23669. if (this.isReady()) {
  23670. if (onLoaded) {
  23671. onLoaded();
  23672. }
  23673. return;
  23674. }
  23675. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23676. scene._addPendingData(this);
  23677. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23678. _this._delayLoadingFunction(JSON.parse(data), _this);
  23679. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23680. _this._delayInfo = [];
  23681. scene._removePendingData(_this);
  23682. var meshes = _this._meshes;
  23683. var numOfMeshes = meshes.length;
  23684. for (var index = 0; index < numOfMeshes; index++) {
  23685. _this._applyToMesh(meshes[index]);
  23686. }
  23687. if (onLoaded) {
  23688. onLoaded();
  23689. }
  23690. }, function () {
  23691. }, scene.database);
  23692. };
  23693. Geometry.prototype.dispose = function () {
  23694. var meshes = this._meshes;
  23695. var numOfMeshes = meshes.length;
  23696. var index;
  23697. for (index = 0; index < numOfMeshes; index++) {
  23698. this.releaseForMesh(meshes[index]);
  23699. }
  23700. this._meshes = [];
  23701. for (var kind in this._vertexBuffers) {
  23702. this._vertexBuffers[kind].dispose();
  23703. }
  23704. this._vertexBuffers = [];
  23705. this._totalVertices = 0;
  23706. if (this._indexBuffer) {
  23707. this._engine._releaseBuffer(this._indexBuffer);
  23708. }
  23709. this._indexBuffer = null;
  23710. this._indices = [];
  23711. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23712. this.delayLoadingFile = null;
  23713. this._delayLoadingFunction = null;
  23714. this._delayInfo = [];
  23715. this._boundingInfo = null; // todo: .dispose()
  23716. var geometries = this._scene.getGeometries();
  23717. index = geometries.indexOf(this);
  23718. if (index > -1) {
  23719. geometries.splice(index, 1);
  23720. }
  23721. };
  23722. Geometry.prototype.copy = function (id) {
  23723. var vertexData = new BABYLON.VertexData();
  23724. vertexData.indices = [];
  23725. var indices = this.getIndices();
  23726. for (var index = 0; index < indices.length; index++) {
  23727. vertexData.indices.push(indices[index]);
  23728. }
  23729. var updatable = false;
  23730. var stopChecking = false;
  23731. for (var kind in this._vertexBuffers) {
  23732. vertexData.set(this.getVerticesData(kind), kind);
  23733. if (!stopChecking) {
  23734. updatable = this.getVertexBuffer(kind).isUpdatable();
  23735. stopChecking = !updatable;
  23736. }
  23737. }
  23738. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  23739. geometry.delayLoadState = this.delayLoadState;
  23740. geometry.delayLoadingFile = this.delayLoadingFile;
  23741. geometry._delayLoadingFunction = this._delayLoadingFunction;
  23742. for (kind in this._delayInfo) {
  23743. geometry._delayInfo = geometry._delayInfo || [];
  23744. geometry._delayInfo.push(kind);
  23745. }
  23746. // Bounding info
  23747. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  23748. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23749. return geometry;
  23750. };
  23751. // Statics
  23752. Geometry.ExtractFromMesh = function (mesh, id) {
  23753. var geometry = mesh._geometry;
  23754. if (!geometry) {
  23755. return null;
  23756. }
  23757. return geometry.copy(id);
  23758. };
  23759. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  23760. // be aware Math.random() could cause collisions
  23761. Geometry.RandomId = function () {
  23762. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  23763. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  23764. return v.toString(16);
  23765. });
  23766. };
  23767. return Geometry;
  23768. })();
  23769. BABYLON.Geometry = Geometry;
  23770. /////// Primitives //////////////////////////////////////////////
  23771. var Geometry;
  23772. (function (Geometry) {
  23773. var Primitives;
  23774. (function (Primitives) {
  23775. /// Abstract class
  23776. var _Primitive = (function (_super) {
  23777. __extends(_Primitive, _super);
  23778. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  23779. this._beingRegenerated = true;
  23780. this._canBeRegenerated = canBeRegenerated;
  23781. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  23782. this._beingRegenerated = false;
  23783. }
  23784. _Primitive.prototype.canBeRegenerated = function () {
  23785. return this._canBeRegenerated;
  23786. };
  23787. _Primitive.prototype.regenerate = function () {
  23788. if (!this._canBeRegenerated) {
  23789. return;
  23790. }
  23791. this._beingRegenerated = true;
  23792. this.setAllVerticesData(this._regenerateVertexData(), false);
  23793. this._beingRegenerated = false;
  23794. };
  23795. _Primitive.prototype.asNewGeometry = function (id) {
  23796. return _super.prototype.copy.call(this, id);
  23797. };
  23798. // overrides
  23799. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  23800. if (!this._beingRegenerated) {
  23801. return;
  23802. }
  23803. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  23804. };
  23805. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  23806. if (!this._beingRegenerated) {
  23807. return;
  23808. }
  23809. _super.prototype.setVerticesData.call(this, kind, data, false);
  23810. };
  23811. // to override
  23812. // protected
  23813. _Primitive.prototype._regenerateVertexData = function () {
  23814. throw new Error("Abstract method");
  23815. };
  23816. _Primitive.prototype.copy = function (id) {
  23817. throw new Error("Must be overriden in sub-classes.");
  23818. };
  23819. return _Primitive;
  23820. })(Geometry);
  23821. Primitives._Primitive = _Primitive;
  23822. var Box = (function (_super) {
  23823. __extends(Box, _super);
  23824. function Box(id, scene, size, canBeRegenerated, mesh) {
  23825. this.size = size;
  23826. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23827. }
  23828. Box.prototype._regenerateVertexData = function () {
  23829. return BABYLON.VertexData.CreateBox(this.size);
  23830. };
  23831. Box.prototype.copy = function (id) {
  23832. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23833. };
  23834. return Box;
  23835. })(_Primitive);
  23836. Primitives.Box = Box;
  23837. var Sphere = (function (_super) {
  23838. __extends(Sphere, _super);
  23839. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  23840. this.segments = segments;
  23841. this.diameter = diameter;
  23842. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23843. }
  23844. Sphere.prototype._regenerateVertexData = function () {
  23845. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  23846. };
  23847. Sphere.prototype.copy = function (id) {
  23848. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  23849. };
  23850. return Sphere;
  23851. })(_Primitive);
  23852. Primitives.Sphere = Sphere;
  23853. var Cylinder = (function (_super) {
  23854. __extends(Cylinder, _super);
  23855. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  23856. if (subdivisions === void 0) { subdivisions = 1; }
  23857. this.height = height;
  23858. this.diameterTop = diameterTop;
  23859. this.diameterBottom = diameterBottom;
  23860. this.tessellation = tessellation;
  23861. this.subdivisions = subdivisions;
  23862. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23863. }
  23864. Cylinder.prototype._regenerateVertexData = function () {
  23865. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  23866. };
  23867. Cylinder.prototype.copy = function (id) {
  23868. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  23869. };
  23870. return Cylinder;
  23871. })(_Primitive);
  23872. Primitives.Cylinder = Cylinder;
  23873. var Torus = (function (_super) {
  23874. __extends(Torus, _super);
  23875. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  23876. this.diameter = diameter;
  23877. this.thickness = thickness;
  23878. this.tessellation = tessellation;
  23879. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23880. }
  23881. Torus.prototype._regenerateVertexData = function () {
  23882. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  23883. };
  23884. Torus.prototype.copy = function (id) {
  23885. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  23886. };
  23887. return Torus;
  23888. })(_Primitive);
  23889. Primitives.Torus = Torus;
  23890. var Ground = (function (_super) {
  23891. __extends(Ground, _super);
  23892. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  23893. this.width = width;
  23894. this.height = height;
  23895. this.subdivisions = subdivisions;
  23896. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23897. }
  23898. Ground.prototype._regenerateVertexData = function () {
  23899. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  23900. };
  23901. Ground.prototype.copy = function (id) {
  23902. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  23903. };
  23904. return Ground;
  23905. })(_Primitive);
  23906. Primitives.Ground = Ground;
  23907. var TiledGround = (function (_super) {
  23908. __extends(TiledGround, _super);
  23909. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  23910. this.xmin = xmin;
  23911. this.zmin = zmin;
  23912. this.xmax = xmax;
  23913. this.zmax = zmax;
  23914. this.subdivisions = subdivisions;
  23915. this.precision = precision;
  23916. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23917. }
  23918. TiledGround.prototype._regenerateVertexData = function () {
  23919. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  23920. };
  23921. TiledGround.prototype.copy = function (id) {
  23922. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  23923. };
  23924. return TiledGround;
  23925. })(_Primitive);
  23926. Primitives.TiledGround = TiledGround;
  23927. var Plane = (function (_super) {
  23928. __extends(Plane, _super);
  23929. function Plane(id, scene, size, canBeRegenerated, mesh) {
  23930. this.size = size;
  23931. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23932. }
  23933. Plane.prototype._regenerateVertexData = function () {
  23934. return BABYLON.VertexData.CreatePlane(this.size);
  23935. };
  23936. Plane.prototype.copy = function (id) {
  23937. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23938. };
  23939. return Plane;
  23940. })(_Primitive);
  23941. Primitives.Plane = Plane;
  23942. var TorusKnot = (function (_super) {
  23943. __extends(TorusKnot, _super);
  23944. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  23945. this.radius = radius;
  23946. this.tube = tube;
  23947. this.radialSegments = radialSegments;
  23948. this.tubularSegments = tubularSegments;
  23949. this.p = p;
  23950. this.q = q;
  23951. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23952. }
  23953. TorusKnot.prototype._regenerateVertexData = function () {
  23954. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  23955. };
  23956. TorusKnot.prototype.copy = function (id) {
  23957. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  23958. };
  23959. return TorusKnot;
  23960. })(_Primitive);
  23961. Primitives.TorusKnot = TorusKnot;
  23962. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  23963. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  23964. })(BABYLON || (BABYLON = {}));
  23965. //# sourceMappingURL=babylon.geometry.js.map
  23966. var BABYLON;
  23967. (function (BABYLON) {
  23968. var Gamepads = (function () {
  23969. function Gamepads(ongamedpadconnected) {
  23970. var _this = this;
  23971. this.babylonGamepads = [];
  23972. this.oneGamepadConnected = false;
  23973. this.isMonitoring = false;
  23974. this.gamepadEventSupported = 'GamepadEvent' in window;
  23975. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  23976. 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=";
  23977. this._callbackGamepadConnected = ongamedpadconnected;
  23978. if (this.gamepadSupportAvailable) {
  23979. // Checking if the gamepad connected event is supported (like in Firefox)
  23980. if (this.gamepadEventSupported) {
  23981. window.addEventListener('gamepadconnected', function (evt) {
  23982. _this._onGamepadConnected(evt);
  23983. }, false);
  23984. window.addEventListener('gamepaddisconnected', function (evt) {
  23985. _this._onGamepadDisconnected(evt);
  23986. }, false);
  23987. }
  23988. else {
  23989. this._startMonitoringGamepads();
  23990. }
  23991. if (!this.oneGamepadConnected) {
  23992. this._insertGamepadDOMInstructions();
  23993. }
  23994. }
  23995. else {
  23996. this._insertGamepadDOMNotSupported();
  23997. }
  23998. }
  23999. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  24000. Gamepads.gamepadDOMInfo = document.createElement("div");
  24001. var buttonAImage = document.createElement("img");
  24002. buttonAImage.src = this.buttonADataURL;
  24003. var spanMessage = document.createElement("span");
  24004. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  24005. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  24006. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24007. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24008. Gamepads.gamepadDOMInfo.style.width = "100%";
  24009. Gamepads.gamepadDOMInfo.style.height = "48px";
  24010. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24011. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24012. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24013. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24014. buttonAImage.style.position = "relative";
  24015. buttonAImage.style.bottom = "8px";
  24016. spanMessage.style.position = "relative";
  24017. spanMessage.style.fontSize = "32px";
  24018. spanMessage.style.bottom = "32px";
  24019. spanMessage.style.color = "green";
  24020. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24021. };
  24022. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  24023. Gamepads.gamepadDOMInfo = document.createElement("div");
  24024. var spanMessage = document.createElement("span");
  24025. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  24026. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24027. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24028. Gamepads.gamepadDOMInfo.style.width = "100%";
  24029. Gamepads.gamepadDOMInfo.style.height = "40px";
  24030. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24031. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24032. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24033. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24034. spanMessage.style.position = "relative";
  24035. spanMessage.style.fontSize = "32px";
  24036. spanMessage.style.color = "red";
  24037. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24038. };
  24039. Gamepads.prototype.dispose = function () {
  24040. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24041. };
  24042. Gamepads.prototype._onGamepadConnected = function (evt) {
  24043. var newGamepad = this._addNewGamepad(evt.gamepad);
  24044. if (this._callbackGamepadConnected)
  24045. this._callbackGamepadConnected(newGamepad);
  24046. this._startMonitoringGamepads();
  24047. };
  24048. Gamepads.prototype._addNewGamepad = function (gamepad) {
  24049. if (!this.oneGamepadConnected) {
  24050. this.oneGamepadConnected = true;
  24051. if (Gamepads.gamepadDOMInfo) {
  24052. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24053. Gamepads.gamepadDOMInfo = null;
  24054. }
  24055. }
  24056. var newGamepad;
  24057. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  24058. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  24059. }
  24060. else {
  24061. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  24062. }
  24063. this.babylonGamepads.push(newGamepad);
  24064. return newGamepad;
  24065. };
  24066. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  24067. for (var i in this.babylonGamepads) {
  24068. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  24069. this.babylonGamepads.splice(i, 1);
  24070. break;
  24071. }
  24072. }
  24073. // If no gamepads are left, stop the polling loop.
  24074. if (this.babylonGamepads.length == 0) {
  24075. this._stopMonitoringGamepads();
  24076. }
  24077. };
  24078. Gamepads.prototype._startMonitoringGamepads = function () {
  24079. if (!this.isMonitoring) {
  24080. this.isMonitoring = true;
  24081. this._checkGamepadsStatus();
  24082. }
  24083. };
  24084. Gamepads.prototype._stopMonitoringGamepads = function () {
  24085. this.isMonitoring = false;
  24086. };
  24087. Gamepads.prototype._checkGamepadsStatus = function () {
  24088. var _this = this;
  24089. // updating gamepad objects
  24090. this._updateGamepadObjects();
  24091. for (var i in this.babylonGamepads) {
  24092. this.babylonGamepads[i].update();
  24093. }
  24094. if (this.isMonitoring) {
  24095. if (window.requestAnimationFrame) {
  24096. window.requestAnimationFrame(function () {
  24097. _this._checkGamepadsStatus();
  24098. });
  24099. }
  24100. else if (window.mozRequestAnimationFrame) {
  24101. window.mozRequestAnimationFrame(function () {
  24102. _this._checkGamepadsStatus();
  24103. });
  24104. }
  24105. else if (window.webkitRequestAnimationFrame) {
  24106. window.webkitRequestAnimationFrame(function () {
  24107. _this._checkGamepadsStatus();
  24108. });
  24109. }
  24110. }
  24111. };
  24112. // This function is called only on Chrome, which does not yet support
  24113. // connection/disconnection events, but requires you to monitor
  24114. // an array for changes.
  24115. Gamepads.prototype._updateGamepadObjects = function () {
  24116. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  24117. for (var i = 0; i < gamepads.length; i++) {
  24118. if (gamepads[i]) {
  24119. if (!(gamepads[i].index in this.babylonGamepads)) {
  24120. var newGamepad = this._addNewGamepad(gamepads[i]);
  24121. if (this._callbackGamepadConnected) {
  24122. this._callbackGamepadConnected(newGamepad);
  24123. }
  24124. }
  24125. else {
  24126. this.babylonGamepads[i].browserGamepad = gamepads[i];
  24127. }
  24128. }
  24129. }
  24130. };
  24131. return Gamepads;
  24132. })();
  24133. BABYLON.Gamepads = Gamepads;
  24134. var StickValues = (function () {
  24135. function StickValues(x, y) {
  24136. this.x = x;
  24137. this.y = y;
  24138. }
  24139. return StickValues;
  24140. })();
  24141. BABYLON.StickValues = StickValues;
  24142. var Gamepad = (function () {
  24143. function Gamepad(id, index, browserGamepad) {
  24144. this.id = id;
  24145. this.index = index;
  24146. this.browserGamepad = browserGamepad;
  24147. if (this.browserGamepad.axes.length >= 2) {
  24148. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24149. }
  24150. if (this.browserGamepad.axes.length >= 4) {
  24151. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24152. }
  24153. }
  24154. Gamepad.prototype.onleftstickchanged = function (callback) {
  24155. this._onleftstickchanged = callback;
  24156. };
  24157. Gamepad.prototype.onrightstickchanged = function (callback) {
  24158. this._onrightstickchanged = callback;
  24159. };
  24160. Object.defineProperty(Gamepad.prototype, "leftStick", {
  24161. get: function () {
  24162. return this._leftStick;
  24163. },
  24164. set: function (newValues) {
  24165. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  24166. this._onleftstickchanged(newValues);
  24167. }
  24168. this._leftStick = newValues;
  24169. },
  24170. enumerable: true,
  24171. configurable: true
  24172. });
  24173. Object.defineProperty(Gamepad.prototype, "rightStick", {
  24174. get: function () {
  24175. return this._rightStick;
  24176. },
  24177. set: function (newValues) {
  24178. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  24179. this._onrightstickchanged(newValues);
  24180. }
  24181. this._rightStick = newValues;
  24182. },
  24183. enumerable: true,
  24184. configurable: true
  24185. });
  24186. Gamepad.prototype.update = function () {
  24187. if (this._leftStick) {
  24188. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24189. }
  24190. if (this._rightStick) {
  24191. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24192. }
  24193. };
  24194. return Gamepad;
  24195. })();
  24196. BABYLON.Gamepad = Gamepad;
  24197. var GenericPad = (function (_super) {
  24198. __extends(GenericPad, _super);
  24199. function GenericPad(id, index, gamepad) {
  24200. _super.call(this, id, index, gamepad);
  24201. this.id = id;
  24202. this.index = index;
  24203. this.gamepad = gamepad;
  24204. this._buttons = new Array(gamepad.buttons.length);
  24205. }
  24206. GenericPad.prototype.onbuttondown = function (callback) {
  24207. this._onbuttondown = callback;
  24208. };
  24209. GenericPad.prototype.onbuttonup = function (callback) {
  24210. this._onbuttonup = callback;
  24211. };
  24212. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  24213. if (newValue !== currentValue) {
  24214. if (this._onbuttondown && newValue === 1) {
  24215. this._onbuttondown(buttonIndex);
  24216. }
  24217. if (this._onbuttonup && newValue === 0) {
  24218. this._onbuttonup(buttonIndex);
  24219. }
  24220. }
  24221. return newValue;
  24222. };
  24223. GenericPad.prototype.update = function () {
  24224. _super.prototype.update.call(this);
  24225. for (var index = 0; index < this._buttons.length; index++) {
  24226. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  24227. }
  24228. };
  24229. return GenericPad;
  24230. })(Gamepad);
  24231. BABYLON.GenericPad = GenericPad;
  24232. (function (Xbox360Button) {
  24233. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  24234. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  24235. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  24236. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  24237. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  24238. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  24239. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  24240. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  24241. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  24242. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  24243. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  24244. var Xbox360Button = BABYLON.Xbox360Button;
  24245. (function (Xbox360Dpad) {
  24246. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  24247. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  24248. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  24249. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  24250. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  24251. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  24252. var Xbox360Pad = (function (_super) {
  24253. __extends(Xbox360Pad, _super);
  24254. function Xbox360Pad() {
  24255. _super.apply(this, arguments);
  24256. this._leftTrigger = 0;
  24257. this._rightTrigger = 0;
  24258. this._buttonA = 0;
  24259. this._buttonB = 0;
  24260. this._buttonX = 0;
  24261. this._buttonY = 0;
  24262. this._buttonBack = 0;
  24263. this._buttonStart = 0;
  24264. this._buttonLB = 0;
  24265. this._buttonRB = 0;
  24266. this._buttonLeftStick = 0;
  24267. this._buttonRightStick = 0;
  24268. this._dPadUp = 0;
  24269. this._dPadDown = 0;
  24270. this._dPadLeft = 0;
  24271. this._dPadRight = 0;
  24272. }
  24273. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  24274. this._onlefttriggerchanged = callback;
  24275. };
  24276. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  24277. this._onrighttriggerchanged = callback;
  24278. };
  24279. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  24280. get: function () {
  24281. return this._leftTrigger;
  24282. },
  24283. set: function (newValue) {
  24284. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  24285. this._onlefttriggerchanged(newValue);
  24286. }
  24287. this._leftTrigger = newValue;
  24288. },
  24289. enumerable: true,
  24290. configurable: true
  24291. });
  24292. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  24293. get: function () {
  24294. return this._rightTrigger;
  24295. },
  24296. set: function (newValue) {
  24297. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  24298. this._onrighttriggerchanged(newValue);
  24299. }
  24300. this._rightTrigger = newValue;
  24301. },
  24302. enumerable: true,
  24303. configurable: true
  24304. });
  24305. Xbox360Pad.prototype.onbuttondown = function (callback) {
  24306. this._onbuttondown = callback;
  24307. };
  24308. Xbox360Pad.prototype.onbuttonup = function (callback) {
  24309. this._onbuttonup = callback;
  24310. };
  24311. Xbox360Pad.prototype.ondpaddown = function (callback) {
  24312. this._ondpaddown = callback;
  24313. };
  24314. Xbox360Pad.prototype.ondpadup = function (callback) {
  24315. this._ondpadup = callback;
  24316. };
  24317. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  24318. if (newValue !== currentValue) {
  24319. if (this._onbuttondown && newValue === 1) {
  24320. this._onbuttondown(buttonType);
  24321. }
  24322. if (this._onbuttonup && newValue === 0) {
  24323. this._onbuttonup(buttonType);
  24324. }
  24325. }
  24326. return newValue;
  24327. };
  24328. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  24329. if (newValue !== currentValue) {
  24330. if (this._ondpaddown && newValue === 1) {
  24331. this._ondpaddown(buttonType);
  24332. }
  24333. if (this._ondpadup && newValue === 0) {
  24334. this._ondpadup(buttonType);
  24335. }
  24336. }
  24337. return newValue;
  24338. };
  24339. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  24340. get: function () {
  24341. return this._buttonA;
  24342. },
  24343. set: function (value) {
  24344. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  24345. },
  24346. enumerable: true,
  24347. configurable: true
  24348. });
  24349. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  24350. get: function () {
  24351. return this._buttonB;
  24352. },
  24353. set: function (value) {
  24354. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  24355. },
  24356. enumerable: true,
  24357. configurable: true
  24358. });
  24359. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  24360. get: function () {
  24361. return this._buttonX;
  24362. },
  24363. set: function (value) {
  24364. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  24365. },
  24366. enumerable: true,
  24367. configurable: true
  24368. });
  24369. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  24370. get: function () {
  24371. return this._buttonY;
  24372. },
  24373. set: function (value) {
  24374. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  24375. },
  24376. enumerable: true,
  24377. configurable: true
  24378. });
  24379. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  24380. get: function () {
  24381. return this._buttonStart;
  24382. },
  24383. set: function (value) {
  24384. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  24385. },
  24386. enumerable: true,
  24387. configurable: true
  24388. });
  24389. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  24390. get: function () {
  24391. return this._buttonBack;
  24392. },
  24393. set: function (value) {
  24394. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  24395. },
  24396. enumerable: true,
  24397. configurable: true
  24398. });
  24399. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  24400. get: function () {
  24401. return this._buttonLB;
  24402. },
  24403. set: function (value) {
  24404. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  24405. },
  24406. enumerable: true,
  24407. configurable: true
  24408. });
  24409. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  24410. get: function () {
  24411. return this._buttonRB;
  24412. },
  24413. set: function (value) {
  24414. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  24415. },
  24416. enumerable: true,
  24417. configurable: true
  24418. });
  24419. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  24420. get: function () {
  24421. return this._buttonLeftStick;
  24422. },
  24423. set: function (value) {
  24424. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  24425. },
  24426. enumerable: true,
  24427. configurable: true
  24428. });
  24429. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  24430. get: function () {
  24431. return this._buttonRightStick;
  24432. },
  24433. set: function (value) {
  24434. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  24435. },
  24436. enumerable: true,
  24437. configurable: true
  24438. });
  24439. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  24440. get: function () {
  24441. return this._dPadUp;
  24442. },
  24443. set: function (value) {
  24444. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  24445. },
  24446. enumerable: true,
  24447. configurable: true
  24448. });
  24449. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  24450. get: function () {
  24451. return this._dPadDown;
  24452. },
  24453. set: function (value) {
  24454. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  24455. },
  24456. enumerable: true,
  24457. configurable: true
  24458. });
  24459. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  24460. get: function () {
  24461. return this._dPadLeft;
  24462. },
  24463. set: function (value) {
  24464. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  24465. },
  24466. enumerable: true,
  24467. configurable: true
  24468. });
  24469. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  24470. get: function () {
  24471. return this._dPadRight;
  24472. },
  24473. set: function (value) {
  24474. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  24475. },
  24476. enumerable: true,
  24477. configurable: true
  24478. });
  24479. Xbox360Pad.prototype.update = function () {
  24480. _super.prototype.update.call(this);
  24481. this.buttonA = this.browserGamepad.buttons[0].value;
  24482. this.buttonB = this.browserGamepad.buttons[1].value;
  24483. this.buttonX = this.browserGamepad.buttons[2].value;
  24484. this.buttonY = this.browserGamepad.buttons[3].value;
  24485. this.buttonLB = this.browserGamepad.buttons[4].value;
  24486. this.buttonRB = this.browserGamepad.buttons[5].value;
  24487. this.leftTrigger = this.browserGamepad.buttons[6].value;
  24488. this.rightTrigger = this.browserGamepad.buttons[7].value;
  24489. this.buttonBack = this.browserGamepad.buttons[8].value;
  24490. this.buttonStart = this.browserGamepad.buttons[9].value;
  24491. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  24492. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  24493. this.dPadUp = this.browserGamepad.buttons[12].value;
  24494. this.dPadDown = this.browserGamepad.buttons[13].value;
  24495. this.dPadLeft = this.browserGamepad.buttons[14].value;
  24496. this.dPadRight = this.browserGamepad.buttons[15].value;
  24497. };
  24498. return Xbox360Pad;
  24499. })(Gamepad);
  24500. BABYLON.Xbox360Pad = Xbox360Pad;
  24501. })(BABYLON || (BABYLON = {}));
  24502. //# sourceMappingURL=babylon.gamepads.js.map
  24503. var BABYLON;
  24504. (function (BABYLON) {
  24505. // We're mainly based on the logic defined into the FreeCamera code
  24506. var GamepadCamera = (function (_super) {
  24507. __extends(GamepadCamera, _super);
  24508. function GamepadCamera(name, position, scene) {
  24509. var _this = this;
  24510. _super.call(this, name, position, scene);
  24511. this.angularSensibility = 200;
  24512. this.moveSensibility = 75;
  24513. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  24514. _this._onNewGameConnected(gamepad);
  24515. });
  24516. }
  24517. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  24518. // Only the first gamepad can control the camera
  24519. if (gamepad.index === 0) {
  24520. this._gamepad = gamepad;
  24521. }
  24522. };
  24523. GamepadCamera.prototype._checkInputs = function () {
  24524. if (!this._gamepad) {
  24525. return;
  24526. }
  24527. var LSValues = this._gamepad.leftStick;
  24528. var normalizedLX = LSValues.x / this.moveSensibility;
  24529. var normalizedLY = LSValues.y / this.moveSensibility;
  24530. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  24531. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  24532. var RSValues = this._gamepad.rightStick;
  24533. var normalizedRX = RSValues.x / this.angularSensibility;
  24534. var normalizedRY = RSValues.y / this.angularSensibility;
  24535. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  24536. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  24537. ;
  24538. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24539. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  24540. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24541. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  24542. };
  24543. GamepadCamera.prototype.dispose = function () {
  24544. this._gamepads.dispose();
  24545. _super.prototype.dispose.call(this);
  24546. };
  24547. return GamepadCamera;
  24548. })(BABYLON.FreeCamera);
  24549. BABYLON.GamepadCamera = GamepadCamera;
  24550. })(BABYLON || (BABYLON = {}));
  24551. //# sourceMappingURL=babylon.gamepadCamera.js.map
  24552. var BABYLON;
  24553. (function (BABYLON) {
  24554. var LinesMesh = (function (_super) {
  24555. __extends(LinesMesh, _super);
  24556. function LinesMesh(name, scene, updatable) {
  24557. if (updatable === void 0) { updatable = false; }
  24558. _super.call(this, name, scene);
  24559. this.color = new BABYLON.Color3(1, 1, 1);
  24560. this.alpha = 1;
  24561. this._indices = new Array();
  24562. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  24563. attributes: ["position"],
  24564. uniforms: ["worldViewProjection", "color"],
  24565. needAlphaBlending: true
  24566. });
  24567. }
  24568. Object.defineProperty(LinesMesh.prototype, "material", {
  24569. get: function () {
  24570. return this._colorShader;
  24571. },
  24572. enumerable: true,
  24573. configurable: true
  24574. });
  24575. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  24576. get: function () {
  24577. return false;
  24578. },
  24579. enumerable: true,
  24580. configurable: true
  24581. });
  24582. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  24583. get: function () {
  24584. return false;
  24585. },
  24586. enumerable: true,
  24587. configurable: true
  24588. });
  24589. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  24590. var engine = this.getScene().getEngine();
  24591. var indexToBind = this._geometry.getIndexBuffer();
  24592. // VBOs
  24593. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  24594. // Color
  24595. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  24596. };
  24597. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  24598. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24599. return;
  24600. }
  24601. var engine = this.getScene().getEngine();
  24602. // Draw order
  24603. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  24604. };
  24605. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  24606. return null;
  24607. };
  24608. LinesMesh.prototype.dispose = function (doNotRecurse) {
  24609. this._colorShader.dispose();
  24610. _super.prototype.dispose.call(this, doNotRecurse);
  24611. };
  24612. return LinesMesh;
  24613. })(BABYLON.Mesh);
  24614. BABYLON.LinesMesh = LinesMesh;
  24615. })(BABYLON || (BABYLON = {}));
  24616. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  24617. (function (BABYLON) {
  24618. var OutlineRenderer = (function () {
  24619. function OutlineRenderer(scene) {
  24620. this._scene = scene;
  24621. }
  24622. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  24623. var _this = this;
  24624. if (useOverlay === void 0) { useOverlay = false; }
  24625. var scene = this._scene;
  24626. var engine = this._scene.getEngine();
  24627. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24628. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  24629. return;
  24630. }
  24631. var mesh = subMesh.getRenderingMesh();
  24632. var material = subMesh.getMaterial();
  24633. engine.enableEffect(this._effect);
  24634. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  24635. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  24636. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24637. // Bones
  24638. if (mesh.useBones) {
  24639. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24640. }
  24641. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  24642. // Alpha test
  24643. if (material && material.needAlphaTesting()) {
  24644. var alphaTexture = material.getAlphaTestTexture();
  24645. this._effect.setTexture("diffuseSampler", alphaTexture);
  24646. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  24647. }
  24648. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  24649. _this._effect.setMatrix("world", world);
  24650. });
  24651. };
  24652. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  24653. var defines = [];
  24654. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  24655. var mesh = subMesh.getMesh();
  24656. var material = subMesh.getMaterial();
  24657. // Alpha test
  24658. if (material && material.needAlphaTesting()) {
  24659. defines.push("#define ALPHATEST");
  24660. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24661. attribs.push(BABYLON.VertexBuffer.UVKind);
  24662. defines.push("#define UV1");
  24663. }
  24664. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24665. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  24666. defines.push("#define UV2");
  24667. }
  24668. }
  24669. // Bones
  24670. if (mesh.useBones) {
  24671. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24672. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24673. defines.push("#define BONES");
  24674. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24675. }
  24676. // Instances
  24677. if (useInstances) {
  24678. defines.push("#define INSTANCES");
  24679. attribs.push("world0");
  24680. attribs.push("world1");
  24681. attribs.push("world2");
  24682. attribs.push("world3");
  24683. }
  24684. // Get correct effect
  24685. var join = defines.join("\n");
  24686. if (this._cachedDefines !== join) {
  24687. this._cachedDefines = join;
  24688. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  24689. }
  24690. return this._effect.isReady();
  24691. };
  24692. return OutlineRenderer;
  24693. })();
  24694. BABYLON.OutlineRenderer = OutlineRenderer;
  24695. })(BABYLON || (BABYLON = {}));
  24696. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  24697. (function (BABYLON) {
  24698. var MeshAssetTask = (function () {
  24699. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  24700. this.name = name;
  24701. this.meshesNames = meshesNames;
  24702. this.rootUrl = rootUrl;
  24703. this.sceneFilename = sceneFilename;
  24704. this.isCompleted = false;
  24705. }
  24706. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24707. var _this = this;
  24708. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  24709. _this.loadedMeshes = meshes;
  24710. _this.loadedParticleSystems = particleSystems;
  24711. _this.loadedSkeletons = skeletons;
  24712. _this.isCompleted = true;
  24713. if (_this.onSuccess) {
  24714. _this.onSuccess(_this);
  24715. }
  24716. onSuccess();
  24717. }, null, function () {
  24718. if (_this.onError) {
  24719. _this.onError(_this);
  24720. }
  24721. onError();
  24722. });
  24723. };
  24724. return MeshAssetTask;
  24725. })();
  24726. BABYLON.MeshAssetTask = MeshAssetTask;
  24727. var TextFileAssetTask = (function () {
  24728. function TextFileAssetTask(name, url) {
  24729. this.name = name;
  24730. this.url = url;
  24731. this.isCompleted = false;
  24732. }
  24733. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24734. var _this = this;
  24735. BABYLON.Tools.LoadFile(this.url, function (data) {
  24736. _this.text = data;
  24737. _this.isCompleted = true;
  24738. if (_this.onSuccess) {
  24739. _this.onSuccess(_this);
  24740. }
  24741. onSuccess();
  24742. }, null, scene.database, false, function () {
  24743. if (_this.onError) {
  24744. _this.onError(_this);
  24745. }
  24746. onError();
  24747. });
  24748. };
  24749. return TextFileAssetTask;
  24750. })();
  24751. BABYLON.TextFileAssetTask = TextFileAssetTask;
  24752. var BinaryFileAssetTask = (function () {
  24753. function BinaryFileAssetTask(name, url) {
  24754. this.name = name;
  24755. this.url = url;
  24756. this.isCompleted = false;
  24757. }
  24758. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24759. var _this = this;
  24760. BABYLON.Tools.LoadFile(this.url, function (data) {
  24761. _this.data = data;
  24762. _this.isCompleted = true;
  24763. if (_this.onSuccess) {
  24764. _this.onSuccess(_this);
  24765. }
  24766. onSuccess();
  24767. }, null, scene.database, true, function () {
  24768. if (_this.onError) {
  24769. _this.onError(_this);
  24770. }
  24771. onError();
  24772. });
  24773. };
  24774. return BinaryFileAssetTask;
  24775. })();
  24776. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  24777. var ImageAssetTask = (function () {
  24778. function ImageAssetTask(name, url) {
  24779. this.name = name;
  24780. this.url = url;
  24781. this.isCompleted = false;
  24782. }
  24783. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24784. var _this = this;
  24785. var img = new Image();
  24786. img.onload = function () {
  24787. _this.image = img;
  24788. _this.isCompleted = true;
  24789. if (_this.onSuccess) {
  24790. _this.onSuccess(_this);
  24791. }
  24792. onSuccess();
  24793. };
  24794. img.onerror = function () {
  24795. if (_this.onError) {
  24796. _this.onError(_this);
  24797. }
  24798. onError();
  24799. };
  24800. img.src = this.url;
  24801. };
  24802. return ImageAssetTask;
  24803. })();
  24804. BABYLON.ImageAssetTask = ImageAssetTask;
  24805. var TextureAssetTask = (function () {
  24806. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  24807. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24808. this.name = name;
  24809. this.url = url;
  24810. this.noMipmap = noMipmap;
  24811. this.invertY = invertY;
  24812. this.samplingMode = samplingMode;
  24813. this.isCompleted = false;
  24814. }
  24815. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24816. var _this = this;
  24817. var onload = function () {
  24818. _this.isCompleted = true;
  24819. if (_this.onSuccess) {
  24820. _this.onSuccess(_this);
  24821. }
  24822. onSuccess();
  24823. };
  24824. var onerror = function () {
  24825. if (_this.onError) {
  24826. _this.onError(_this);
  24827. }
  24828. onError();
  24829. };
  24830. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  24831. };
  24832. return TextureAssetTask;
  24833. })();
  24834. BABYLON.TextureAssetTask = TextureAssetTask;
  24835. var AssetsManager = (function () {
  24836. function AssetsManager(scene) {
  24837. this._tasks = new Array();
  24838. this._waitingTasksCount = 0;
  24839. this.useDefaultLoadingScreen = true;
  24840. this._scene = scene;
  24841. }
  24842. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  24843. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  24844. this._tasks.push(task);
  24845. return task;
  24846. };
  24847. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  24848. var task = new TextFileAssetTask(taskName, url);
  24849. this._tasks.push(task);
  24850. return task;
  24851. };
  24852. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  24853. var task = new BinaryFileAssetTask(taskName, url);
  24854. this._tasks.push(task);
  24855. return task;
  24856. };
  24857. AssetsManager.prototype.addImageTask = function (taskName, url) {
  24858. var task = new ImageAssetTask(taskName, url);
  24859. this._tasks.push(task);
  24860. return task;
  24861. };
  24862. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  24863. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24864. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  24865. this._tasks.push(task);
  24866. return task;
  24867. };
  24868. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  24869. this._waitingTasksCount--;
  24870. if (this._waitingTasksCount === 0) {
  24871. if (this.onFinish) {
  24872. this.onFinish(this._tasks);
  24873. }
  24874. this._scene.getEngine().hideLoadingUI();
  24875. }
  24876. };
  24877. AssetsManager.prototype._runTask = function (task) {
  24878. var _this = this;
  24879. task.run(this._scene, function () {
  24880. if (_this.onTaskSuccess) {
  24881. _this.onTaskSuccess(task);
  24882. }
  24883. _this._decreaseWaitingTasksCount();
  24884. }, function () {
  24885. if (_this.onTaskError) {
  24886. _this.onTaskError(task);
  24887. }
  24888. _this._decreaseWaitingTasksCount();
  24889. });
  24890. };
  24891. AssetsManager.prototype.reset = function () {
  24892. this._tasks = new Array();
  24893. return this;
  24894. };
  24895. AssetsManager.prototype.load = function () {
  24896. this._waitingTasksCount = this._tasks.length;
  24897. if (this._waitingTasksCount === 0) {
  24898. if (this.onFinish) {
  24899. this.onFinish(this._tasks);
  24900. }
  24901. return this;
  24902. }
  24903. if (this.useDefaultLoadingScreen) {
  24904. this._scene.getEngine().displayLoadingUI();
  24905. }
  24906. for (var index = 0; index < this._tasks.length; index++) {
  24907. var task = this._tasks[index];
  24908. this._runTask(task);
  24909. }
  24910. return this;
  24911. };
  24912. return AssetsManager;
  24913. })();
  24914. BABYLON.AssetsManager = AssetsManager;
  24915. })(BABYLON || (BABYLON = {}));
  24916. //# sourceMappingURL=babylon.assetsManager.js.map
  24917. var BABYLON;
  24918. (function (BABYLON) {
  24919. var VRDeviceOrientationCamera = (function (_super) {
  24920. __extends(VRDeviceOrientationCamera, _super);
  24921. function VRDeviceOrientationCamera(name, position, scene) {
  24922. _super.call(this, name, position, scene);
  24923. this._alpha = 0;
  24924. this._beta = 0;
  24925. this._gamma = 0;
  24926. }
  24927. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  24928. this._alpha = +evt.alpha | 0;
  24929. this._beta = +evt.beta | 0;
  24930. this._gamma = +evt.gamma | 0;
  24931. if (this._gamma < 0) {
  24932. this._gamma = 90 + this._gamma;
  24933. }
  24934. else {
  24935. // Incline it in the correct angle.
  24936. this._gamma = 270 - this._gamma;
  24937. }
  24938. this.rotation.x = this._gamma / 180.0 * Math.PI;
  24939. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  24940. this.rotation.z = this._beta / 180.0 * Math.PI;
  24941. };
  24942. return VRDeviceOrientationCamera;
  24943. })(BABYLON.OculusCamera);
  24944. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  24945. })(BABYLON || (BABYLON = {}));
  24946. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  24947. var BABYLON;
  24948. (function (BABYLON) {
  24949. var WebVRCamera = (function (_super) {
  24950. __extends(WebVRCamera, _super);
  24951. function WebVRCamera(name, position, scene) {
  24952. _super.call(this, name, position, scene);
  24953. this._hmdDevice = null;
  24954. this._sensorDevice = null;
  24955. this._cacheState = null;
  24956. this._cacheQuaternion = new BABYLON.Quaternion();
  24957. this._cacheRotation = BABYLON.Vector3.Zero();
  24958. this._vrEnabled = false;
  24959. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  24960. }
  24961. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  24962. var size = devices.length;
  24963. var i = 0;
  24964. // Reset devices.
  24965. this._sensorDevice = null;
  24966. this._hmdDevice = null;
  24967. while (i < size && this._hmdDevice === null) {
  24968. if (devices[i] instanceof HMDVRDevice) {
  24969. this._hmdDevice = devices[i];
  24970. }
  24971. i++;
  24972. }
  24973. i = 0;
  24974. while (i < size && this._sensorDevice === null) {
  24975. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  24976. this._sensorDevice = devices[i];
  24977. }
  24978. i++;
  24979. }
  24980. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  24981. };
  24982. WebVRCamera.prototype._update = function () {
  24983. if (this._vrEnabled) {
  24984. this._cacheState = this._sensorDevice.getState();
  24985. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  24986. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  24987. this.rotation.x = -this._cacheRotation.z;
  24988. this.rotation.y = -this._cacheRotation.y;
  24989. this.rotation.z = this._cacheRotation.x;
  24990. }
  24991. _super.prototype._update.call(this);
  24992. };
  24993. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  24994. _super.prototype.attachControl.call(this, element, noPreventDefault);
  24995. if (navigator.getVRDevices) {
  24996. navigator.getVRDevices().then(this._getWebVRDevices);
  24997. }
  24998. else if (navigator.mozGetVRDevices) {
  24999. navigator.mozGetVRDevices(this._getWebVRDevices);
  25000. }
  25001. };
  25002. WebVRCamera.prototype.detachControl = function (element) {
  25003. _super.prototype.detachControl.call(this, element);
  25004. this._vrEnabled = false;
  25005. };
  25006. return WebVRCamera;
  25007. })(BABYLON.OculusCamera);
  25008. BABYLON.WebVRCamera = WebVRCamera;
  25009. })(BABYLON || (BABYLON = {}));
  25010. //# sourceMappingURL=babylon.webVRCamera.js.map
  25011. var BABYLON;
  25012. (function (BABYLON) {
  25013. // Standard optimizations
  25014. var SceneOptimization = (function () {
  25015. function SceneOptimization(priority) {
  25016. if (priority === void 0) { priority = 0; }
  25017. this.priority = priority;
  25018. this.apply = function (scene) {
  25019. return true; // Return true if everything that can be done was applied
  25020. };
  25021. }
  25022. return SceneOptimization;
  25023. })();
  25024. BABYLON.SceneOptimization = SceneOptimization;
  25025. var TextureOptimization = (function (_super) {
  25026. __extends(TextureOptimization, _super);
  25027. function TextureOptimization(priority, maximumSize) {
  25028. var _this = this;
  25029. if (priority === void 0) { priority = 0; }
  25030. if (maximumSize === void 0) { maximumSize = 1024; }
  25031. _super.call(this, priority);
  25032. this.priority = priority;
  25033. this.maximumSize = maximumSize;
  25034. this.apply = function (scene) {
  25035. var allDone = true;
  25036. for (var index = 0; index < scene.textures.length; index++) {
  25037. var texture = scene.textures[index];
  25038. if (!texture.canRescale) {
  25039. continue;
  25040. }
  25041. var currentSize = texture.getSize();
  25042. var maxDimension = Math.max(currentSize.width, currentSize.height);
  25043. if (maxDimension > _this.maximumSize) {
  25044. texture.scale(0.5);
  25045. allDone = false;
  25046. }
  25047. }
  25048. return allDone;
  25049. };
  25050. }
  25051. return TextureOptimization;
  25052. })(SceneOptimization);
  25053. BABYLON.TextureOptimization = TextureOptimization;
  25054. var HardwareScalingOptimization = (function (_super) {
  25055. __extends(HardwareScalingOptimization, _super);
  25056. function HardwareScalingOptimization(priority, maximumScale) {
  25057. var _this = this;
  25058. if (priority === void 0) { priority = 0; }
  25059. if (maximumScale === void 0) { maximumScale = 2; }
  25060. _super.call(this, priority);
  25061. this.priority = priority;
  25062. this.maximumScale = maximumScale;
  25063. this._currentScale = 1;
  25064. this.apply = function (scene) {
  25065. _this._currentScale++;
  25066. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  25067. return _this._currentScale >= _this.maximumScale;
  25068. };
  25069. }
  25070. return HardwareScalingOptimization;
  25071. })(SceneOptimization);
  25072. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  25073. var ShadowsOptimization = (function (_super) {
  25074. __extends(ShadowsOptimization, _super);
  25075. function ShadowsOptimization() {
  25076. _super.apply(this, arguments);
  25077. this.apply = function (scene) {
  25078. scene.shadowsEnabled = false;
  25079. return true;
  25080. };
  25081. }
  25082. return ShadowsOptimization;
  25083. })(SceneOptimization);
  25084. BABYLON.ShadowsOptimization = ShadowsOptimization;
  25085. var PostProcessesOptimization = (function (_super) {
  25086. __extends(PostProcessesOptimization, _super);
  25087. function PostProcessesOptimization() {
  25088. _super.apply(this, arguments);
  25089. this.apply = function (scene) {
  25090. scene.postProcessesEnabled = false;
  25091. return true;
  25092. };
  25093. }
  25094. return PostProcessesOptimization;
  25095. })(SceneOptimization);
  25096. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  25097. var LensFlaresOptimization = (function (_super) {
  25098. __extends(LensFlaresOptimization, _super);
  25099. function LensFlaresOptimization() {
  25100. _super.apply(this, arguments);
  25101. this.apply = function (scene) {
  25102. scene.lensFlaresEnabled = false;
  25103. return true;
  25104. };
  25105. }
  25106. return LensFlaresOptimization;
  25107. })(SceneOptimization);
  25108. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  25109. var ParticlesOptimization = (function (_super) {
  25110. __extends(ParticlesOptimization, _super);
  25111. function ParticlesOptimization() {
  25112. _super.apply(this, arguments);
  25113. this.apply = function (scene) {
  25114. scene.particlesEnabled = false;
  25115. return true;
  25116. };
  25117. }
  25118. return ParticlesOptimization;
  25119. })(SceneOptimization);
  25120. BABYLON.ParticlesOptimization = ParticlesOptimization;
  25121. var RenderTargetsOptimization = (function (_super) {
  25122. __extends(RenderTargetsOptimization, _super);
  25123. function RenderTargetsOptimization() {
  25124. _super.apply(this, arguments);
  25125. this.apply = function (scene) {
  25126. scene.renderTargetsEnabled = false;
  25127. return true;
  25128. };
  25129. }
  25130. return RenderTargetsOptimization;
  25131. })(SceneOptimization);
  25132. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  25133. var MergeMeshesOptimization = (function (_super) {
  25134. __extends(MergeMeshesOptimization, _super);
  25135. function MergeMeshesOptimization() {
  25136. var _this = this;
  25137. _super.apply(this, arguments);
  25138. this._canBeMerged = function (abstractMesh) {
  25139. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  25140. return false;
  25141. }
  25142. var mesh = abstractMesh;
  25143. if (!mesh.isVisible || !mesh.isEnabled()) {
  25144. return false;
  25145. }
  25146. if (mesh.instances.length > 0) {
  25147. return false;
  25148. }
  25149. if (mesh.skeleton || mesh.hasLODLevels) {
  25150. return false;
  25151. }
  25152. return true;
  25153. };
  25154. this.apply = function (scene) {
  25155. var globalPool = scene.meshes.slice(0);
  25156. var globalLength = globalPool.length;
  25157. for (var index = 0; index < globalLength; index++) {
  25158. var currentPool = new Array();
  25159. var current = globalPool[index];
  25160. // Checks
  25161. if (!_this._canBeMerged(current)) {
  25162. continue;
  25163. }
  25164. currentPool.push(current);
  25165. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  25166. var otherMesh = globalPool[subIndex];
  25167. if (!_this._canBeMerged(otherMesh)) {
  25168. continue;
  25169. }
  25170. if (otherMesh.material !== current.material) {
  25171. continue;
  25172. }
  25173. if (otherMesh.checkCollisions !== current.checkCollisions) {
  25174. continue;
  25175. }
  25176. currentPool.push(otherMesh);
  25177. globalLength--;
  25178. globalPool.splice(subIndex, 1);
  25179. subIndex--;
  25180. }
  25181. if (currentPool.length < 2) {
  25182. continue;
  25183. }
  25184. // Merge meshes
  25185. BABYLON.Mesh.MergeMeshes(currentPool);
  25186. }
  25187. return true;
  25188. };
  25189. }
  25190. return MergeMeshesOptimization;
  25191. })(SceneOptimization);
  25192. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  25193. // Options
  25194. var SceneOptimizerOptions = (function () {
  25195. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  25196. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  25197. if (trackerDuration === void 0) { trackerDuration = 2000; }
  25198. this.targetFrameRate = targetFrameRate;
  25199. this.trackerDuration = trackerDuration;
  25200. this.optimizations = new Array();
  25201. }
  25202. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  25203. var result = new SceneOptimizerOptions(targetFrameRate);
  25204. var priority = 0;
  25205. result.optimizations.push(new MergeMeshesOptimization(priority));
  25206. result.optimizations.push(new ShadowsOptimization(priority));
  25207. result.optimizations.push(new LensFlaresOptimization(priority));
  25208. // Next priority
  25209. priority++;
  25210. result.optimizations.push(new PostProcessesOptimization(priority));
  25211. result.optimizations.push(new ParticlesOptimization(priority));
  25212. // Next priority
  25213. priority++;
  25214. result.optimizations.push(new TextureOptimization(priority, 1024));
  25215. return result;
  25216. };
  25217. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  25218. var result = new SceneOptimizerOptions(targetFrameRate);
  25219. var priority = 0;
  25220. result.optimizations.push(new MergeMeshesOptimization(priority));
  25221. result.optimizations.push(new ShadowsOptimization(priority));
  25222. result.optimizations.push(new LensFlaresOptimization(priority));
  25223. // Next priority
  25224. priority++;
  25225. result.optimizations.push(new PostProcessesOptimization(priority));
  25226. result.optimizations.push(new ParticlesOptimization(priority));
  25227. // Next priority
  25228. priority++;
  25229. result.optimizations.push(new TextureOptimization(priority, 512));
  25230. // Next priority
  25231. priority++;
  25232. result.optimizations.push(new RenderTargetsOptimization(priority));
  25233. // Next priority
  25234. priority++;
  25235. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  25236. return result;
  25237. };
  25238. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  25239. var result = new SceneOptimizerOptions(targetFrameRate);
  25240. var priority = 0;
  25241. result.optimizations.push(new MergeMeshesOptimization(priority));
  25242. result.optimizations.push(new ShadowsOptimization(priority));
  25243. result.optimizations.push(new LensFlaresOptimization(priority));
  25244. // Next priority
  25245. priority++;
  25246. result.optimizations.push(new PostProcessesOptimization(priority));
  25247. result.optimizations.push(new ParticlesOptimization(priority));
  25248. // Next priority
  25249. priority++;
  25250. result.optimizations.push(new TextureOptimization(priority, 256));
  25251. // Next priority
  25252. priority++;
  25253. result.optimizations.push(new RenderTargetsOptimization(priority));
  25254. // Next priority
  25255. priority++;
  25256. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  25257. return result;
  25258. };
  25259. return SceneOptimizerOptions;
  25260. })();
  25261. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  25262. // Scene optimizer tool
  25263. var SceneOptimizer = (function () {
  25264. function SceneOptimizer() {
  25265. }
  25266. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  25267. // TODO: add an epsilon
  25268. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  25269. if (onSuccess) {
  25270. onSuccess();
  25271. }
  25272. return;
  25273. }
  25274. // Apply current level of optimizations
  25275. var allDone = true;
  25276. var noOptimizationApplied = true;
  25277. for (var index = 0; index < options.optimizations.length; index++) {
  25278. var optimization = options.optimizations[index];
  25279. if (optimization.priority === currentPriorityLevel) {
  25280. noOptimizationApplied = false;
  25281. allDone = allDone && optimization.apply(scene);
  25282. }
  25283. }
  25284. // If no optimization was applied, this is a failure :(
  25285. if (noOptimizationApplied) {
  25286. if (onFailure) {
  25287. onFailure();
  25288. }
  25289. return;
  25290. }
  25291. // If all optimizations were done, move to next level
  25292. if (allDone) {
  25293. currentPriorityLevel++;
  25294. }
  25295. // Let's the system running for a specific amount of time before checking FPS
  25296. scene.executeWhenReady(function () {
  25297. setTimeout(function () {
  25298. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  25299. }, options.trackerDuration);
  25300. });
  25301. };
  25302. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  25303. if (!options) {
  25304. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  25305. }
  25306. // Let's the system running for a specific amount of time before checking FPS
  25307. scene.executeWhenReady(function () {
  25308. setTimeout(function () {
  25309. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  25310. }, options.trackerDuration);
  25311. });
  25312. };
  25313. return SceneOptimizer;
  25314. })();
  25315. BABYLON.SceneOptimizer = SceneOptimizer;
  25316. })(BABYLON || (BABYLON = {}));
  25317. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  25318. (function (BABYLON) {
  25319. var Internals;
  25320. (function (Internals) {
  25321. var MeshLODLevel = (function () {
  25322. function MeshLODLevel(distance, mesh) {
  25323. this.distance = distance;
  25324. this.mesh = mesh;
  25325. }
  25326. return MeshLODLevel;
  25327. })();
  25328. Internals.MeshLODLevel = MeshLODLevel;
  25329. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25330. })(BABYLON || (BABYLON = {}));
  25331. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  25332. (function (BABYLON) {
  25333. var AudioEngine = (function () {
  25334. function AudioEngine() {
  25335. this.audioContext = null;
  25336. this.canUseWebAudio = false;
  25337. this.WarnedWebAudioUnsupported = false;
  25338. try {
  25339. if (typeof AudioContext !== 'undefined') {
  25340. this.audioContext = new AudioContext();
  25341. this.canUseWebAudio = true;
  25342. }
  25343. else if (typeof webkitAudioContext !== 'undefined') {
  25344. this.audioContext = new webkitAudioContext();
  25345. this.canUseWebAudio = true;
  25346. }
  25347. }
  25348. catch (e) {
  25349. this.canUseWebAudio = false;
  25350. BABYLON.Tools.Error("Web Audio: " + e.message);
  25351. }
  25352. // create a global volume gain node
  25353. if (this.canUseWebAudio) {
  25354. this.masterGain = this.audioContext.createGain();
  25355. this.masterGain.gain.value = 1;
  25356. this.masterGain.connect(this.audioContext.destination);
  25357. }
  25358. }
  25359. AudioEngine.prototype.dispose = function () {
  25360. if (this.canUseWebAudio) {
  25361. if (this._connectedAnalyser) {
  25362. this._connectedAnalyser.stopDebugCanvas();
  25363. this._connectedAnalyser.dispose();
  25364. this.masterGain.disconnect();
  25365. this.masterGain.connect(this.audioContext.destination);
  25366. this._connectedAnalyser = null;
  25367. }
  25368. this.masterGain.gain.value = 1;
  25369. }
  25370. this.WarnedWebAudioUnsupported = false;
  25371. };
  25372. AudioEngine.prototype.getGlobalVolume = function () {
  25373. if (this.canUseWebAudio) {
  25374. return this.masterGain.gain.value;
  25375. }
  25376. else {
  25377. return -1;
  25378. }
  25379. };
  25380. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  25381. if (this.canUseWebAudio) {
  25382. this.masterGain.gain.value = newVolume;
  25383. }
  25384. };
  25385. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  25386. if (this._connectedAnalyser) {
  25387. this._connectedAnalyser.stopDebugCanvas();
  25388. }
  25389. this._connectedAnalyser = analyser;
  25390. if (this.canUseWebAudio) {
  25391. this.masterGain.disconnect();
  25392. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  25393. }
  25394. };
  25395. return AudioEngine;
  25396. })();
  25397. BABYLON.AudioEngine = AudioEngine;
  25398. })(BABYLON || (BABYLON = {}));
  25399. //# sourceMappingURL=babylon.audioengine.js.mapvar BABYLON;
  25400. (function (BABYLON) {
  25401. var Sound = (function () {
  25402. /**
  25403. * Create a sound and attach it to a scene
  25404. * @param name Name of your sound
  25405. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  25406. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  25407. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  25408. */
  25409. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  25410. var _this = this;
  25411. this.autoplay = false;
  25412. this.loop = false;
  25413. this.useCustomAttenuation = false;
  25414. this.spatialSound = false;
  25415. this.refDistance = 1;
  25416. this.rolloffFactor = 1;
  25417. this.maxDistance = 100;
  25418. this.distanceModel = "linear";
  25419. this.panningModel = "HRTF";
  25420. this._playbackRate = 1;
  25421. this._startTime = 0;
  25422. this._startOffset = 0;
  25423. this._position = BABYLON.Vector3.Zero();
  25424. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  25425. this._volume = 1;
  25426. this._isLoaded = false;
  25427. this._isReadyToPlay = false;
  25428. this._isPlaying = false;
  25429. this._isDirectional = false;
  25430. // Used if you'd like to create a directional sound.
  25431. // If not set, the sound will be omnidirectional
  25432. this._coneInnerAngle = 360;
  25433. this._coneOuterAngle = 360;
  25434. this._coneOuterGain = 0;
  25435. this.name = name;
  25436. this._scene = scene;
  25437. this._readyToPlayCallback = readyToPlayCallback;
  25438. // Default custom attenuation function is a linear attenuation
  25439. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  25440. if (currentDistance < maxDistance) {
  25441. return currentVolume * (1 - currentDistance / maxDistance);
  25442. }
  25443. else {
  25444. return 0;
  25445. }
  25446. };
  25447. if (options) {
  25448. this.autoplay = options.autoplay || false;
  25449. this.loop = options.loop || false;
  25450. // if volume === 0, we need another way to check this option
  25451. if (options.volume !== undefined) {
  25452. this._volume = options.volume;
  25453. }
  25454. this.spatialSound = options.spatialSound || false;
  25455. this.maxDistance = options.maxDistance || 100;
  25456. this.useCustomAttenuation = options.useCustomAttenuation || false;
  25457. this.rolloffFactor = options.rolloffFactor || 1;
  25458. this.refDistance = options.refDistance || 1;
  25459. this.distanceModel = options.distanceModel || "linear";
  25460. this.panningModel = options.panningModel || "HRTF";
  25461. this._playbackRate = options.playbackRate || 1;
  25462. }
  25463. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25464. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  25465. this._soundGain.gain.value = this._volume;
  25466. this._inputAudioNode = this._soundGain;
  25467. this._ouputAudioNode = this._soundGain;
  25468. if (this.spatialSound) {
  25469. this._createSpatialParameters();
  25470. }
  25471. this._scene.mainSoundTrack.AddSound(this);
  25472. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  25473. if (urlOrArrayBuffer) {
  25474. // If it's an URL
  25475. if (typeof (urlOrArrayBuffer) === "string") {
  25476. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  25477. _this._soundLoaded(data);
  25478. }, null, null, true);
  25479. }
  25480. else {
  25481. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  25482. this._soundLoaded(urlOrArrayBuffer);
  25483. }
  25484. else {
  25485. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  25486. }
  25487. }
  25488. }
  25489. }
  25490. else {
  25491. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  25492. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  25493. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  25494. }
  25495. }
  25496. }
  25497. Sound.prototype.dispose = function () {
  25498. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  25499. if (this._isPlaying) {
  25500. this.stop();
  25501. }
  25502. this._isReadyToPlay = false;
  25503. if (this.soundTrackId === -1) {
  25504. this._scene.mainSoundTrack.RemoveSound(this);
  25505. }
  25506. else {
  25507. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  25508. }
  25509. this._soundGain.disconnect();
  25510. this._soundSource.disconnect();
  25511. if (this._soundPanner) {
  25512. this._soundPanner.disconnect();
  25513. this._soundPanner = null;
  25514. }
  25515. this._audioBuffer = null;
  25516. this._soundGain = null;
  25517. this._soundSource = null;
  25518. if (this._connectedMesh) {
  25519. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  25520. this._connectedMesh = null;
  25521. }
  25522. }
  25523. };
  25524. Sound.prototype._soundLoaded = function (audioData) {
  25525. var _this = this;
  25526. this._isLoaded = true;
  25527. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  25528. _this._audioBuffer = buffer;
  25529. _this._isReadyToPlay = true;
  25530. if (_this.autoplay) {
  25531. _this.play();
  25532. }
  25533. if (_this._readyToPlayCallback) {
  25534. _this._readyToPlayCallback();
  25535. }
  25536. }, function (error) {
  25537. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  25538. });
  25539. };
  25540. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  25541. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25542. this._audioBuffer = audioBuffer;
  25543. this._isReadyToPlay = true;
  25544. }
  25545. };
  25546. Sound.prototype.updateOptions = function (options) {
  25547. if (options) {
  25548. this.loop = options.loop || this.loop;
  25549. this.maxDistance = options.maxDistance || this.maxDistance;
  25550. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  25551. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  25552. this.refDistance = options.refDistance || this.refDistance;
  25553. this.distanceModel = options.distanceModel || this.distanceModel;
  25554. this.panningModel = options.panningModel || this.panningModel;
  25555. this._playbackRate = options.playbackRate || this._playbackRate;
  25556. }
  25557. };
  25558. Sound.prototype._createSpatialParameters = function () {
  25559. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25560. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  25561. if (this.useCustomAttenuation) {
  25562. // Tricks to disable in a way embedded Web Audio attenuation
  25563. this._soundPanner.distanceModel = "linear";
  25564. this._soundPanner.maxDistance = Number.MAX_VALUE;
  25565. this._soundPanner.refDistance = 1;
  25566. this._soundPanner.rolloffFactor = 1;
  25567. this._soundPanner.panningModel = "HRTF";
  25568. }
  25569. else {
  25570. this._soundPanner.distanceModel = this.distanceModel;
  25571. this._soundPanner.maxDistance = this.maxDistance;
  25572. this._soundPanner.refDistance = this.refDistance;
  25573. this._soundPanner.rolloffFactor = this.rolloffFactor;
  25574. this._soundPanner.panningModel = this.panningModel;
  25575. }
  25576. this._soundPanner.connect(this._ouputAudioNode);
  25577. this._inputAudioNode = this._soundPanner;
  25578. }
  25579. };
  25580. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  25581. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25582. this._ouputAudioNode.disconnect();
  25583. this._ouputAudioNode.connect(soundTrackAudioNode);
  25584. }
  25585. };
  25586. /**
  25587. * Transform this sound into a directional source
  25588. * @param coneInnerAngle Size of the inner cone in degree
  25589. * @param coneOuterAngle Size of the outer cone in degree
  25590. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  25591. */
  25592. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25593. if (coneOuterAngle < coneInnerAngle) {
  25594. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  25595. return;
  25596. }
  25597. this._coneInnerAngle = coneInnerAngle;
  25598. this._coneOuterAngle = coneOuterAngle;
  25599. this._coneOuterGain = coneOuterGain;
  25600. this._isDirectional = true;
  25601. if (this._isPlaying && this.loop) {
  25602. this.stop();
  25603. this.play();
  25604. }
  25605. };
  25606. Sound.prototype.setPosition = function (newPosition) {
  25607. this._position = newPosition;
  25608. if (this._isPlaying && this.spatialSound) {
  25609. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25610. }
  25611. };
  25612. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  25613. this._localDirection = newLocalDirection;
  25614. if (this._connectedMesh && this._isPlaying) {
  25615. this._updateDirection();
  25616. }
  25617. };
  25618. Sound.prototype._updateDirection = function () {
  25619. var mat = this._connectedMesh.getWorldMatrix();
  25620. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  25621. direction.normalize();
  25622. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  25623. };
  25624. Sound.prototype.updateDistanceFromListener = function () {
  25625. if (this._connectedMesh && this.useCustomAttenuation) {
  25626. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  25627. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  25628. }
  25629. };
  25630. Sound.prototype.setAttenuationFunction = function (callback) {
  25631. this._customAttenuationFunction = callback;
  25632. };
  25633. /**
  25634. * Play the sound
  25635. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  25636. */
  25637. Sound.prototype.play = function (time) {
  25638. if (this._isReadyToPlay) {
  25639. try {
  25640. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  25641. if (!this._soundSource) {
  25642. if (this.spatialSound) {
  25643. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25644. if (this._isDirectional) {
  25645. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  25646. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  25647. this._soundPanner.coneOuterGain = this._coneOuterGain;
  25648. if (this._connectedMesh) {
  25649. this._updateDirection();
  25650. }
  25651. else {
  25652. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  25653. }
  25654. }
  25655. }
  25656. }
  25657. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  25658. this._soundSource.buffer = this._audioBuffer;
  25659. this._soundSource.connect(this._inputAudioNode);
  25660. this._soundSource.loop = this.loop;
  25661. this._soundSource.playbackRate.value = this._playbackRate;
  25662. this._startTime = startTime;
  25663. if (this.onended) {
  25664. this._soundSource.onended = this.onended;
  25665. }
  25666. this._soundSource.start(startTime, this._startOffset % this._soundSource.buffer.duration);
  25667. this._isPlaying = true;
  25668. }
  25669. catch (ex) {
  25670. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  25671. }
  25672. }
  25673. };
  25674. /**
  25675. * Stop the sound
  25676. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  25677. */
  25678. Sound.prototype.stop = function (time) {
  25679. if (this._isPlaying) {
  25680. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  25681. this._soundSource.stop(stopTime);
  25682. this._isPlaying = false;
  25683. }
  25684. };
  25685. Sound.prototype.pause = function () {
  25686. if (this._isPlaying) {
  25687. this._soundSource.stop(0);
  25688. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  25689. }
  25690. };
  25691. Sound.prototype.setVolume = function (newVolume) {
  25692. this._volume = newVolume;
  25693. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25694. this._soundGain.gain.value = newVolume;
  25695. }
  25696. };
  25697. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  25698. this._playbackRate = newPlaybackRate;
  25699. if (this._isPlaying) {
  25700. this._soundSource.playbackRate.value = this._playbackRate;
  25701. }
  25702. };
  25703. Sound.prototype.getVolume = function () {
  25704. return this._volume;
  25705. };
  25706. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  25707. var _this = this;
  25708. this._connectedMesh = meshToConnectTo;
  25709. if (!this.spatialSound) {
  25710. this._createSpatialParameters();
  25711. this.spatialSound = true;
  25712. if (this._isPlaying && this.loop) {
  25713. this.stop();
  25714. this.play();
  25715. }
  25716. }
  25717. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  25718. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  25719. };
  25720. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  25721. this.setPosition(connectedMesh.position);
  25722. if (this._isDirectional && this._isPlaying) {
  25723. this._updateDirection();
  25724. }
  25725. };
  25726. return Sound;
  25727. })();
  25728. BABYLON.Sound = Sound;
  25729. })(BABYLON || (BABYLON = {}));
  25730. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  25731. (function (BABYLON) {
  25732. var SoundTrack = (function () {
  25733. function SoundTrack(scene, options) {
  25734. this.id = -1;
  25735. this._isMainTrack = false;
  25736. this._scene = scene;
  25737. this._audioEngine = BABYLON.Engine.audioEngine;
  25738. this.soundCollection = new Array();
  25739. if (this._audioEngine.canUseWebAudio) {
  25740. this._trackGain = this._audioEngine.audioContext.createGain();
  25741. this._trackGain.connect(this._audioEngine.masterGain);
  25742. if (options) {
  25743. if (options.volume) {
  25744. this._trackGain.gain.value = options.volume;
  25745. }
  25746. if (options.mainTrack) {
  25747. this._isMainTrack = options.mainTrack;
  25748. }
  25749. }
  25750. }
  25751. if (!this._isMainTrack) {
  25752. this._scene.soundTracks.push(this);
  25753. this.id = this._scene.soundTracks.length - 1;
  25754. }
  25755. }
  25756. SoundTrack.prototype.dispose = function () {
  25757. if (this._audioEngine.canUseWebAudio) {
  25758. if (this._connectedAnalyser) {
  25759. this._connectedAnalyser.stopDebugCanvas();
  25760. }
  25761. while (this.soundCollection.length) {
  25762. this.soundCollection[0].dispose();
  25763. }
  25764. this._trackGain.disconnect();
  25765. this._trackGain = null;
  25766. }
  25767. };
  25768. SoundTrack.prototype.AddSound = function (sound) {
  25769. sound.connectToSoundTrackAudioNode(this._trackGain);
  25770. if (sound.soundTrackId) {
  25771. if (sound.soundTrackId === -1) {
  25772. this._scene.mainSoundTrack.RemoveSound(sound);
  25773. }
  25774. else {
  25775. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  25776. }
  25777. }
  25778. this.soundCollection.push(sound);
  25779. sound.soundTrackId = this.id;
  25780. };
  25781. SoundTrack.prototype.RemoveSound = function (sound) {
  25782. var index = this.soundCollection.indexOf(sound);
  25783. if (index !== -1) {
  25784. this.soundCollection.splice(index, 1);
  25785. }
  25786. };
  25787. SoundTrack.prototype.setVolume = function (newVolume) {
  25788. if (this._audioEngine.canUseWebAudio) {
  25789. this._trackGain.gain.value = newVolume;
  25790. }
  25791. };
  25792. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  25793. if (this._connectedAnalyser) {
  25794. this._connectedAnalyser.stopDebugCanvas();
  25795. }
  25796. this._connectedAnalyser = analyser;
  25797. if (this._audioEngine.canUseWebAudio) {
  25798. this._trackGain.disconnect();
  25799. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  25800. }
  25801. };
  25802. return SoundTrack;
  25803. })();
  25804. BABYLON.SoundTrack = SoundTrack;
  25805. })(BABYLON || (BABYLON = {}));
  25806. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  25807. (function (BABYLON) {
  25808. var DebugLayer = (function () {
  25809. function DebugLayer(scene) {
  25810. var _this = this;
  25811. this._enabled = false;
  25812. this._labelsEnabled = false;
  25813. this._displayStatistics = true;
  25814. this._displayTree = false;
  25815. this._displayLogs = false;
  25816. this._identityMatrix = BABYLON.Matrix.Identity();
  25817. this.axisRatio = 0.02;
  25818. this.accentColor = "orange";
  25819. this._scene = scene;
  25820. this._syncPositions = function () {
  25821. var engine = _this._scene.getEngine();
  25822. var canvasRect = engine.getRenderingCanvasClientRect();
  25823. if (_this._showUI) {
  25824. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  25825. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  25826. _this._statsDiv.style.width = "400px";
  25827. _this._statsDiv.style.height = "auto";
  25828. _this._statsSubsetDiv.style.maxHeight = "240px";
  25829. _this._optionsDiv.style.left = "0px";
  25830. _this._optionsDiv.style.top = "10px";
  25831. _this._optionsDiv.style.width = "200px";
  25832. _this._optionsDiv.style.height = "auto";
  25833. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  25834. _this._logDiv.style.left = "0px";
  25835. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  25836. _this._logDiv.style.width = "600px";
  25837. _this._logDiv.style.height = "160px";
  25838. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  25839. _this._treeDiv.style.top = "10px";
  25840. _this._treeDiv.style.width = "300px";
  25841. _this._treeDiv.style.height = "auto";
  25842. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  25843. }
  25844. _this._globalDiv.style.left = canvasRect.left + "px";
  25845. _this._globalDiv.style.top = canvasRect.top + "px";
  25846. _this._drawingCanvas.style.left = "0px";
  25847. _this._drawingCanvas.style.top = "0px";
  25848. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  25849. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  25850. var devicePixelRatio = window.devicePixelRatio || 1;
  25851. var context = _this._drawingContext;
  25852. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  25853. _this._ratio = devicePixelRatio / backingStoreRatio;
  25854. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  25855. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  25856. };
  25857. this._onCanvasClick = function (evt) {
  25858. _this._clickPosition = {
  25859. x: evt.clientX * _this._ratio,
  25860. y: evt.clientY * _this._ratio
  25861. };
  25862. };
  25863. this._syncData = function () {
  25864. if (_this._showUI) {
  25865. if (_this._displayStatistics) {
  25866. _this._displayStats();
  25867. _this._statsDiv.style.display = "";
  25868. }
  25869. else {
  25870. _this._statsDiv.style.display = "none";
  25871. }
  25872. if (_this._displayLogs) {
  25873. _this._logDiv.style.display = "";
  25874. }
  25875. else {
  25876. _this._logDiv.style.display = "none";
  25877. }
  25878. if (_this._displayTree) {
  25879. _this._treeDiv.style.display = "";
  25880. if (_this._needToRefreshMeshesTree) {
  25881. _this._needToRefreshMeshesTree = false;
  25882. _this._refreshMeshesTreeContent();
  25883. }
  25884. }
  25885. else {
  25886. _this._treeDiv.style.display = "none";
  25887. }
  25888. }
  25889. if (_this._labelsEnabled || !_this._showUI) {
  25890. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  25891. var engine = _this._scene.getEngine();
  25892. var viewport = _this._scene.activeCamera.viewport;
  25893. var globalViewport = viewport.toGlobal(engine);
  25894. // Meshes
  25895. var meshes = _this._scene.getActiveMeshes();
  25896. for (var index = 0; index < meshes.length; index++) {
  25897. var mesh = meshes.data[index];
  25898. var position = mesh.getBoundingInfo().boundingSphere.center;
  25899. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25900. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  25901. _this._renderAxis(projectedPosition, mesh, globalViewport);
  25902. }
  25903. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  25904. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  25905. mesh.renderOverlay = !mesh.renderOverlay;
  25906. }, function () {
  25907. return mesh.renderOverlay ? 'red' : 'black';
  25908. });
  25909. }
  25910. }
  25911. // Cameras
  25912. var cameras = _this._scene.cameras;
  25913. for (index = 0; index < cameras.length; index++) {
  25914. var camera = cameras[index];
  25915. if (camera === _this._scene.activeCamera) {
  25916. continue;
  25917. }
  25918. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25919. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  25920. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  25921. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  25922. _this._scene.activeCamera = camera;
  25923. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  25924. }, function () {
  25925. return "purple";
  25926. });
  25927. }
  25928. }
  25929. // Lights
  25930. var lights = _this._scene.lights;
  25931. for (index = 0; index < lights.length; index++) {
  25932. var light = lights[index];
  25933. if (light.position) {
  25934. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  25935. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  25936. _this._renderLabel(light.name, projectedPosition, -20, function () {
  25937. light.setEnabled(!light.isEnabled());
  25938. }, function () {
  25939. return light.isEnabled() ? "orange" : "gray";
  25940. });
  25941. }
  25942. }
  25943. }
  25944. }
  25945. _this._clickPosition = undefined;
  25946. };
  25947. }
  25948. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  25949. while (this._treeSubsetDiv.hasChildNodes()) {
  25950. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  25951. }
  25952. // Add meshes
  25953. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  25954. sortedArray.sort(function (a, b) {
  25955. if (a.name === b.name) {
  25956. return 0;
  25957. }
  25958. return (a.name > b.name) ? 1 : -1;
  25959. });
  25960. for (var index = 0; index < sortedArray.length; index++) {
  25961. var mesh = sortedArray[index];
  25962. if (!mesh.isEnabled()) {
  25963. continue;
  25964. }
  25965. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  25966. m.isVisible = element.checked;
  25967. }, mesh);
  25968. }
  25969. };
  25970. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  25971. this._drawingContext.beginPath();
  25972. this._drawingContext.moveTo(zero.x, zero.y);
  25973. this._drawingContext.lineTo(unit.x, unit.y);
  25974. this._drawingContext.strokeStyle = color;
  25975. this._drawingContext.lineWidth = 4;
  25976. this._drawingContext.stroke();
  25977. this._drawingContext.font = "normal 14px Segoe UI";
  25978. this._drawingContext.fillStyle = color;
  25979. this._drawingContext.fillText(label, unitText.x, unitText.y);
  25980. };
  25981. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  25982. var position = mesh.getBoundingInfo().boundingSphere.center;
  25983. var worldMatrix = mesh.getWorldMatrix();
  25984. 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());
  25985. var unit = (unprojectedVector.subtract(position)).length();
  25986. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25987. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25988. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  25989. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25990. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25991. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  25992. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25993. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25994. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  25995. };
  25996. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  25997. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  25998. this._drawingContext.font = "normal 12px Segoe UI";
  25999. var textMetrics = this._drawingContext.measureText(text);
  26000. var centerX = projectedPosition.x - textMetrics.width / 2;
  26001. var centerY = projectedPosition.y;
  26002. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26003. onClick();
  26004. }
  26005. this._drawingContext.beginPath();
  26006. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26007. this._drawingContext.fillStyle = getFillStyle();
  26008. this._drawingContext.globalAlpha = 0.5;
  26009. this._drawingContext.fill();
  26010. this._drawingContext.globalAlpha = 1.0;
  26011. this._drawingContext.strokeStyle = '#FFFFFF';
  26012. this._drawingContext.lineWidth = 1;
  26013. this._drawingContext.stroke();
  26014. this._drawingContext.fillStyle = "#FFFFFF";
  26015. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26016. this._drawingContext.beginPath();
  26017. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26018. this._drawingContext.fill();
  26019. }
  26020. };
  26021. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26022. if (!this._clickPosition) {
  26023. return false;
  26024. }
  26025. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26026. return false;
  26027. }
  26028. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26029. return false;
  26030. }
  26031. return true;
  26032. };
  26033. DebugLayer.prototype.isVisible = function () {
  26034. return this._enabled;
  26035. };
  26036. DebugLayer.prototype.hide = function () {
  26037. if (!this._enabled) {
  26038. return;
  26039. }
  26040. this._enabled = false;
  26041. var engine = this._scene.getEngine();
  26042. this._scene.unregisterAfterRender(this._syncData);
  26043. document.body.removeChild(this._globalDiv);
  26044. window.removeEventListener("resize", this._syncPositions);
  26045. this._scene.forceShowBoundingBoxes = false;
  26046. this._scene.forceWireframe = false;
  26047. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26048. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26049. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26050. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26051. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26052. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26053. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26054. this._scene.shadowsEnabled = true;
  26055. this._scene.particlesEnabled = true;
  26056. this._scene.postProcessesEnabled = true;
  26057. this._scene.collisionsEnabled = true;
  26058. this._scene.lightsEnabled = true;
  26059. this._scene.texturesEnabled = true;
  26060. this._scene.lensFlaresEnabled = true;
  26061. this._scene.proceduralTexturesEnabled = true;
  26062. this._scene.renderTargetsEnabled = true;
  26063. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26064. };
  26065. DebugLayer.prototype.show = function (showUI) {
  26066. if (showUI === void 0) { showUI = true; }
  26067. if (this._enabled) {
  26068. return;
  26069. }
  26070. this._enabled = true;
  26071. this._showUI = showUI;
  26072. var engine = this._scene.getEngine();
  26073. this._globalDiv = document.createElement("div");
  26074. document.body.appendChild(this._globalDiv);
  26075. this._generateDOMelements();
  26076. window.addEventListener("resize", this._syncPositions);
  26077. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26078. this._syncPositions();
  26079. this._scene.registerAfterRender(this._syncData);
  26080. };
  26081. DebugLayer.prototype._clearLabels = function () {
  26082. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26083. for (var index = 0; index < this._scene.meshes.length; index++) {
  26084. var mesh = this._scene.meshes[index];
  26085. mesh.renderOverlay = false;
  26086. }
  26087. };
  26088. DebugLayer.prototype._generateheader = function (root, text) {
  26089. var header = document.createElement("div");
  26090. header.innerHTML = text + "&nbsp;";
  26091. header.style.textAlign = "right";
  26092. header.style.width = "100%";
  26093. header.style.color = "white";
  26094. header.style.backgroundColor = "Black";
  26095. header.style.padding = "5px 5px 4px 0px";
  26096. header.style.marginLeft = "-5px";
  26097. header.style.fontWeight = "bold";
  26098. root.appendChild(header);
  26099. };
  26100. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26101. var label = document.createElement("label");
  26102. label.innerHTML = title;
  26103. label.style.color = color;
  26104. root.appendChild(label);
  26105. root.appendChild(document.createElement("br"));
  26106. };
  26107. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26108. if (tag === void 0) { tag = null; }
  26109. var label = document.createElement("label");
  26110. var boundingBoxesCheckbox = document.createElement("input");
  26111. boundingBoxesCheckbox.type = "checkbox";
  26112. boundingBoxesCheckbox.checked = initialState;
  26113. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26114. task(evt.target, tag);
  26115. });
  26116. label.appendChild(boundingBoxesCheckbox);
  26117. var container = document.createElement("span");
  26118. var leftPart = document.createElement("span");
  26119. var rightPart = document.createElement("span");
  26120. rightPart.style.cssFloat = "right";
  26121. leftPart.innerHTML = leftTitle;
  26122. rightPart.innerHTML = rightTitle;
  26123. rightPart.style.fontSize = "12px";
  26124. rightPart.style.maxWidth = "200px";
  26125. container.appendChild(leftPart);
  26126. container.appendChild(rightPart);
  26127. label.appendChild(container);
  26128. root.appendChild(label);
  26129. root.appendChild(document.createElement("br"));
  26130. };
  26131. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26132. if (tag === void 0) { tag = null; }
  26133. var label = document.createElement("label");
  26134. var boundingBoxesCheckbox = document.createElement("input");
  26135. boundingBoxesCheckbox.type = "checkbox";
  26136. boundingBoxesCheckbox.checked = initialState;
  26137. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26138. task(evt.target, tag);
  26139. });
  26140. label.appendChild(boundingBoxesCheckbox);
  26141. label.appendChild(document.createTextNode(title));
  26142. root.appendChild(label);
  26143. root.appendChild(document.createElement("br"));
  26144. };
  26145. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26146. if (tag === void 0) { tag = null; }
  26147. var label = document.createElement("label");
  26148. var boundingBoxesRadio = document.createElement("input");
  26149. boundingBoxesRadio.type = "radio";
  26150. boundingBoxesRadio.name = name;
  26151. boundingBoxesRadio.checked = initialState;
  26152. boundingBoxesRadio.addEventListener("change", function (evt) {
  26153. task(evt.target, tag);
  26154. });
  26155. label.appendChild(boundingBoxesRadio);
  26156. label.appendChild(document.createTextNode(title));
  26157. root.appendChild(label);
  26158. root.appendChild(document.createElement("br"));
  26159. };
  26160. DebugLayer.prototype._generateDOMelements = function () {
  26161. var _this = this;
  26162. this._globalDiv.id = "DebugLayer";
  26163. this._globalDiv.style.position = "absolute";
  26164. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  26165. this._globalDiv.style.fontSize = "14px";
  26166. this._globalDiv.style.color = "white";
  26167. // Drawing canvas
  26168. this._drawingCanvas = document.createElement("canvas");
  26169. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  26170. this._drawingCanvas.style.position = "absolute";
  26171. this._drawingCanvas.style.pointerEvents = "none";
  26172. this._drawingContext = this._drawingCanvas.getContext("2d");
  26173. this._globalDiv.appendChild(this._drawingCanvas);
  26174. if (this._showUI) {
  26175. var background = "rgba(128, 128, 128, 0.4)";
  26176. var border = "rgb(180, 180, 180) solid 1px";
  26177. // Stats
  26178. this._statsDiv = document.createElement("div");
  26179. this._statsDiv.id = "DebugLayerStats";
  26180. this._statsDiv.style.border = border;
  26181. this._statsDiv.style.position = "absolute";
  26182. this._statsDiv.style.background = background;
  26183. this._statsDiv.style.padding = "0px 0px 0px 5px";
  26184. this._generateheader(this._statsDiv, "STATISTICS");
  26185. this._statsSubsetDiv = document.createElement("div");
  26186. this._statsSubsetDiv.style.paddingTop = "5px";
  26187. this._statsSubsetDiv.style.paddingBottom = "5px";
  26188. this._statsSubsetDiv.style.overflowY = "auto";
  26189. this._statsDiv.appendChild(this._statsSubsetDiv);
  26190. // Tree
  26191. this._treeDiv = document.createElement("div");
  26192. this._treeDiv.id = "DebugLayerTree";
  26193. this._treeDiv.style.border = border;
  26194. this._treeDiv.style.position = "absolute";
  26195. this._treeDiv.style.background = background;
  26196. this._treeDiv.style.padding = "0px 0px 0px 5px";
  26197. this._treeDiv.style.display = "none";
  26198. this._generateheader(this._treeDiv, "MESHES TREE");
  26199. this._treeSubsetDiv = document.createElement("div");
  26200. this._treeSubsetDiv.style.paddingTop = "5px";
  26201. this._treeSubsetDiv.style.paddingRight = "5px";
  26202. this._treeSubsetDiv.style.overflowY = "auto";
  26203. this._treeSubsetDiv.style.maxHeight = "300px";
  26204. this._treeDiv.appendChild(this._treeSubsetDiv);
  26205. this._needToRefreshMeshesTree = true;
  26206. // Logs
  26207. this._logDiv = document.createElement("div");
  26208. this._logDiv.style.border = border;
  26209. this._logDiv.id = "DebugLayerLogs";
  26210. this._logDiv.style.position = "absolute";
  26211. this._logDiv.style.background = background;
  26212. this._logDiv.style.padding = "0px 0px 0px 5px";
  26213. this._logDiv.style.display = "none";
  26214. this._generateheader(this._logDiv, "LOGS");
  26215. this._logSubsetDiv = document.createElement("div");
  26216. this._logSubsetDiv.style.height = "127px";
  26217. this._logSubsetDiv.style.paddingTop = "5px";
  26218. this._logSubsetDiv.style.overflowY = "auto";
  26219. this._logSubsetDiv.style.fontSize = "12px";
  26220. this._logSubsetDiv.style.fontFamily = "consolas";
  26221. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  26222. this._logDiv.appendChild(this._logSubsetDiv);
  26223. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  26224. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  26225. };
  26226. // Options
  26227. this._optionsDiv = document.createElement("div");
  26228. this._optionsDiv.id = "DebugLayerOptions";
  26229. this._optionsDiv.style.border = border;
  26230. this._optionsDiv.style.position = "absolute";
  26231. this._optionsDiv.style.background = background;
  26232. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  26233. this._optionsDiv.style.overflowY = "auto";
  26234. this._generateheader(this._optionsDiv, "OPTIONS");
  26235. this._optionsSubsetDiv = document.createElement("div");
  26236. this._optionsSubsetDiv.style.paddingTop = "5px";
  26237. this._optionsSubsetDiv.style.paddingBottom = "5px";
  26238. this._optionsSubsetDiv.style.overflowY = "auto";
  26239. this._optionsSubsetDiv.style.maxHeight = "200px";
  26240. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  26241. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  26242. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  26243. _this._displayStatistics = element.checked;
  26244. });
  26245. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  26246. _this._displayLogs = element.checked;
  26247. });
  26248. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  26249. _this._displayTree = element.checked;
  26250. _this._needToRefreshMeshesTree = true;
  26251. });
  26252. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26253. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  26254. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  26255. _this._scene.forceShowBoundingBoxes = element.checked;
  26256. });
  26257. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  26258. _this._labelsEnabled = element.checked;
  26259. if (!_this._labelsEnabled) {
  26260. _this._clearLabels();
  26261. }
  26262. });
  26263. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  26264. if (element.checked) {
  26265. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  26266. }
  26267. else {
  26268. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  26269. }
  26270. });
  26271. ;
  26272. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26273. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  26274. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  26275. if (element.checked) {
  26276. _this._scene.forceWireframe = false;
  26277. _this._scene.forcePointsCloud = false;
  26278. }
  26279. });
  26280. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  26281. if (element.checked) {
  26282. _this._scene.forceWireframe = true;
  26283. _this._scene.forcePointsCloud = false;
  26284. }
  26285. });
  26286. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  26287. if (element.checked) {
  26288. _this._scene.forceWireframe = false;
  26289. _this._scene.forcePointsCloud = true;
  26290. }
  26291. });
  26292. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26293. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  26294. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  26295. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  26296. });
  26297. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  26298. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  26299. });
  26300. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  26301. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  26302. });
  26303. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  26304. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  26305. });
  26306. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  26307. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  26308. });
  26309. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  26310. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  26311. });
  26312. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  26313. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  26314. });
  26315. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  26316. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  26317. });
  26318. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26319. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  26320. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  26321. _this._scene.animationsEnabled = element.checked;
  26322. });
  26323. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  26324. _this._scene.collisionsEnabled = element.checked;
  26325. });
  26326. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  26327. _this._scene.fogEnabled = element.checked;
  26328. });
  26329. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  26330. _this._scene.lensFlaresEnabled = element.checked;
  26331. });
  26332. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  26333. _this._scene.lightsEnabled = element.checked;
  26334. });
  26335. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  26336. _this._scene.particlesEnabled = element.checked;
  26337. });
  26338. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  26339. _this._scene.postProcessesEnabled = element.checked;
  26340. });
  26341. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  26342. _this._scene.proceduralTexturesEnabled = element.checked;
  26343. });
  26344. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  26345. _this._scene.renderTargetsEnabled = element.checked;
  26346. });
  26347. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  26348. _this._scene.shadowsEnabled = element.checked;
  26349. });
  26350. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  26351. _this._scene.skeletonsEnabled = element.checked;
  26352. });
  26353. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  26354. _this._scene.texturesEnabled = element.checked;
  26355. });
  26356. this._globalDiv.appendChild(this._statsDiv);
  26357. this._globalDiv.appendChild(this._logDiv);
  26358. this._globalDiv.appendChild(this._optionsDiv);
  26359. this._globalDiv.appendChild(this._treeDiv);
  26360. }
  26361. };
  26362. DebugLayer.prototype._displayStats = function () {
  26363. var scene = this._scene;
  26364. var engine = scene.getEngine();
  26365. var glInfo = engine.getGlInfo();
  26366. 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>";
  26367. if (this.customStatsFunction) {
  26368. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  26369. }
  26370. };
  26371. return DebugLayer;
  26372. })();
  26373. BABYLON.DebugLayer = DebugLayer;
  26374. })(BABYLON || (BABYLON = {}));
  26375. //# sourceMappingURL=babylon.debugLayer.js.map
  26376. var BABYLON;
  26377. (function (BABYLON) {
  26378. var RawTexture = (function (_super) {
  26379. __extends(RawTexture, _super);
  26380. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  26381. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26382. if (invertY === void 0) { invertY = false; }
  26383. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26384. _super.call(this, null, scene, !generateMipMaps, invertY);
  26385. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  26386. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26387. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26388. }
  26389. // Statics
  26390. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26391. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26392. if (invertY === void 0) { invertY = false; }
  26393. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26394. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  26395. };
  26396. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26397. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26398. if (invertY === void 0) { invertY = false; }
  26399. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26400. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26401. };
  26402. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26403. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26404. if (invertY === void 0) { invertY = false; }
  26405. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26406. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26407. };
  26408. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26409. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26410. if (invertY === void 0) { invertY = false; }
  26411. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26412. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  26413. };
  26414. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26415. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26416. if (invertY === void 0) { invertY = false; }
  26417. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26418. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  26419. };
  26420. return RawTexture;
  26421. })(BABYLON.Texture);
  26422. BABYLON.RawTexture = RawTexture;
  26423. })(BABYLON || (BABYLON = {}));
  26424. //# sourceMappingURL=babylon.rawTexture.js.map
  26425. var BABYLON;
  26426. (function (BABYLON) {
  26427. var IndexedVector2 = (function (_super) {
  26428. __extends(IndexedVector2, _super);
  26429. function IndexedVector2(original, index) {
  26430. _super.call(this, original.x, original.y);
  26431. this.index = index;
  26432. }
  26433. return IndexedVector2;
  26434. })(BABYLON.Vector2);
  26435. var PolygonPoints = (function () {
  26436. function PolygonPoints() {
  26437. this.elements = new Array();
  26438. }
  26439. PolygonPoints.prototype.add = function (originalPoints) {
  26440. var _this = this;
  26441. var result = new Array();
  26442. originalPoints.forEach(function (point) {
  26443. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  26444. var newPoint = new IndexedVector2(point, _this.elements.length);
  26445. result.push(newPoint);
  26446. _this.elements.push(newPoint);
  26447. }
  26448. });
  26449. return result;
  26450. };
  26451. PolygonPoints.prototype.computeBounds = function () {
  26452. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26453. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26454. this.elements.forEach(function (point) {
  26455. // x
  26456. if (point.x < lmin.x) {
  26457. lmin.x = point.x;
  26458. }
  26459. else if (point.x > lmax.x) {
  26460. lmax.x = point.x;
  26461. }
  26462. // y
  26463. if (point.y < lmin.y) {
  26464. lmin.y = point.y;
  26465. }
  26466. else if (point.y > lmax.y) {
  26467. lmax.y = point.y;
  26468. }
  26469. });
  26470. return {
  26471. min: lmin,
  26472. max: lmax,
  26473. width: lmax.x - lmin.x,
  26474. height: lmax.y - lmin.y
  26475. };
  26476. };
  26477. return PolygonPoints;
  26478. })();
  26479. var Polygon = (function () {
  26480. function Polygon() {
  26481. }
  26482. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  26483. return [
  26484. new BABYLON.Vector2(xmin, ymin),
  26485. new BABYLON.Vector2(xmax, ymin),
  26486. new BABYLON.Vector2(xmax, ymax),
  26487. new BABYLON.Vector2(xmin, ymax)
  26488. ];
  26489. };
  26490. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  26491. if (cx === void 0) { cx = 0; }
  26492. if (cy === void 0) { cy = 0; }
  26493. if (numberOfSides === void 0) { numberOfSides = 32; }
  26494. var result = new Array();
  26495. var angle = 0;
  26496. var increment = (Math.PI * 2) / numberOfSides;
  26497. for (var i = 0; i < numberOfSides; i++) {
  26498. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  26499. angle -= increment;
  26500. }
  26501. return result;
  26502. };
  26503. Polygon.Parse = function (input) {
  26504. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  26505. var i, result = [];
  26506. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  26507. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  26508. }
  26509. return result;
  26510. };
  26511. Polygon.StartingAt = function (x, y) {
  26512. return BABYLON.Path2.StartingAt(x, y);
  26513. };
  26514. return Polygon;
  26515. })();
  26516. BABYLON.Polygon = Polygon;
  26517. var PolygonMeshBuilder = (function () {
  26518. function PolygonMeshBuilder(name, contours, scene) {
  26519. this._points = new PolygonPoints();
  26520. if (!("poly2tri" in window)) {
  26521. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  26522. }
  26523. this._name = name;
  26524. this._scene = scene;
  26525. var points;
  26526. if (contours instanceof BABYLON.Path2) {
  26527. points = contours.getPoints();
  26528. }
  26529. else {
  26530. points = contours;
  26531. }
  26532. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  26533. }
  26534. PolygonMeshBuilder.prototype.addHole = function (hole) {
  26535. this._swctx.addHole(this._points.add(hole));
  26536. return this;
  26537. };
  26538. PolygonMeshBuilder.prototype.build = function (updatable) {
  26539. if (updatable === void 0) { updatable = false; }
  26540. var result = new BABYLON.Mesh(this._name, this._scene);
  26541. var normals = [];
  26542. var positions = [];
  26543. var uvs = [];
  26544. var bounds = this._points.computeBounds();
  26545. this._points.elements.forEach(function (p) {
  26546. normals.push(0, 1.0, 0);
  26547. positions.push(p.x, 0, p.y);
  26548. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  26549. });
  26550. var indices = [];
  26551. this._swctx.triangulate();
  26552. this._swctx.getTriangles().forEach(function (triangle) {
  26553. triangle.getPoints().forEach(function (point) {
  26554. indices.push(point.index);
  26555. });
  26556. });
  26557. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  26558. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  26559. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  26560. result.setIndices(indices);
  26561. return result;
  26562. };
  26563. return PolygonMeshBuilder;
  26564. })();
  26565. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  26566. })(BABYLON || (BABYLON = {}));
  26567. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  26568. (function (BABYLON) {
  26569. var SimplificationSettings = (function () {
  26570. function SimplificationSettings(quality, distance) {
  26571. this.quality = quality;
  26572. this.distance = distance;
  26573. }
  26574. return SimplificationSettings;
  26575. })();
  26576. BABYLON.SimplificationSettings = SimplificationSettings;
  26577. /**
  26578. * The implemented types of simplification.
  26579. * At the moment only Quadratic Error Decimation is implemented.
  26580. */
  26581. (function (SimplificationType) {
  26582. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  26583. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  26584. var SimplificationType = BABYLON.SimplificationType;
  26585. var DecimationTriangle = (function () {
  26586. function DecimationTriangle(vertices) {
  26587. this.vertices = vertices;
  26588. this.error = new Array(4);
  26589. this.deleted = false;
  26590. this.isDirty = false;
  26591. this.borderFactor = 0;
  26592. }
  26593. return DecimationTriangle;
  26594. })();
  26595. BABYLON.DecimationTriangle = DecimationTriangle;
  26596. var DecimationVertex = (function () {
  26597. function DecimationVertex(position, normal, uv, id) {
  26598. this.position = position;
  26599. this.normal = normal;
  26600. this.uv = uv;
  26601. this.id = id;
  26602. this.isBorder = true;
  26603. this.q = new QuadraticMatrix();
  26604. this.triangleCount = 0;
  26605. this.triangleStart = 0;
  26606. }
  26607. return DecimationVertex;
  26608. })();
  26609. BABYLON.DecimationVertex = DecimationVertex;
  26610. var QuadraticMatrix = (function () {
  26611. function QuadraticMatrix(data) {
  26612. this.data = new Array(10);
  26613. for (var i = 0; i < 10; ++i) {
  26614. if (data && data[i]) {
  26615. this.data[i] = data[i];
  26616. }
  26617. else {
  26618. this.data[i] = 0;
  26619. }
  26620. }
  26621. }
  26622. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  26623. 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];
  26624. return det;
  26625. };
  26626. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  26627. for (var i = 0; i < 10; ++i) {
  26628. this.data[i] += matrix.data[i];
  26629. }
  26630. };
  26631. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  26632. for (var i = 0; i < 10; ++i) {
  26633. this.data[i] += data[i];
  26634. }
  26635. };
  26636. QuadraticMatrix.prototype.add = function (matrix) {
  26637. var m = new QuadraticMatrix();
  26638. for (var i = 0; i < 10; ++i) {
  26639. m.data[i] = this.data[i] + matrix.data[i];
  26640. }
  26641. return m;
  26642. };
  26643. QuadraticMatrix.FromData = function (a, b, c, d) {
  26644. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  26645. };
  26646. //returning an array to avoid garbage collection
  26647. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  26648. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  26649. };
  26650. return QuadraticMatrix;
  26651. })();
  26652. BABYLON.QuadraticMatrix = QuadraticMatrix;
  26653. var Reference = (function () {
  26654. function Reference(vertexId, triangleId) {
  26655. this.vertexId = vertexId;
  26656. this.triangleId = triangleId;
  26657. }
  26658. return Reference;
  26659. })();
  26660. BABYLON.Reference = Reference;
  26661. /**
  26662. * An implementation of the Quadratic Error simplification algorithm.
  26663. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  26664. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  26665. * @author RaananW
  26666. */
  26667. var QuadraticErrorSimplification = (function () {
  26668. function QuadraticErrorSimplification(_mesh) {
  26669. this._mesh = _mesh;
  26670. this.initialised = false;
  26671. this.syncIterations = 5000;
  26672. this.aggressiveness = 7;
  26673. this.decimationIterations = 100;
  26674. }
  26675. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  26676. var _this = this;
  26677. this.initWithMesh(this._mesh, function () {
  26678. _this.runDecimation(settings, successCallback);
  26679. });
  26680. };
  26681. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  26682. var _this = this;
  26683. var targetCount = ~~(this.triangles.length * settings.quality);
  26684. var deletedTriangles = 0;
  26685. var triangleCount = this.triangles.length;
  26686. var iterationFunction = function (iteration, callback) {
  26687. setTimeout(function () {
  26688. if (iteration % 5 === 0) {
  26689. _this.updateMesh(iteration === 0);
  26690. }
  26691. for (var i = 0; i < _this.triangles.length; ++i) {
  26692. _this.triangles[i].isDirty = false;
  26693. }
  26694. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  26695. var trianglesIterator = function (i) {
  26696. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  26697. var t = _this.triangles[tIdx];
  26698. if (!t)
  26699. return;
  26700. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  26701. return;
  26702. }
  26703. for (var j = 0; j < 3; ++j) {
  26704. if (t.error[j] < threshold) {
  26705. var deleted0 = [];
  26706. var deleted1 = [];
  26707. var i0 = t.vertices[j];
  26708. var i1 = t.vertices[(j + 1) % 3];
  26709. var v0 = _this.vertices[i0];
  26710. var v1 = _this.vertices[i1];
  26711. if (v0.isBorder !== v1.isBorder)
  26712. continue;
  26713. var p = BABYLON.Vector3.Zero();
  26714. var n = BABYLON.Vector3.Zero();
  26715. var uv = BABYLON.Vector2.Zero();
  26716. var color = new BABYLON.Color4(0, 0, 0, 1);
  26717. _this.calculateError(v0, v1, p, n, uv, color);
  26718. var delTr = [];
  26719. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  26720. continue;
  26721. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  26722. continue;
  26723. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  26724. continue;
  26725. }
  26726. v0.normal = n;
  26727. if (v0.uv)
  26728. v0.uv = uv;
  26729. else if (v0.color)
  26730. v0.color = color;
  26731. v0.q = v1.q.add(v0.q);
  26732. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  26733. continue;
  26734. if (p.equals(v0.position))
  26735. continue;
  26736. v0.position = p;
  26737. var tStart = _this.references.length;
  26738. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  26739. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  26740. var tCount = _this.references.length - tStart;
  26741. if (tCount <= v0.triangleCount) {
  26742. if (tCount) {
  26743. for (var c = 0; c < tCount; c++) {
  26744. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  26745. }
  26746. }
  26747. }
  26748. else {
  26749. v0.triangleStart = tStart;
  26750. }
  26751. v0.triangleCount = tCount;
  26752. break;
  26753. }
  26754. }
  26755. };
  26756. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  26757. return (triangleCount - deletedTriangles <= targetCount);
  26758. });
  26759. }, 0);
  26760. };
  26761. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  26762. if (triangleCount - deletedTriangles <= targetCount)
  26763. loop.breakLoop();
  26764. else {
  26765. iterationFunction(loop.index, function () {
  26766. loop.executeNext();
  26767. });
  26768. }
  26769. }, function () {
  26770. setTimeout(function () {
  26771. successCallback(_this.reconstructMesh());
  26772. }, 0);
  26773. });
  26774. };
  26775. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  26776. var _this = this;
  26777. if (!mesh)
  26778. return;
  26779. this.vertices = [];
  26780. this.triangles = [];
  26781. this._mesh = mesh;
  26782. //It is assumed that a mesh has positions, normals and either uvs or colors.
  26783. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26784. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26785. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26786. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26787. var indices = mesh.getIndices();
  26788. var vertexInit = function (i) {
  26789. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), null, i);
  26790. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26791. vertex.uv = BABYLON.Vector2.FromArray(uvs, i * 2);
  26792. }
  26793. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26794. vertex.color = BABYLON.Color4.FromArray(colorsData, i * 4);
  26795. }
  26796. _this.vertices.push(vertex);
  26797. };
  26798. var totalVertices = mesh.getTotalVertices();
  26799. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  26800. var indicesInit = function (i) {
  26801. var pos = i * 3;
  26802. var i0 = indices[pos + 0];
  26803. var i1 = indices[pos + 1];
  26804. var i2 = indices[pos + 2];
  26805. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  26806. _this.triangles.push(triangle);
  26807. };
  26808. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  26809. _this.init(callback);
  26810. });
  26811. });
  26812. };
  26813. QuadraticErrorSimplification.prototype.init = function (callback) {
  26814. var _this = this;
  26815. var triangleInit1 = function (i) {
  26816. var t = _this.triangles[i];
  26817. 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();
  26818. for (var j = 0; j < 3; j++) {
  26819. _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))));
  26820. }
  26821. };
  26822. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  26823. var triangleInit2 = function (i) {
  26824. var t = _this.triangles[i];
  26825. for (var j = 0; j < 3; ++j) {
  26826. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  26827. }
  26828. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26829. };
  26830. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  26831. _this.initialised = true;
  26832. callback();
  26833. });
  26834. });
  26835. };
  26836. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  26837. var newTriangles = [];
  26838. var i;
  26839. for (i = 0; i < this.vertices.length; ++i) {
  26840. this.vertices[i].triangleCount = 0;
  26841. }
  26842. var t;
  26843. var j;
  26844. for (i = 0; i < this.triangles.length; ++i) {
  26845. if (!this.triangles[i].deleted) {
  26846. t = this.triangles[i];
  26847. for (j = 0; j < 3; ++j) {
  26848. this.vertices[t.vertices[j]].triangleCount = 1;
  26849. }
  26850. newTriangles.push(t);
  26851. }
  26852. }
  26853. var newVerticesOrder = [];
  26854. //compact vertices, get the IDs of the vertices used.
  26855. var dst = 0;
  26856. for (i = 0; i < this.vertices.length; ++i) {
  26857. if (this.vertices[i].triangleCount) {
  26858. this.vertices[i].triangleStart = dst;
  26859. this.vertices[dst].position = this.vertices[i].position;
  26860. this.vertices[dst].normal = this.vertices[i].normal;
  26861. this.vertices[dst].uv = this.vertices[i].uv;
  26862. this.vertices[dst].color = this.vertices[i].color;
  26863. newVerticesOrder.push(i);
  26864. dst++;
  26865. }
  26866. }
  26867. for (i = 0; i < newTriangles.length; ++i) {
  26868. t = newTriangles[i];
  26869. for (j = 0; j < 3; ++j) {
  26870. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  26871. }
  26872. }
  26873. this.vertices = this.vertices.slice(0, dst);
  26874. var newPositionData = [];
  26875. var newNormalData = [];
  26876. var newUVsData = [];
  26877. var newColorsData = [];
  26878. for (i = 0; i < newVerticesOrder.length; ++i) {
  26879. newPositionData.push(this.vertices[i].position.x);
  26880. newPositionData.push(this.vertices[i].position.y);
  26881. newPositionData.push(this.vertices[i].position.z);
  26882. newNormalData.push(this.vertices[i].normal.x);
  26883. newNormalData.push(this.vertices[i].normal.y);
  26884. newNormalData.push(this.vertices[i].normal.z);
  26885. if (this.vertices[i].uv) {
  26886. newUVsData.push(this.vertices[i].uv.x);
  26887. newUVsData.push(this.vertices[i].uv.y);
  26888. }
  26889. else if (this.vertices[i].color) {
  26890. newColorsData.push(this.vertices[i].color.r);
  26891. newColorsData.push(this.vertices[i].color.g);
  26892. newColorsData.push(this.vertices[i].color.b);
  26893. newColorsData.push(this.vertices[i].color.a);
  26894. }
  26895. }
  26896. var newIndicesArray = [];
  26897. for (i = 0; i < newTriangles.length; ++i) {
  26898. newIndicesArray.push(newTriangles[i].vertices[0]);
  26899. newIndicesArray.push(newTriangles[i].vertices[1]);
  26900. newIndicesArray.push(newTriangles[i].vertices[2]);
  26901. }
  26902. //not cloning, to avoid geometry problems. Creating a whole new mesh.
  26903. var newMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  26904. newMesh.material = this._mesh.material;
  26905. newMesh.parent = this._mesh.parent;
  26906. newMesh.setIndices(newIndicesArray);
  26907. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  26908. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  26909. if (newUVsData.length > 0)
  26910. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  26911. if (newColorsData.length > 0)
  26912. newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  26913. //preparing the skeleton support
  26914. if (this._mesh.skeleton) {
  26915. }
  26916. return newMesh;
  26917. };
  26918. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  26919. for (var i = 0; i < vertex1.triangleCount; ++i) {
  26920. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  26921. if (t.deleted)
  26922. continue;
  26923. var s = this.references[vertex1.triangleStart + i].vertexId;
  26924. var id1 = t.vertices[(s + 1) % 3];
  26925. var id2 = t.vertices[(s + 2) % 3];
  26926. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  26927. deletedArray[i] = true;
  26928. delTr.push(t);
  26929. continue;
  26930. }
  26931. var d1 = this.vertices[id1].position.subtract(point);
  26932. d1 = d1.normalize();
  26933. var d2 = this.vertices[id2].position.subtract(point);
  26934. d2 = d2.normalize();
  26935. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  26936. return true;
  26937. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  26938. deletedArray[i] = false;
  26939. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  26940. return true;
  26941. }
  26942. return false;
  26943. };
  26944. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  26945. var newDeleted = deletedTriangles;
  26946. for (var i = 0; i < vertex.triangleCount; ++i) {
  26947. var ref = this.references[vertex.triangleStart + i];
  26948. var t = this.triangles[ref.triangleId];
  26949. if (t.deleted)
  26950. continue;
  26951. if (deletedArray[i]) {
  26952. t.deleted = true;
  26953. newDeleted++;
  26954. continue;
  26955. }
  26956. t.vertices[ref.vertexId] = vertexId;
  26957. t.isDirty = true;
  26958. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  26959. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  26960. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  26961. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26962. this.references.push(ref);
  26963. }
  26964. return newDeleted;
  26965. };
  26966. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  26967. for (var i = 0; i < this.vertices.length; ++i) {
  26968. var vCount = [];
  26969. var vId = [];
  26970. var v = this.vertices[i];
  26971. var j;
  26972. for (j = 0; j < v.triangleCount; ++j) {
  26973. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  26974. for (var ii = 0; ii < 3; ii++) {
  26975. var ofs = 0;
  26976. var id = triangle.vertices[ii];
  26977. while (ofs < vCount.length) {
  26978. if (vId[ofs] === id)
  26979. break;
  26980. ++ofs;
  26981. }
  26982. if (ofs === vCount.length) {
  26983. vCount.push(1);
  26984. vId.push(id);
  26985. }
  26986. else {
  26987. vCount[ofs]++;
  26988. }
  26989. }
  26990. }
  26991. for (j = 0; j < vCount.length; ++j) {
  26992. if (vCount[j] === 1) {
  26993. this.vertices[vId[j]].isBorder = true;
  26994. }
  26995. else {
  26996. this.vertices[vId[j]].isBorder = false;
  26997. }
  26998. }
  26999. }
  27000. };
  27001. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  27002. if (identifyBorders === void 0) { identifyBorders = false; }
  27003. var i;
  27004. if (!identifyBorders) {
  27005. var newTrianglesVector = [];
  27006. for (i = 0; i < this.triangles.length; ++i) {
  27007. if (!this.triangles[i].deleted) {
  27008. newTrianglesVector.push(this.triangles[i]);
  27009. }
  27010. }
  27011. this.triangles = newTrianglesVector;
  27012. }
  27013. for (i = 0; i < this.vertices.length; ++i) {
  27014. this.vertices[i].triangleCount = 0;
  27015. this.vertices[i].triangleStart = 0;
  27016. }
  27017. var t;
  27018. var j;
  27019. var v;
  27020. for (i = 0; i < this.triangles.length; ++i) {
  27021. t = this.triangles[i];
  27022. for (j = 0; j < 3; ++j) {
  27023. v = this.vertices[t.vertices[j]];
  27024. v.triangleCount++;
  27025. }
  27026. }
  27027. var tStart = 0;
  27028. for (i = 0; i < this.vertices.length; ++i) {
  27029. this.vertices[i].triangleStart = tStart;
  27030. tStart += this.vertices[i].triangleCount;
  27031. this.vertices[i].triangleCount = 0;
  27032. }
  27033. var newReferences = new Array(this.triangles.length * 3);
  27034. for (i = 0; i < this.triangles.length; ++i) {
  27035. t = this.triangles[i];
  27036. for (j = 0; j < 3; ++j) {
  27037. v = this.vertices[t.vertices[j]];
  27038. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  27039. v.triangleCount++;
  27040. }
  27041. }
  27042. this.references = newReferences;
  27043. if (identifyBorders) {
  27044. this.identifyBorder();
  27045. }
  27046. };
  27047. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  27048. var x = point.x;
  27049. var y = point.y;
  27050. var z = point.z;
  27051. 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];
  27052. };
  27053. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  27054. var q = vertex1.q.add(vertex2.q);
  27055. var border = vertex1.isBorder && vertex2.isBorder;
  27056. var error = 0;
  27057. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  27058. if (qDet !== 0 && !border) {
  27059. if (!pointResult) {
  27060. pointResult = BABYLON.Vector3.Zero();
  27061. }
  27062. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  27063. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  27064. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  27065. error = this.vertexError(q, pointResult);
  27066. //TODO this should be correctly calculated
  27067. if (normalResult) {
  27068. normalResult.copyFrom(vertex1.normal);
  27069. if (vertex1.uv)
  27070. uvResult.copyFrom(vertex1.uv);
  27071. else if (vertex1.color)
  27072. colorResult.copyFrom(vertex1.color);
  27073. }
  27074. }
  27075. else {
  27076. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  27077. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  27078. var error1 = this.vertexError(q, vertex1.position);
  27079. var error2 = this.vertexError(q, vertex2.position);
  27080. var error3 = this.vertexError(q, p3);
  27081. error = Math.min(error1, error2, error3);
  27082. if (error === error1) {
  27083. if (pointResult) {
  27084. pointResult.copyFrom(vertex1.position);
  27085. normalResult.copyFrom(vertex1.normal);
  27086. if (vertex1.uv)
  27087. uvResult.copyFrom(vertex1.uv);
  27088. else if (vertex1.color)
  27089. colorResult.copyFrom(vertex1.color);
  27090. }
  27091. }
  27092. else if (error === error2) {
  27093. if (pointResult) {
  27094. pointResult.copyFrom(vertex2.position);
  27095. normalResult.copyFrom(vertex2.normal);
  27096. if (vertex2.uv)
  27097. uvResult.copyFrom(vertex2.uv);
  27098. else if (vertex2.color)
  27099. colorResult.copyFrom(vertex2.color);
  27100. }
  27101. }
  27102. else {
  27103. if (pointResult) {
  27104. pointResult.copyFrom(p3);
  27105. normalResult.copyFrom(vertex1.normal);
  27106. if (vertex1.uv)
  27107. uvResult.copyFrom(vertex1.uv);
  27108. else if (vertex1.color)
  27109. colorResult.copyFrom(vertex1.color);
  27110. }
  27111. }
  27112. }
  27113. return error;
  27114. };
  27115. return QuadraticErrorSimplification;
  27116. })();
  27117. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  27118. })(BABYLON || (BABYLON = {}));
  27119. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  27120. (function (BABYLON) {
  27121. var Analyser = (function () {
  27122. function Analyser(scene) {
  27123. this.SMOOTHING = 0.75;
  27124. this.FFT_SIZE = 512;
  27125. this.BARGRAPHAMPLITUDE = 256;
  27126. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  27127. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  27128. this._scene = scene;
  27129. this._audioEngine = BABYLON.Engine.audioEngine;
  27130. if (this._audioEngine.canUseWebAudio) {
  27131. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  27132. this._webAudioAnalyser.minDecibels = -140;
  27133. this._webAudioAnalyser.maxDecibels = 0;
  27134. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27135. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27136. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  27137. }
  27138. }
  27139. Analyser.prototype.getFrequencyBinCount = function () {
  27140. if (this._audioEngine.canUseWebAudio) {
  27141. return this._webAudioAnalyser.frequencyBinCount;
  27142. }
  27143. else {
  27144. return 0;
  27145. }
  27146. };
  27147. Analyser.prototype.getByteFrequencyData = function () {
  27148. if (this._audioEngine.canUseWebAudio) {
  27149. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27150. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27151. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  27152. }
  27153. return this._byteFreqs;
  27154. };
  27155. Analyser.prototype.getByteTimeDomainData = function () {
  27156. if (this._audioEngine.canUseWebAudio) {
  27157. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27158. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27159. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  27160. }
  27161. return this._byteTime;
  27162. };
  27163. Analyser.prototype.getFloatFrequencyData = function () {
  27164. if (this._audioEngine.canUseWebAudio) {
  27165. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27166. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27167. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  27168. }
  27169. return this._floatFreqs;
  27170. };
  27171. Analyser.prototype.drawDebugCanvas = function () {
  27172. var _this = this;
  27173. if (this._audioEngine.canUseWebAudio) {
  27174. if (!this._debugCanvas) {
  27175. this._debugCanvas = document.createElement("canvas");
  27176. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  27177. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  27178. this._debugCanvas.style.position = "absolute";
  27179. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  27180. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  27181. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  27182. document.body.appendChild(this._debugCanvas);
  27183. this._registerFunc = function () {
  27184. _this.drawDebugCanvas();
  27185. };
  27186. this._scene.registerBeforeRender(this._registerFunc);
  27187. }
  27188. if (this._registerFunc) {
  27189. var workingArray = this.getByteFrequencyData();
  27190. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  27191. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  27192. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  27193. var value = workingArray[i];
  27194. var percent = value / this.BARGRAPHAMPLITUDE;
  27195. var height = this.DEBUGCANVASSIZE.height * percent;
  27196. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  27197. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  27198. var hue = i / this.getFrequencyBinCount() * 360;
  27199. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  27200. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  27201. }
  27202. }
  27203. }
  27204. };
  27205. Analyser.prototype.stopDebugCanvas = function () {
  27206. if (this._debugCanvas) {
  27207. this._scene.unregisterBeforeRender(this._registerFunc);
  27208. this._registerFunc = null;
  27209. document.body.removeChild(this._debugCanvas);
  27210. this._debugCanvas = null;
  27211. this._debugCanvasContext = null;
  27212. }
  27213. };
  27214. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  27215. if (this._audioEngine.canUseWebAudio) {
  27216. inputAudioNode.connect(this._webAudioAnalyser);
  27217. this._webAudioAnalyser.connect(outputAudioNode);
  27218. }
  27219. };
  27220. Analyser.prototype.dispose = function () {
  27221. if (this._audioEngine.canUseWebAudio) {
  27222. this._webAudioAnalyser.disconnect();
  27223. }
  27224. };
  27225. return Analyser;
  27226. })();
  27227. BABYLON.Analyser = Analyser;
  27228. })(BABYLON || (BABYLON = {}));
  27229. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  27230. (function (BABYLON) {
  27231. var DepthRenderer = (function () {
  27232. function DepthRenderer(scene, type) {
  27233. var _this = this;
  27234. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  27235. this._viewMatrix = BABYLON.Matrix.Zero();
  27236. this._projectionMatrix = BABYLON.Matrix.Zero();
  27237. this._transformMatrix = BABYLON.Matrix.Zero();
  27238. this._worldViewProjection = BABYLON.Matrix.Zero();
  27239. this._scene = scene;
  27240. var engine = scene.getEngine();
  27241. // Render target
  27242. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  27243. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27244. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27245. this._depthMap.refreshRate = 1;
  27246. this._depthMap.renderParticles = false;
  27247. this._depthMap.renderList = null;
  27248. // Custom render function
  27249. var renderSubMesh = function (subMesh) {
  27250. var mesh = subMesh.getRenderingMesh();
  27251. var scene = _this._scene;
  27252. var engine = scene.getEngine();
  27253. // Culling
  27254. engine.setState(subMesh.getMaterial().backFaceCulling);
  27255. // Managing instances
  27256. var batch = mesh._getInstancesRenderList(subMesh._id);
  27257. if (batch.mustReturn) {
  27258. return;
  27259. }
  27260. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  27261. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  27262. engine.enableEffect(_this._effect);
  27263. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  27264. var material = subMesh.getMaterial();
  27265. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27266. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  27267. // Alpha test
  27268. if (material && material.needAlphaTesting()) {
  27269. var alphaTexture = material.getAlphaTestTexture();
  27270. _this._effect.setTexture("diffuseSampler", alphaTexture);
  27271. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27272. }
  27273. // Bones
  27274. if (mesh.useBones) {
  27275. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27276. }
  27277. // Draw
  27278. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  27279. }
  27280. };
  27281. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  27282. var index;
  27283. for (index = 0; index < opaqueSubMeshes.length; index++) {
  27284. renderSubMesh(opaqueSubMeshes.data[index]);
  27285. }
  27286. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  27287. renderSubMesh(alphaTestSubMeshes.data[index]);
  27288. }
  27289. };
  27290. }
  27291. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  27292. var defines = [];
  27293. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27294. var mesh = subMesh.getMesh();
  27295. var scene = mesh.getScene();
  27296. var material = subMesh.getMaterial();
  27297. // Alpha test
  27298. if (material && material.needAlphaTesting()) {
  27299. defines.push("#define ALPHATEST");
  27300. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27301. attribs.push(BABYLON.VertexBuffer.UVKind);
  27302. defines.push("#define UV1");
  27303. }
  27304. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27305. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27306. defines.push("#define UV2");
  27307. }
  27308. }
  27309. // Bones
  27310. if (mesh.useBones) {
  27311. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27312. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27313. defines.push("#define BONES");
  27314. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27315. }
  27316. // Instances
  27317. if (useInstances) {
  27318. defines.push("#define INSTANCES");
  27319. attribs.push("world0");
  27320. attribs.push("world1");
  27321. attribs.push("world2");
  27322. attribs.push("world3");
  27323. }
  27324. // Get correct effect
  27325. var join = defines.join("\n");
  27326. if (this._cachedDefines !== join) {
  27327. this._cachedDefines = join;
  27328. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  27329. }
  27330. return this._effect.isReady();
  27331. };
  27332. DepthRenderer.prototype.getDepthMap = function () {
  27333. return this._depthMap;
  27334. };
  27335. // Methods
  27336. DepthRenderer.prototype.dispose = function () {
  27337. this._depthMap.dispose();
  27338. };
  27339. return DepthRenderer;
  27340. })();
  27341. BABYLON.DepthRenderer = DepthRenderer;
  27342. })(BABYLON || (BABYLON = {}));
  27343. //# sourceMappingURL=babylon.depthRenderer.js.map
  27344. var BABYLON;
  27345. (function (BABYLON) {
  27346. var SSAORenderingPipeline = (function (_super) {
  27347. __extends(SSAORenderingPipeline, _super);
  27348. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  27349. var _this = this;
  27350. if (ratio === void 0) { ratio = 1.0; }
  27351. _super.call(this, scene.getEngine(), name);
  27352. // Members
  27353. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  27354. this.SSAORenderEffect = "SSAORenderEffect";
  27355. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  27356. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  27357. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  27358. this._firstUpdate = true;
  27359. this._scene = scene;
  27360. // Set up assets
  27361. this._createRandomTexture();
  27362. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  27363. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27364. this._createSSAOPostProcess(ratio);
  27365. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 1.0, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27366. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 1.0, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27367. this._createSSAOCombinePostProcess();
  27368. // Set up pipeline
  27369. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  27370. return _this._originalColorPostProcess;
  27371. }, true));
  27372. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  27373. return _this._ssaoPostProcess;
  27374. }, true));
  27375. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  27376. return _this._blurHPostProcess;
  27377. }, true));
  27378. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  27379. return _this._blurVPostProcess;
  27380. }, true));
  27381. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  27382. return _this._ssaoCombinePostProcess;
  27383. }, true));
  27384. // Finish
  27385. scene.postProcessRenderPipelineManager.addPipeline(this);
  27386. }
  27387. // Public Methods
  27388. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  27389. return this._blurHPostProcess;
  27390. };
  27391. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  27392. return this._blurVPostProcess;
  27393. };
  27394. SSAORenderingPipeline.prototype.dispose = function (cameras) {
  27395. if (cameras !== undefined)
  27396. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, cameras);
  27397. this._originalColorPostProcess = undefined;
  27398. this._ssaoPostProcess = undefined;
  27399. this._blurHPostProcess = undefined;
  27400. this._blurVPostProcess = undefined;
  27401. this._ssaoCombinePostProcess = undefined;
  27402. this._randomTexture.dispose();
  27403. };
  27404. // Private Methods
  27405. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  27406. var _this = this;
  27407. var sampleSphere = [
  27408. 0.5381,
  27409. 0.1856,
  27410. -0.4319,
  27411. 0.1379,
  27412. 0.2486,
  27413. 0.4430,
  27414. 0.3371,
  27415. 0.5679,
  27416. -0.0057,
  27417. -0.6999,
  27418. -0.0451,
  27419. -0.0019,
  27420. 0.0689,
  27421. -0.1598,
  27422. -0.8547,
  27423. 0.0560,
  27424. 0.0069,
  27425. -0.1843,
  27426. -0.0146,
  27427. 0.1402,
  27428. 0.0762,
  27429. 0.0100,
  27430. -0.1924,
  27431. -0.0344,
  27432. -0.3577,
  27433. -0.5301,
  27434. -0.4358,
  27435. -0.3169,
  27436. 0.1063,
  27437. 0.0158,
  27438. 0.0103,
  27439. -0.5869,
  27440. 0.0046,
  27441. -0.0897,
  27442. -0.4940,
  27443. 0.3287,
  27444. 0.7119,
  27445. -0.0154,
  27446. -0.0918,
  27447. -0.0533,
  27448. 0.0596,
  27449. -0.5411,
  27450. 0.0352,
  27451. -0.0631,
  27452. 0.5460,
  27453. -0.4776,
  27454. 0.2847,
  27455. -0.0271
  27456. ];
  27457. var samplesFactor = 1.0 / 16.0;
  27458. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  27459. this._ssaoPostProcess.onApply = function (effect) {
  27460. if (_this._firstUpdate) {
  27461. effect.setArray3("sampleSphere", sampleSphere);
  27462. effect.setFloat("samplesFactor", samplesFactor);
  27463. _this._firstUpdate = false;
  27464. }
  27465. effect.setTexture("textureSampler", _this._depthTexture);
  27466. effect.setTexture("randomSampler", _this._randomTexture);
  27467. };
  27468. return this._ssaoPostProcess;
  27469. };
  27470. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function () {
  27471. var _this = this;
  27472. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  27473. this._ssaoCombinePostProcess.onApply = function (effect) {
  27474. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  27475. };
  27476. return this._ssaoCombinePostProcess;
  27477. };
  27478. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  27479. var size = 512;
  27480. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  27481. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  27482. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  27483. var context = this._randomTexture.getContext();
  27484. var rand = function (min, max) {
  27485. return Math.random() * (max - min) + min;
  27486. };
  27487. for (var x = 0; x < size; x++) {
  27488. for (var y = 0; y < size; y++) {
  27489. var randVector = BABYLON.Vector3.Zero();
  27490. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  27491. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  27492. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  27493. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  27494. context.fillRect(x, y, 1, 1);
  27495. }
  27496. }
  27497. this._randomTexture.update(false);
  27498. };
  27499. return SSAORenderingPipeline;
  27500. })(BABYLON.PostProcessRenderPipeline);
  27501. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  27502. })(BABYLON || (BABYLON = {}));
  27503. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  27504. var BABYLON;
  27505. (function (BABYLON) {
  27506. var GodRaysPostProcess = (function (_super) {
  27507. __extends(GodRaysPostProcess, _super);
  27508. function GodRaysPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27509. var _this = this;
  27510. _super.call(this, name, "volumetricLightScattering", ["lightPositionOnScreen"], ["lightScatteringSampler"], ratio, camera, samplingMode, engine, reusable);
  27511. this._screenCoordinates = BABYLON.Vector2.Zero();
  27512. this.invert = true;
  27513. var scene = camera.getScene();
  27514. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  27515. // Create billboard
  27516. this.mesh = BABYLON.Mesh.CreatePlane("VolumetricLightScatteringMesh", 2, scene);
  27517. this.mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  27518. this.mesh.material = new BABYLON.StandardMaterial('VolumetricLightScatteringMaterial', scene);
  27519. // Configure
  27520. this._createPass(scene);
  27521. this.onApply = function (effect) {
  27522. _this._updateScreenCoordinates(scene);
  27523. effect.setTexture("lightScatteringSampler", _this._godRaysRTT);
  27524. effect.setVector2("lightPositionOnScreen", _this._screenCoordinates);
  27525. };
  27526. }
  27527. GodRaysPostProcess.prototype.isReady = function (subMesh, useInstances) {
  27528. var mesh = subMesh.getMesh();
  27529. var scene = mesh.getScene();
  27530. var defines = [];
  27531. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27532. var material = subMesh.getMaterial();
  27533. // Render this.mesh as default
  27534. if (mesh === this.mesh)
  27535. defines.push("#define BASIC_RENDER");
  27536. // Alpha test
  27537. if (material) {
  27538. if (material.needAlphaTesting() || mesh === this.mesh)
  27539. defines.push("#define ALPHATEST");
  27540. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27541. attribs.push(BABYLON.VertexBuffer.UVKind);
  27542. defines.push("#define UV1");
  27543. }
  27544. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27545. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27546. defines.push("#define UV2");
  27547. }
  27548. }
  27549. // Bones
  27550. if (mesh.useBones) {
  27551. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27552. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27553. defines.push("#define BONES");
  27554. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27555. }
  27556. // Instances
  27557. if (useInstances) {
  27558. defines.push("#define INSTANCES");
  27559. attribs.push("world0");
  27560. attribs.push("world1");
  27561. attribs.push("world2");
  27562. attribs.push("world3");
  27563. }
  27564. // Get correct effect
  27565. var join = defines.join("\n");
  27566. if (this._cachedDefines !== join) {
  27567. this._cachedDefines = join;
  27568. this._godRaysPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  27569. }
  27570. return this._godRaysPass.isReady();
  27571. };
  27572. GodRaysPostProcess.prototype.dispose = function (camera) {
  27573. this._godRaysRTT.dispose();
  27574. _super.prototype.dispose.call(this, camera);
  27575. };
  27576. GodRaysPostProcess.prototype.getPass = function () {
  27577. return this._godRaysRTT;
  27578. };
  27579. // Private methods
  27580. GodRaysPostProcess.prototype._createPass = function (scene) {
  27581. var _this = this;
  27582. var engine = scene.getEngine();
  27583. this._godRaysRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  27584. this._godRaysRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27585. this._godRaysRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27586. this._godRaysRTT.renderList = null;
  27587. scene.customRenderTargets.push(this._godRaysRTT);
  27588. // Custom render function for submeshes
  27589. var renderSubMesh = function (subMesh) {
  27590. var mesh = subMesh.getRenderingMesh();
  27591. var scene = mesh.getScene();
  27592. var engine = scene.getEngine();
  27593. // Culling
  27594. engine.setState(subMesh.getMaterial().backFaceCulling);
  27595. // Managing instances
  27596. var batch = mesh._getInstancesRenderList(subMesh._id);
  27597. if (batch.mustReturn) {
  27598. return;
  27599. }
  27600. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  27601. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  27602. engine.enableEffect(_this._godRaysPass);
  27603. mesh._bind(subMesh, _this._godRaysPass, BABYLON.Material.TriangleFillMode);
  27604. var material = subMesh.getMaterial();
  27605. _this._godRaysPass.setMatrix("viewProjection", scene.getTransformMatrix());
  27606. // Alpha test
  27607. if (material && (mesh === _this.mesh || material.needAlphaTesting())) {
  27608. var alphaTexture = material.getAlphaTestTexture();
  27609. _this._godRaysPass.setTexture("diffuseSampler", alphaTexture);
  27610. _this._godRaysPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27611. }
  27612. // Bones
  27613. if (mesh.useBones) {
  27614. _this._godRaysPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27615. }
  27616. // Draw
  27617. mesh._processRendering(subMesh, _this._godRaysPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._godRaysPass.setMatrix("world", world); });
  27618. }
  27619. };
  27620. // Render target texture callbacks
  27621. var savedSceneClearColor = null;
  27622. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  27623. this._godRaysRTT.onBeforeRender = function () {
  27624. savedSceneClearColor = scene.clearColor;
  27625. scene.clearColor = sceneClearColor;
  27626. };
  27627. this._godRaysRTT.onAfterRender = function () {
  27628. scene.clearColor = savedSceneClearColor;
  27629. };
  27630. this._godRaysRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  27631. var index;
  27632. for (index = 0; index < opaqueSubMeshes.length; index++) {
  27633. renderSubMesh(opaqueSubMeshes.data[index]);
  27634. }
  27635. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  27636. renderSubMesh(alphaTestSubMeshes.data[index]);
  27637. }
  27638. };
  27639. };
  27640. GodRaysPostProcess.prototype._updateScreenCoordinates = function (scene) {
  27641. var transform = scene.getTransformMatrix();
  27642. var pos = BABYLON.Vector3.Project(this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  27643. this._screenCoordinates.x = pos.x / this._viewPort.width;
  27644. this._screenCoordinates.y = pos.y / this._viewPort.height;
  27645. if (this.invert)
  27646. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  27647. };
  27648. return GodRaysPostProcess;
  27649. })(BABYLON.PostProcess);
  27650. BABYLON.GodRaysPostProcess = GodRaysPostProcess;
  27651. })(BABYLON || (BABYLON = {}));
  27652. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map