babylon.2.1-beta.debug.js 1.5 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596
  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. return this;
  29. };
  30. Color3.prototype.toColor4 = function (alpha) {
  31. if (alpha === void 0) { alpha = 1; }
  32. return new Color4(this.r, this.g, this.b, alpha);
  33. };
  34. Color3.prototype.asArray = function () {
  35. var result = [];
  36. this.toArray(result, 0);
  37. return result;
  38. };
  39. Color3.prototype.toLuminance = function () {
  40. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  41. };
  42. Color3.prototype.multiply = function (otherColor) {
  43. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  44. };
  45. Color3.prototype.multiplyToRef = function (otherColor, result) {
  46. result.r = this.r * otherColor.r;
  47. result.g = this.g * otherColor.g;
  48. result.b = this.b * otherColor.b;
  49. return this;
  50. };
  51. Color3.prototype.equals = function (otherColor) {
  52. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  53. };
  54. Color3.prototype.scale = function (scale) {
  55. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  56. };
  57. Color3.prototype.scaleToRef = function (scale, result) {
  58. result.r = this.r * scale;
  59. result.g = this.g * scale;
  60. result.b = this.b * scale;
  61. return this;
  62. };
  63. Color3.prototype.add = function (otherColor) {
  64. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  65. };
  66. Color3.prototype.addToRef = function (otherColor, result) {
  67. result.r = this.r + otherColor.r;
  68. result.g = this.g + otherColor.g;
  69. result.b = this.b + otherColor.b;
  70. return this;
  71. };
  72. Color3.prototype.subtract = function (otherColor) {
  73. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  74. };
  75. Color3.prototype.subtractToRef = function (otherColor, result) {
  76. result.r = this.r - otherColor.r;
  77. result.g = this.g - otherColor.g;
  78. result.b = this.b - otherColor.b;
  79. return this;
  80. };
  81. Color3.prototype.clone = function () {
  82. return new Color3(this.r, this.g, this.b);
  83. };
  84. Color3.prototype.copyFrom = function (source) {
  85. this.r = source.r;
  86. this.g = source.g;
  87. this.b = source.b;
  88. return this;
  89. };
  90. Color3.prototype.copyFromFloats = function (r, g, b) {
  91. this.r = r;
  92. this.g = g;
  93. this.b = b;
  94. return this;
  95. };
  96. // Statics
  97. Color3.FromArray = function (array, offset) {
  98. if (offset === void 0) { offset = 0; }
  99. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  100. };
  101. Color3.FromInts = function (r, g, b) {
  102. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  103. };
  104. Color3.Lerp = function (start, end, amount) {
  105. var r = start.r + ((end.r - start.r) * amount);
  106. var g = start.g + ((end.g - start.g) * amount);
  107. var b = start.b + ((end.b - start.b) * amount);
  108. return new Color3(r, g, b);
  109. };
  110. Color3.Red = function () {
  111. return new Color3(1, 0, 0);
  112. };
  113. Color3.Green = function () {
  114. return new Color3(0, 1, 0);
  115. };
  116. Color3.Blue = function () {
  117. return new Color3(0, 0, 1);
  118. };
  119. Color3.Black = function () {
  120. return new Color3(0, 0, 0);
  121. };
  122. Color3.White = function () {
  123. return new Color3(1, 1, 1);
  124. };
  125. Color3.Purple = function () {
  126. return new Color3(0.5, 0, 0.5);
  127. };
  128. Color3.Magenta = function () {
  129. return new Color3(1, 0, 1);
  130. };
  131. Color3.Yellow = function () {
  132. return new Color3(1, 1, 0);
  133. };
  134. Color3.Gray = function () {
  135. return new Color3(0.5, 0.5, 0.5);
  136. };
  137. return Color3;
  138. })();
  139. BABYLON.Color3 = Color3;
  140. var Color4 = (function () {
  141. function Color4(r, g, b, a) {
  142. this.r = r;
  143. this.g = g;
  144. this.b = b;
  145. this.a = a;
  146. }
  147. // Operators
  148. Color4.prototype.addInPlace = function (right) {
  149. this.r += right.r;
  150. this.g += right.g;
  151. this.b += right.b;
  152. this.a += right.a;
  153. return this;
  154. };
  155. Color4.prototype.asArray = function () {
  156. var result = [];
  157. this.toArray(result, 0);
  158. return result;
  159. };
  160. Color4.prototype.toArray = function (array, index) {
  161. if (index === undefined) {
  162. index = 0;
  163. }
  164. array[index] = this.r;
  165. array[index + 1] = this.g;
  166. array[index + 2] = this.b;
  167. array[index + 3] = this.a;
  168. return this;
  169. };
  170. Color4.prototype.add = function (right) {
  171. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  172. };
  173. Color4.prototype.subtract = function (right) {
  174. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  175. };
  176. Color4.prototype.subtractToRef = function (right, result) {
  177. result.r = this.r - right.r;
  178. result.g = this.g - right.g;
  179. result.b = this.b - right.b;
  180. result.a = this.a - right.a;
  181. return this;
  182. };
  183. Color4.prototype.scale = function (scale) {
  184. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  185. };
  186. Color4.prototype.scaleToRef = function (scale, result) {
  187. result.r = this.r * scale;
  188. result.g = this.g * scale;
  189. result.b = this.b * scale;
  190. result.a = this.a * scale;
  191. return this;
  192. };
  193. Color4.prototype.toString = function () {
  194. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  195. };
  196. Color4.prototype.clone = function () {
  197. return new Color4(this.r, this.g, this.b, this.a);
  198. };
  199. Color4.prototype.copyFrom = function (source) {
  200. this.r = source.r;
  201. this.g = source.g;
  202. this.b = source.b;
  203. this.a = source.a;
  204. return this;
  205. };
  206. // Statics
  207. Color4.Lerp = function (left, right, amount) {
  208. var result = new Color4(0, 0, 0, 0);
  209. Color4.LerpToRef(left, right, amount, result);
  210. return result;
  211. };
  212. Color4.LerpToRef = function (left, right, amount, result) {
  213. result.r = left.r + (right.r - left.r) * amount;
  214. result.g = left.g + (right.g - left.g) * amount;
  215. result.b = left.b + (right.b - left.b) * amount;
  216. result.a = left.a + (right.a - left.a) * amount;
  217. };
  218. Color4.FromArray = function (array, offset) {
  219. if (offset === void 0) { offset = 0; }
  220. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  221. };
  222. Color4.FromInts = function (r, g, b, a) {
  223. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  224. };
  225. return Color4;
  226. })();
  227. BABYLON.Color4 = Color4;
  228. var Vector2 = (function () {
  229. function Vector2(x, y) {
  230. this.x = x;
  231. this.y = y;
  232. }
  233. Vector2.prototype.toString = function () {
  234. return "{X: " + this.x + " Y:" + this.y + "}";
  235. };
  236. // Operators
  237. Vector2.prototype.toArray = function (array, index) {
  238. if (index === void 0) { index = 0; }
  239. array[index] = this.x;
  240. array[index + 1] = this.y;
  241. return this;
  242. };
  243. Vector2.prototype.asArray = function () {
  244. var result = [];
  245. this.toArray(result, 0);
  246. return result;
  247. };
  248. Vector2.prototype.copyFrom = function (source) {
  249. this.x = source.x;
  250. this.y = source.y;
  251. return this;
  252. };
  253. Vector2.prototype.copyFromFloats = function (x, y) {
  254. this.x = x;
  255. this.y = y;
  256. return this;
  257. };
  258. Vector2.prototype.add = function (otherVector) {
  259. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  260. };
  261. Vector2.prototype.addVector3 = function (otherVector) {
  262. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  263. };
  264. Vector2.prototype.subtract = function (otherVector) {
  265. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  266. };
  267. Vector2.prototype.subtractInPlace = function (otherVector) {
  268. this.x -= otherVector.x;
  269. this.y -= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiplyInPlace = function (otherVector) {
  273. this.x *= otherVector.x;
  274. this.y *= otherVector.y;
  275. return this;
  276. };
  277. Vector2.prototype.multiply = function (otherVector) {
  278. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  279. };
  280. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  281. result.x = this.x * otherVector.x;
  282. result.y = this.y * otherVector.y;
  283. return this;
  284. };
  285. Vector2.prototype.multiplyByFloats = function (x, y) {
  286. return new Vector2(this.x * x, this.y * y);
  287. };
  288. Vector2.prototype.divide = function (otherVector) {
  289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  290. };
  291. Vector2.prototype.divideToRef = function (otherVector, result) {
  292. result.x = this.x / otherVector.x;
  293. result.y = this.y / otherVector.y;
  294. return this;
  295. };
  296. Vector2.prototype.negate = function () {
  297. return new Vector2(-this.x, -this.y);
  298. };
  299. Vector2.prototype.scaleInPlace = function (scale) {
  300. this.x *= scale;
  301. this.y *= scale;
  302. return this;
  303. };
  304. Vector2.prototype.scale = function (scale) {
  305. return new Vector2(this.x * scale, this.y * scale);
  306. };
  307. Vector2.prototype.equals = function (otherVector) {
  308. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  309. };
  310. // Properties
  311. Vector2.prototype.length = function () {
  312. return Math.sqrt(this.x * this.x + this.y * this.y);
  313. };
  314. Vector2.prototype.lengthSquared = function () {
  315. return (this.x * this.x + this.y * this.y);
  316. };
  317. // Methods
  318. Vector2.prototype.normalize = function () {
  319. var len = this.length();
  320. if (len === 0)
  321. return this;
  322. var num = 1.0 / len;
  323. this.x *= num;
  324. this.y *= num;
  325. return this;
  326. };
  327. Vector2.prototype.clone = function () {
  328. return new Vector2(this.x, this.y);
  329. };
  330. // Statics
  331. Vector2.Zero = function () {
  332. return new Vector2(0, 0);
  333. };
  334. Vector2.FromArray = function (array, offset) {
  335. if (offset === void 0) { offset = 0; }
  336. return new Vector2(array[offset], array[offset + 1]);
  337. };
  338. Vector2.FromArrayToRef = function (array, offset, result) {
  339. result.x = array[offset];
  340. result.y = array[offset + 1];
  341. };
  342. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. 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));
  346. 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));
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Clamp = function (value, min, max) {
  350. var x = value.x;
  351. x = (x > max.x) ? max.x : x;
  352. x = (x < min.x) ? min.x : x;
  353. var y = value.y;
  354. y = (y > max.y) ? max.y : y;
  355. y = (y < min.y) ? min.y : y;
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  359. var squared = amount * amount;
  360. var cubed = amount * squared;
  361. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  362. var part2 = (-2.0 * cubed) + (3.0 * squared);
  363. var part3 = (cubed - (2.0 * squared)) + amount;
  364. var part4 = cubed - squared;
  365. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  366. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Lerp = function (start, end, amount) {
  370. var x = start.x + ((end.x - start.x) * amount);
  371. var y = start.y + ((end.y - start.y) * amount);
  372. return new Vector2(x, y);
  373. };
  374. Vector2.Dot = function (left, right) {
  375. return left.x * right.x + left.y * right.y;
  376. };
  377. Vector2.Normalize = function (vector) {
  378. var newVector = vector.clone();
  379. newVector.normalize();
  380. return newVector;
  381. };
  382. Vector2.Minimize = function (left, right) {
  383. var x = (left.x < right.x) ? left.x : right.x;
  384. var y = (left.y < right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Maximize = function (left, right) {
  388. var x = (left.x > right.x) ? left.x : right.x;
  389. var y = (left.y > right.y) ? left.y : right.y;
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Transform = function (vector, transformation) {
  393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Distance = function (value1, value2) {
  398. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  399. };
  400. Vector2.DistanceSquared = function (value1, value2) {
  401. var x = value1.x - value2.x;
  402. var y = value1.y - value2.y;
  403. return (x * x) + (y * y);
  404. };
  405. return Vector2;
  406. })();
  407. BABYLON.Vector2 = Vector2;
  408. var Vector3 = (function () {
  409. function Vector3(x, y, z) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. }
  414. Vector3.prototype.toString = function () {
  415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  416. };
  417. // Operators
  418. Vector3.prototype.asArray = function () {
  419. var result = [];
  420. this.toArray(result, 0);
  421. return result;
  422. };
  423. Vector3.prototype.toArray = function (array, index) {
  424. if (index === void 0) { index = 0; }
  425. array[index] = this.x;
  426. array[index + 1] = this.y;
  427. array[index + 2] = this.z;
  428. return this;
  429. };
  430. Vector3.prototype.toQuaternion = function () {
  431. var result = new Quaternion(0, 0, 0, 1);
  432. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  433. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  434. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  435. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  436. var cosy = Math.cos(this.y * 0.5);
  437. var siny = Math.sin(this.y * 0.5);
  438. result.x = coszMinusx * siny;
  439. result.y = -sinzMinusx * siny;
  440. result.z = sinxPlusz * cosy;
  441. result.w = cosxPlusz * cosy;
  442. return result;
  443. };
  444. Vector3.prototype.addInPlace = function (otherVector) {
  445. this.x += otherVector.x;
  446. this.y += otherVector.y;
  447. this.z += otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.add = function (otherVector) {
  451. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  452. };
  453. Vector3.prototype.addToRef = function (otherVector, result) {
  454. result.x = this.x + otherVector.x;
  455. result.y = this.y + otherVector.y;
  456. result.z = this.z + otherVector.z;
  457. return this;
  458. };
  459. Vector3.prototype.subtractInPlace = function (otherVector) {
  460. this.x -= otherVector.x;
  461. this.y -= otherVector.y;
  462. this.z -= otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtract = function (otherVector) {
  466. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  467. };
  468. Vector3.prototype.subtractToRef = function (otherVector, result) {
  469. result.x = this.x - otherVector.x;
  470. result.y = this.y - otherVector.y;
  471. result.z = this.z - otherVector.z;
  472. return this;
  473. };
  474. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  475. return new Vector3(this.x - x, this.y - y, this.z - z);
  476. };
  477. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  478. result.x = this.x - x;
  479. result.y = this.y - y;
  480. result.z = this.z - z;
  481. return this;
  482. };
  483. Vector3.prototype.negate = function () {
  484. return new Vector3(-this.x, -this.y, -this.z);
  485. };
  486. Vector3.prototype.scaleInPlace = function (scale) {
  487. this.x *= scale;
  488. this.y *= scale;
  489. this.z *= scale;
  490. return this;
  491. };
  492. Vector3.prototype.scale = function (scale) {
  493. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  494. };
  495. Vector3.prototype.scaleToRef = function (scale, result) {
  496. result.x = this.x * scale;
  497. result.y = this.y * scale;
  498. result.z = this.z * scale;
  499. };
  500. Vector3.prototype.equals = function (otherVector) {
  501. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  502. };
  503. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  504. 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;
  505. };
  506. Vector3.prototype.equalsToFloats = function (x, y, z) {
  507. return this.x === x && this.y === y && this.z === z;
  508. };
  509. Vector3.prototype.multiplyInPlace = function (otherVector) {
  510. this.x *= otherVector.x;
  511. this.y *= otherVector.y;
  512. this.z *= otherVector.z;
  513. return this;
  514. };
  515. Vector3.prototype.multiply = function (otherVector) {
  516. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  517. };
  518. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  519. result.x = this.x * otherVector.x;
  520. result.y = this.y * otherVector.y;
  521. result.z = this.z * otherVector.z;
  522. return this;
  523. };
  524. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  525. return new Vector3(this.x * x, this.y * y, this.z * z);
  526. };
  527. Vector3.prototype.divide = function (otherVector) {
  528. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  529. };
  530. Vector3.prototype.divideToRef = function (otherVector, result) {
  531. result.x = this.x / otherVector.x;
  532. result.y = this.y / otherVector.y;
  533. result.z = this.z / otherVector.z;
  534. return this;
  535. };
  536. Vector3.prototype.MinimizeInPlace = function (other) {
  537. if (other.x < this.x)
  538. this.x = other.x;
  539. if (other.y < this.y)
  540. this.y = other.y;
  541. if (other.z < this.z)
  542. this.z = other.z;
  543. return this;
  544. };
  545. Vector3.prototype.MaximizeInPlace = function (other) {
  546. if (other.x > this.x)
  547. this.x = other.x;
  548. if (other.y > this.y)
  549. this.y = other.y;
  550. if (other.z > this.z)
  551. this.z = other.z;
  552. return this;
  553. };
  554. // Properties
  555. Vector3.prototype.length = function () {
  556. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  557. };
  558. Vector3.prototype.lengthSquared = function () {
  559. return (this.x * this.x + this.y * this.y + this.z * this.z);
  560. };
  561. // Methods
  562. Vector3.prototype.normalize = function () {
  563. var len = this.length();
  564. if (len === 0)
  565. return this;
  566. var num = 1.0 / len;
  567. this.x *= num;
  568. this.y *= num;
  569. this.z *= num;
  570. return this;
  571. };
  572. Vector3.prototype.clone = function () {
  573. return new Vector3(this.x, this.y, this.z);
  574. };
  575. Vector3.prototype.copyFrom = function (source) {
  576. this.x = source.x;
  577. this.y = source.y;
  578. this.z = source.z;
  579. return this;
  580. };
  581. Vector3.prototype.copyFromFloats = function (x, y, z) {
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. };
  587. // Statics
  588. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  589. var d0 = Vector3.Dot(vector0, axis) - size;
  590. var d1 = Vector3.Dot(vector1, axis) - size;
  591. var s = d0 / (d0 - d1);
  592. return s;
  593. };
  594. Vector3.FromArray = function (array, offset) {
  595. if (!offset) {
  596. offset = 0;
  597. }
  598. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  599. };
  600. Vector3.FromArrayToRef = function (array, offset, result) {
  601. result.x = array[offset];
  602. result.y = array[offset + 1];
  603. result.z = array[offset + 2];
  604. };
  605. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  606. result.x = array[offset];
  607. result.y = array[offset + 1];
  608. result.z = array[offset + 2];
  609. };
  610. Vector3.FromFloatsToRef = function (x, y, z, result) {
  611. result.x = x;
  612. result.y = y;
  613. result.z = z;
  614. };
  615. Vector3.Zero = function () {
  616. return new Vector3(0, 0, 0);
  617. };
  618. Vector3.Up = function () {
  619. return new Vector3(0, 1.0, 0);
  620. };
  621. Vector3.TransformCoordinates = function (vector, transformation) {
  622. var result = Vector3.Zero();
  623. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  624. return result;
  625. };
  626. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  627. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  628. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  629. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  630. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  631. result.x = x / w;
  632. result.y = y / w;
  633. result.z = z / w;
  634. };
  635. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  636. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  637. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  638. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  639. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  640. result.x = rx / rw;
  641. result.y = ry / rw;
  642. result.z = rz / rw;
  643. };
  644. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  645. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  646. var m0 = SIMD.float32x4.load(transformation.m, 0);
  647. var m1 = SIMD.float32x4.load(transformation.m, 4);
  648. var m2 = SIMD.float32x4.load(transformation.m, 8);
  649. var m3 = SIMD.float32x4.load(transformation.m, 12);
  650. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  651. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  652. SIMD.float32x4.storeXYZ(result._data, 0, r);
  653. };
  654. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  655. var v0 = SIMD.float32x4.splat(x);
  656. var v1 = SIMD.float32x4.splat(y);
  657. var v2 = SIMD.float32x4.splat(z);
  658. var m0 = SIMD.float32x4.load(transformation.m, 0);
  659. var m1 = SIMD.float32x4.load(transformation.m, 4);
  660. var m2 = SIMD.float32x4.load(transformation.m, 8);
  661. var m3 = SIMD.float32x4.load(transformation.m, 12);
  662. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  663. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  664. SIMD.float32x4.storeXYZ(result._data, 0, r);
  665. };
  666. Vector3.TransformNormal = function (vector, transformation) {
  667. var result = Vector3.Zero();
  668. Vector3.TransformNormalToRef(vector, transformation, result);
  669. return result;
  670. };
  671. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  672. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  673. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  674. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  675. };
  676. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  677. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  678. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  679. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  680. };
  681. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  682. var squared = amount * amount;
  683. var cubed = amount * squared;
  684. 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));
  685. 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));
  686. 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));
  687. return new Vector3(x, y, z);
  688. };
  689. Vector3.Clamp = function (value, min, max) {
  690. var x = value.x;
  691. x = (x > max.x) ? max.x : x;
  692. x = (x < min.x) ? min.x : x;
  693. var y = value.y;
  694. y = (y > max.y) ? max.y : y;
  695. y = (y < min.y) ? min.y : y;
  696. var z = value.z;
  697. z = (z > max.z) ? max.z : z;
  698. z = (z < min.z) ? min.z : z;
  699. return new Vector3(x, y, z);
  700. };
  701. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  702. var squared = amount * amount;
  703. var cubed = amount * squared;
  704. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  705. var part2 = (-2.0 * cubed) + (3.0 * squared);
  706. var part3 = (cubed - (2.0 * squared)) + amount;
  707. var part4 = cubed - squared;
  708. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  709. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  710. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  711. return new Vector3(x, y, z);
  712. };
  713. Vector3.Lerp = function (start, end, amount) {
  714. var x = start.x + ((end.x - start.x) * amount);
  715. var y = start.y + ((end.y - start.y) * amount);
  716. var z = start.z + ((end.z - start.z) * amount);
  717. return new Vector3(x, y, z);
  718. };
  719. Vector3.Dot = function (left, right) {
  720. return (left.x * right.x + left.y * right.y + left.z * right.z);
  721. };
  722. Vector3.Cross = function (left, right) {
  723. var result = Vector3.Zero();
  724. Vector3.CrossToRef(left, right, result);
  725. return result;
  726. };
  727. Vector3.CrossToRef = function (left, right, result) {
  728. result.x = left.y * right.z - left.z * right.y;
  729. result.y = left.z * right.x - left.x * right.z;
  730. result.z = left.x * right.y - left.y * right.x;
  731. };
  732. Vector3.Normalize = function (vector) {
  733. var result = Vector3.Zero();
  734. Vector3.NormalizeToRef(vector, result);
  735. return result;
  736. };
  737. Vector3.NormalizeToRef = function (vector, result) {
  738. result.copyFrom(vector);
  739. result.normalize();
  740. };
  741. Vector3.Project = function (vector, world, transform, viewport) {
  742. var cw = viewport.width;
  743. var ch = viewport.height;
  744. var cx = viewport.x;
  745. var cy = viewport.y;
  746. 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);
  747. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  748. return Vector3.TransformCoordinates(vector, finalMatrix);
  749. };
  750. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  751. var matrix = world.multiply(transform);
  752. matrix.invert();
  753. source.x = source.x / viewportWidth * 2 - 1;
  754. source.y = -(source.y / viewportHeight * 2 - 1);
  755. var vector = Vector3.TransformCoordinates(source, matrix);
  756. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  757. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  758. vector = vector.scale(1.0 / num);
  759. }
  760. return vector;
  761. };
  762. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  763. var matrix = world.multiply(view).multiply(projection);
  764. matrix.invert();
  765. source.x = source.x / viewportWidth * 2 - 1;
  766. source.y = -(source.y / viewportHeight * 2 - 1);
  767. var vector = Vector3.TransformCoordinates(source, matrix);
  768. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  769. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  770. vector = vector.scale(1.0 / num);
  771. }
  772. return vector;
  773. };
  774. Vector3.Minimize = function (left, right) {
  775. var min = left.clone();
  776. min.MinimizeInPlace(right);
  777. return min;
  778. };
  779. Vector3.Maximize = function (left, right) {
  780. var max = left.clone();
  781. max.MaximizeInPlace(right);
  782. return max;
  783. };
  784. Vector3.Distance = function (value1, value2) {
  785. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  786. };
  787. Vector3.DistanceSquared = function (value1, value2) {
  788. var x = value1.x - value2.x;
  789. var y = value1.y - value2.y;
  790. var z = value1.z - value2.z;
  791. return (x * x) + (y * y) + (z * z);
  792. };
  793. Vector3.Center = function (value1, value2) {
  794. var center = value1.add(value2);
  795. center.scaleInPlace(0.5);
  796. return center;
  797. };
  798. return Vector3;
  799. })();
  800. BABYLON.Vector3 = Vector3;
  801. //Vector4 class created for EulerAngle class conversion to Quaternion
  802. var Vector4 = (function () {
  803. function Vector4(x, y, z, w) {
  804. this.x = x;
  805. this.y = y;
  806. this.z = z;
  807. this.w = w;
  808. }
  809. Vector4.prototype.toString = function () {
  810. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  811. };
  812. // Operators
  813. Vector4.prototype.asArray = function () {
  814. var result = [];
  815. this.toArray(result, 0);
  816. return result;
  817. };
  818. Vector4.prototype.toArray = function (array, index) {
  819. if (index === undefined) {
  820. index = 0;
  821. }
  822. array[index] = this.x;
  823. array[index + 1] = this.y;
  824. array[index + 2] = this.z;
  825. array[index + 3] = this.w;
  826. return this;
  827. };
  828. Vector4.prototype.addInPlace = function (otherVector) {
  829. this.x += otherVector.x;
  830. this.y += otherVector.y;
  831. this.z += otherVector.z;
  832. this.w += otherVector.w;
  833. return this;
  834. };
  835. Vector4.prototype.add = function (otherVector) {
  836. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  837. };
  838. Vector4.prototype.addToRef = function (otherVector, result) {
  839. result.x = this.x + otherVector.x;
  840. result.y = this.y + otherVector.y;
  841. result.z = this.z + otherVector.z;
  842. result.w = this.w + otherVector.w;
  843. return this;
  844. };
  845. Vector4.prototype.subtractInPlace = function (otherVector) {
  846. this.x -= otherVector.x;
  847. this.y -= otherVector.y;
  848. this.z -= otherVector.z;
  849. this.w -= otherVector.w;
  850. return this;
  851. };
  852. Vector4.prototype.subtract = function (otherVector) {
  853. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  854. };
  855. Vector4.prototype.subtractToRef = function (otherVector, result) {
  856. result.x = this.x - otherVector.x;
  857. result.y = this.y - otherVector.y;
  858. result.z = this.z - otherVector.z;
  859. result.w = this.w - otherVector.w;
  860. return this;
  861. };
  862. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  863. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  864. };
  865. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  866. result.x = this.x - x;
  867. result.y = this.y - y;
  868. result.z = this.z - z;
  869. result.w = this.w - w;
  870. return this;
  871. };
  872. Vector4.prototype.negate = function () {
  873. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  874. };
  875. Vector4.prototype.scaleInPlace = function (scale) {
  876. this.x *= scale;
  877. this.y *= scale;
  878. this.z *= scale;
  879. this.w *= scale;
  880. return this;
  881. };
  882. Vector4.prototype.scale = function (scale) {
  883. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  884. };
  885. Vector4.prototype.scaleToRef = function (scale, result) {
  886. result.x = this.x * scale;
  887. result.y = this.y * scale;
  888. result.z = this.z * scale;
  889. result.w = this.w * scale;
  890. };
  891. Vector4.prototype.equals = function (otherVector) {
  892. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  893. };
  894. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  895. 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;
  896. };
  897. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  898. return this.x === x && this.y === y && this.z === z && this.w === w;
  899. };
  900. Vector4.prototype.multiplyInPlace = function (otherVector) {
  901. this.x *= otherVector.x;
  902. this.y *= otherVector.y;
  903. this.z *= otherVector.z;
  904. this.w *= otherVector.w;
  905. return this;
  906. };
  907. Vector4.prototype.multiply = function (otherVector) {
  908. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  909. };
  910. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  911. result.x = this.x * otherVector.x;
  912. result.y = this.y * otherVector.y;
  913. result.z = this.z * otherVector.z;
  914. result.w = this.w * otherVector.w;
  915. return this;
  916. };
  917. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  918. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  919. };
  920. Vector4.prototype.divide = function (otherVector) {
  921. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  922. };
  923. Vector4.prototype.divideToRef = function (otherVector, result) {
  924. result.x = this.x / otherVector.x;
  925. result.y = this.y / otherVector.y;
  926. result.z = this.z / otherVector.z;
  927. result.w = this.w / otherVector.w;
  928. return this;
  929. };
  930. Vector4.prototype.MinimizeInPlace = function (other) {
  931. if (other.x < this.x)
  932. this.x = other.x;
  933. if (other.y < this.y)
  934. this.y = other.y;
  935. if (other.z < this.z)
  936. this.z = other.z;
  937. if (other.w < this.w)
  938. this.w = other.w;
  939. return this;
  940. };
  941. Vector4.prototype.MaximizeInPlace = function (other) {
  942. if (other.x > this.x)
  943. this.x = other.x;
  944. if (other.y > this.y)
  945. this.y = other.y;
  946. if (other.z > this.z)
  947. this.z = other.z;
  948. if (other.w > this.w)
  949. this.w = other.w;
  950. return this;
  951. };
  952. // Properties
  953. Vector4.prototype.length = function () {
  954. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  955. };
  956. Vector4.prototype.lengthSquared = function () {
  957. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  958. };
  959. // Methods
  960. Vector4.prototype.normalize = function () {
  961. var len = this.length();
  962. if (len === 0)
  963. return this;
  964. var num = 1.0 / len;
  965. this.x *= num;
  966. this.y *= num;
  967. this.z *= num;
  968. this.w *= num;
  969. return this;
  970. };
  971. Vector4.prototype.clone = function () {
  972. return new Vector4(this.x, this.y, this.z, this.w);
  973. };
  974. Vector4.prototype.copyFrom = function (source) {
  975. this.x = source.x;
  976. this.y = source.y;
  977. this.z = source.z;
  978. this.w = source.w;
  979. return this;
  980. };
  981. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  982. this.x = x;
  983. this.y = y;
  984. this.z = z;
  985. this.w = w;
  986. return this;
  987. };
  988. // Statics
  989. Vector4.FromArray = function (array, offset) {
  990. if (!offset) {
  991. offset = 0;
  992. }
  993. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  994. };
  995. Vector4.FromArrayToRef = function (array, offset, result) {
  996. result.x = array[offset];
  997. result.y = array[offset + 1];
  998. result.z = array[offset + 2];
  999. result.w = array[offset + 3];
  1000. };
  1001. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1002. result.x = array[offset];
  1003. result.y = array[offset + 1];
  1004. result.z = array[offset + 2];
  1005. result.w = array[offset + 3];
  1006. };
  1007. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1008. result.x = x;
  1009. result.y = y;
  1010. result.z = z;
  1011. result.w = w;
  1012. };
  1013. Vector4.Zero = function () {
  1014. return new Vector4(0, 0, 0, 0);
  1015. };
  1016. Vector4.Normalize = function (vector) {
  1017. var result = Vector4.Zero();
  1018. Vector4.NormalizeToRef(vector, result);
  1019. return result;
  1020. };
  1021. Vector4.NormalizeToRef = function (vector, result) {
  1022. result.copyFrom(vector);
  1023. result.normalize();
  1024. };
  1025. Vector4.Minimize = function (left, right) {
  1026. var min = left.clone();
  1027. min.MinimizeInPlace(right);
  1028. return min;
  1029. };
  1030. Vector4.Maximize = function (left, right) {
  1031. var max = left.clone();
  1032. max.MaximizeInPlace(right);
  1033. return max;
  1034. };
  1035. Vector4.Distance = function (value1, value2) {
  1036. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1037. };
  1038. Vector4.DistanceSquared = function (value1, value2) {
  1039. var x = value1.x - value2.x;
  1040. var y = value1.y - value2.y;
  1041. var z = value1.z - value2.z;
  1042. var w = value1.w - value2.w;
  1043. return (x * x) + (y * y) + (z * z) + (w * w);
  1044. };
  1045. Vector4.Center = function (value1, value2) {
  1046. var center = value1.add(value2);
  1047. center.scaleInPlace(0.5);
  1048. return center;
  1049. };
  1050. return Vector4;
  1051. })();
  1052. BABYLON.Vector4 = Vector4;
  1053. var Quaternion = (function () {
  1054. function Quaternion(x, y, z, w) {
  1055. if (x === void 0) { x = 0; }
  1056. if (y === void 0) { y = 0; }
  1057. if (z === void 0) { z = 0; }
  1058. if (w === void 0) { w = 1; }
  1059. this.x = x;
  1060. this.y = y;
  1061. this.z = z;
  1062. this.w = w;
  1063. }
  1064. Quaternion.prototype.toString = function () {
  1065. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1066. };
  1067. Quaternion.prototype.asArray = function () {
  1068. return [this.x, this.y, this.z, this.w];
  1069. };
  1070. Quaternion.prototype.equals = function (otherQuaternion) {
  1071. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1072. };
  1073. Quaternion.prototype.clone = function () {
  1074. return new Quaternion(this.x, this.y, this.z, this.w);
  1075. };
  1076. Quaternion.prototype.copyFrom = function (other) {
  1077. this.x = other.x;
  1078. this.y = other.y;
  1079. this.z = other.z;
  1080. this.w = other.w;
  1081. return this;
  1082. };
  1083. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1084. this.x = x;
  1085. this.y = y;
  1086. this.z = z;
  1087. this.w = w;
  1088. return this;
  1089. };
  1090. Quaternion.prototype.add = function (other) {
  1091. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1092. };
  1093. Quaternion.prototype.subtract = function (other) {
  1094. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1095. };
  1096. Quaternion.prototype.scale = function (value) {
  1097. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1098. };
  1099. Quaternion.prototype.multiply = function (q1) {
  1100. var result = new Quaternion(0, 0, 0, 1.0);
  1101. this.multiplyToRef(q1, result);
  1102. return result;
  1103. };
  1104. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1105. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1106. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1107. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1108. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1109. return this;
  1110. };
  1111. Quaternion.prototype.length = function () {
  1112. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1113. };
  1114. Quaternion.prototype.normalize = function () {
  1115. var length = 1.0 / this.length();
  1116. this.x *= length;
  1117. this.y *= length;
  1118. this.z *= length;
  1119. this.w *= length;
  1120. return this;
  1121. };
  1122. Quaternion.prototype.toEulerAngles = function () {
  1123. var result = Vector3.Zero();
  1124. this.toEulerAnglesToRef(result);
  1125. return result;
  1126. };
  1127. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1128. //result is an EulerAngles in the in the z-x-z convention
  1129. var qx = this.x;
  1130. var qy = this.y;
  1131. var qz = this.z;
  1132. var qw = this.w;
  1133. var qxy = qx * qy;
  1134. var qxz = qx * qz;
  1135. var qwy = qw * qy;
  1136. var qwz = qw * qz;
  1137. var qwx = qw * qx;
  1138. var qyz = qy * qz;
  1139. var sqx = qx * qx;
  1140. var sqy = qy * qy;
  1141. var determinant = sqx + sqy;
  1142. if (determinant !== 0.000 && determinant !== 1.000) {
  1143. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1144. result.y = Math.acos(1 - 2 * determinant);
  1145. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1146. }
  1147. else {
  1148. if (determinant === 0.0) {
  1149. result.x = 0.0;
  1150. result.y = 0.0;
  1151. 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)
  1152. }
  1153. else {
  1154. 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)
  1155. result.y = Math.PI;
  1156. result.z = 0.0;
  1157. }
  1158. }
  1159. return this;
  1160. };
  1161. Quaternion.prototype.toRotationMatrix = function (result) {
  1162. var xx = this.x * this.x;
  1163. var yy = this.y * this.y;
  1164. var zz = this.z * this.z;
  1165. var xy = this.x * this.y;
  1166. var zw = this.z * this.w;
  1167. var zx = this.z * this.x;
  1168. var yw = this.y * this.w;
  1169. var yz = this.y * this.z;
  1170. var xw = this.x * this.w;
  1171. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1172. result.m[1] = 2.0 * (xy + zw);
  1173. result.m[2] = 2.0 * (zx - yw);
  1174. result.m[3] = 0;
  1175. result.m[4] = 2.0 * (xy - zw);
  1176. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1177. result.m[6] = 2.0 * (yz + xw);
  1178. result.m[7] = 0;
  1179. result.m[8] = 2.0 * (zx + yw);
  1180. result.m[9] = 2.0 * (yz - xw);
  1181. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1182. result.m[11] = 0;
  1183. result.m[12] = 0;
  1184. result.m[13] = 0;
  1185. result.m[14] = 0;
  1186. result.m[15] = 1.0;
  1187. return this;
  1188. };
  1189. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1190. Quaternion.FromRotationMatrixToRef(matrix, this);
  1191. return this;
  1192. };
  1193. // Statics
  1194. Quaternion.FromRotationMatrix = function (matrix) {
  1195. var result = new Quaternion();
  1196. Quaternion.FromRotationMatrixToRef(matrix, result);
  1197. return result;
  1198. };
  1199. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1200. var data = matrix.m;
  1201. var m11 = data[0], m12 = data[4], m13 = data[8];
  1202. var m21 = data[1], m22 = data[5], m23 = data[9];
  1203. var m31 = data[2], m32 = data[6], m33 = data[10];
  1204. var trace = m11 + m22 + m33;
  1205. var s;
  1206. if (trace > 0) {
  1207. s = 0.5 / Math.sqrt(trace + 1.0);
  1208. result.w = 0.25 / s;
  1209. result.x = (m32 - m23) * s;
  1210. result.y = (m13 - m31) * s;
  1211. result.z = (m21 - m12) * s;
  1212. }
  1213. else if (m11 > m22 && m11 > m33) {
  1214. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1215. result.w = (m32 - m23) / s;
  1216. result.x = 0.25 * s;
  1217. result.y = (m12 + m21) / s;
  1218. result.z = (m13 + m31) / s;
  1219. }
  1220. else if (m22 > m33) {
  1221. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1222. result.w = (m13 - m31) / s;
  1223. result.x = (m12 + m21) / s;
  1224. result.y = 0.25 * s;
  1225. result.z = (m23 + m32) / s;
  1226. }
  1227. else {
  1228. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1229. result.w = (m21 - m12) / s;
  1230. result.x = (m13 + m31) / s;
  1231. result.y = (m23 + m32) / s;
  1232. result.z = 0.25 * s;
  1233. }
  1234. };
  1235. Quaternion.Inverse = function (q) {
  1236. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1237. };
  1238. Quaternion.Identity = function () {
  1239. return new Quaternion(0, 0, 0, 1);
  1240. };
  1241. Quaternion.RotationAxis = function (axis, angle) {
  1242. var result = new Quaternion();
  1243. var sin = Math.sin(angle / 2);
  1244. result.w = Math.cos(angle / 2);
  1245. result.x = axis.x * sin;
  1246. result.y = axis.y * sin;
  1247. result.z = axis.z * sin;
  1248. return result;
  1249. };
  1250. Quaternion.FromArray = function (array, offset) {
  1251. if (!offset) {
  1252. offset = 0;
  1253. }
  1254. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1255. };
  1256. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1257. var result = new Quaternion();
  1258. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1259. return result;
  1260. };
  1261. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1262. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1263. var halfRoll = roll * 0.5;
  1264. var halfPitch = pitch * 0.5;
  1265. var halfYaw = yaw * 0.5;
  1266. var sinRoll = Math.sin(halfRoll);
  1267. var cosRoll = Math.cos(halfRoll);
  1268. var sinPitch = Math.sin(halfPitch);
  1269. var cosPitch = Math.cos(halfPitch);
  1270. var sinYaw = Math.sin(halfYaw);
  1271. var cosYaw = Math.cos(halfYaw);
  1272. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1273. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1274. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1275. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1276. };
  1277. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1278. var result = new Quaternion();
  1279. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1280. return result;
  1281. };
  1282. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1283. // Produces a quaternion from Euler angles in the z-x-z orientation
  1284. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1285. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1286. var halfBeta = beta * 0.5;
  1287. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1288. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1289. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1290. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1291. };
  1292. Quaternion.Slerp = function (left, right, amount) {
  1293. var num2;
  1294. var num3;
  1295. var num = amount;
  1296. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1297. var flag = false;
  1298. if (num4 < 0) {
  1299. flag = true;
  1300. num4 = -num4;
  1301. }
  1302. if (num4 > 0.999999) {
  1303. num3 = 1 - num;
  1304. num2 = flag ? -num : num;
  1305. }
  1306. else {
  1307. var num5 = Math.acos(num4);
  1308. var num6 = (1.0 / Math.sin(num5));
  1309. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1310. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1311. }
  1312. 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));
  1313. };
  1314. return Quaternion;
  1315. })();
  1316. BABYLON.Quaternion = Quaternion;
  1317. var Matrix = (function () {
  1318. function Matrix() {
  1319. this.m = new Float32Array(16);
  1320. }
  1321. // Properties
  1322. Matrix.prototype.isIdentity = function () {
  1323. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1324. return false;
  1325. 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)
  1326. return false;
  1327. return true;
  1328. };
  1329. Matrix.prototype.determinant = function () {
  1330. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1331. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1332. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1333. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1334. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1335. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1336. 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))));
  1337. };
  1338. // Methods
  1339. Matrix.prototype.toArray = function () {
  1340. return this.m;
  1341. };
  1342. Matrix.prototype.asArray = function () {
  1343. return this.toArray();
  1344. };
  1345. Matrix.prototype.invert = function () {
  1346. this.invertToRef(this);
  1347. return this;
  1348. };
  1349. Matrix.prototype.invertToRef = function (other) {
  1350. var l1 = this.m[0];
  1351. var l2 = this.m[1];
  1352. var l3 = this.m[2];
  1353. var l4 = this.m[3];
  1354. var l5 = this.m[4];
  1355. var l6 = this.m[5];
  1356. var l7 = this.m[6];
  1357. var l8 = this.m[7];
  1358. var l9 = this.m[8];
  1359. var l10 = this.m[9];
  1360. var l11 = this.m[10];
  1361. var l12 = this.m[11];
  1362. var l13 = this.m[12];
  1363. var l14 = this.m[13];
  1364. var l15 = this.m[14];
  1365. var l16 = this.m[15];
  1366. var l17 = (l11 * l16) - (l12 * l15);
  1367. var l18 = (l10 * l16) - (l12 * l14);
  1368. var l19 = (l10 * l15) - (l11 * l14);
  1369. var l20 = (l9 * l16) - (l12 * l13);
  1370. var l21 = (l9 * l15) - (l11 * l13);
  1371. var l22 = (l9 * l14) - (l10 * l13);
  1372. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1373. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1374. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1375. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1376. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1377. var l28 = (l7 * l16) - (l8 * l15);
  1378. var l29 = (l6 * l16) - (l8 * l14);
  1379. var l30 = (l6 * l15) - (l7 * l14);
  1380. var l31 = (l5 * l16) - (l8 * l13);
  1381. var l32 = (l5 * l15) - (l7 * l13);
  1382. var l33 = (l5 * l14) - (l6 * l13);
  1383. var l34 = (l7 * l12) - (l8 * l11);
  1384. var l35 = (l6 * l12) - (l8 * l10);
  1385. var l36 = (l6 * l11) - (l7 * l10);
  1386. var l37 = (l5 * l12) - (l8 * l9);
  1387. var l38 = (l5 * l11) - (l7 * l9);
  1388. var l39 = (l5 * l10) - (l6 * l9);
  1389. other.m[0] = l23 * l27;
  1390. other.m[4] = l24 * l27;
  1391. other.m[8] = l25 * l27;
  1392. other.m[12] = l26 * l27;
  1393. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1394. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1395. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1396. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1397. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1398. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1399. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1400. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1401. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1402. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1403. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1404. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1405. return this;
  1406. };
  1407. Matrix.prototype.invertToRefSIMD = function (other) {
  1408. var src = this.m;
  1409. var dest = other.m;
  1410. var row0, row1, row2, row3;
  1411. var tmp1;
  1412. var minor0, minor1, minor2, minor3;
  1413. var det;
  1414. // Load the 4 rows
  1415. var src0 = SIMD.float32x4.load(src, 0);
  1416. var src1 = SIMD.float32x4.load(src, 4);
  1417. var src2 = SIMD.float32x4.load(src, 8);
  1418. var src3 = SIMD.float32x4.load(src, 12);
  1419. // Transpose the source matrix. Sort of. Not a true transpose operation
  1420. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1421. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1422. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1423. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1424. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1425. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1426. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1427. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1428. // This is a true transposition, but it will lead to an incorrect result
  1429. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1430. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1431. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1432. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1433. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1434. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1435. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1436. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1437. // ----
  1438. tmp1 = SIMD.float32x4.mul(row2, row3);
  1439. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1440. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1441. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1442. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1443. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1444. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1445. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1446. // ----
  1447. tmp1 = SIMD.float32x4.mul(row1, row2);
  1448. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1449. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1450. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1451. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1452. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1453. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1454. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1455. // ----
  1456. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1457. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1458. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1459. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1460. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1461. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1462. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1463. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1464. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1465. // ----
  1466. tmp1 = SIMD.float32x4.mul(row0, row1);
  1467. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1468. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1469. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1470. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1471. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1472. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1473. // ----
  1474. tmp1 = SIMD.float32x4.mul(row0, row3);
  1475. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1476. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1477. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1478. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1479. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1480. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1481. // ----
  1482. tmp1 = SIMD.float32x4.mul(row0, row2);
  1483. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1484. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1485. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1486. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1487. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1488. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1489. // Compute determinant
  1490. det = SIMD.float32x4.mul(row0, minor0);
  1491. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1492. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1493. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1494. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1495. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1496. // These shuffles aren't necessary if the faulty transposition is done
  1497. // up at the top of this function.
  1498. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1499. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1500. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1501. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1502. // Compute final values by multiplying with 1/det
  1503. minor0 = SIMD.float32x4.mul(det, minor0);
  1504. minor1 = SIMD.float32x4.mul(det, minor1);
  1505. minor2 = SIMD.float32x4.mul(det, minor2);
  1506. minor3 = SIMD.float32x4.mul(det, minor3);
  1507. SIMD.float32x4.store(dest, 0, minor0);
  1508. SIMD.float32x4.store(dest, 4, minor1);
  1509. SIMD.float32x4.store(dest, 8, minor2);
  1510. SIMD.float32x4.store(dest, 12, minor3);
  1511. return this;
  1512. };
  1513. Matrix.prototype.setTranslation = function (vector3) {
  1514. this.m[12] = vector3.x;
  1515. this.m[13] = vector3.y;
  1516. this.m[14] = vector3.z;
  1517. return this;
  1518. };
  1519. Matrix.prototype.multiply = function (other) {
  1520. var result = new Matrix();
  1521. this.multiplyToRef(other, result);
  1522. return result;
  1523. };
  1524. Matrix.prototype.copyFrom = function (other) {
  1525. for (var index = 0; index < 16; index++) {
  1526. this.m[index] = other.m[index];
  1527. }
  1528. return this;
  1529. };
  1530. Matrix.prototype.copyToArray = function (array, offset) {
  1531. if (offset === void 0) { offset = 0; }
  1532. for (var index = 0; index < 16; index++) {
  1533. array[offset + index] = this.m[index];
  1534. }
  1535. return this;
  1536. };
  1537. Matrix.prototype.multiplyToRef = function (other, result) {
  1538. this.multiplyToArray(other, result.m, 0);
  1539. return this;
  1540. };
  1541. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1542. var tm0 = this.m[0];
  1543. var tm1 = this.m[1];
  1544. var tm2 = this.m[2];
  1545. var tm3 = this.m[3];
  1546. var tm4 = this.m[4];
  1547. var tm5 = this.m[5];
  1548. var tm6 = this.m[6];
  1549. var tm7 = this.m[7];
  1550. var tm8 = this.m[8];
  1551. var tm9 = this.m[9];
  1552. var tm10 = this.m[10];
  1553. var tm11 = this.m[11];
  1554. var tm12 = this.m[12];
  1555. var tm13 = this.m[13];
  1556. var tm14 = this.m[14];
  1557. var tm15 = this.m[15];
  1558. var om0 = other.m[0];
  1559. var om1 = other.m[1];
  1560. var om2 = other.m[2];
  1561. var om3 = other.m[3];
  1562. var om4 = other.m[4];
  1563. var om5 = other.m[5];
  1564. var om6 = other.m[6];
  1565. var om7 = other.m[7];
  1566. var om8 = other.m[8];
  1567. var om9 = other.m[9];
  1568. var om10 = other.m[10];
  1569. var om11 = other.m[11];
  1570. var om12 = other.m[12];
  1571. var om13 = other.m[13];
  1572. var om14 = other.m[14];
  1573. var om15 = other.m[15];
  1574. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1575. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1576. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1577. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1578. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1579. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1580. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1581. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1582. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1583. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1584. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1585. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1586. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1587. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1588. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1589. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1590. return this;
  1591. };
  1592. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1593. if (offset === void 0) { offset = 0; }
  1594. var tm = this.m;
  1595. var om = other.m;
  1596. var om0 = SIMD.float32x4.load(om, 0);
  1597. var om1 = SIMD.float32x4.load(om, 4);
  1598. var om2 = SIMD.float32x4.load(om, 8);
  1599. var om3 = SIMD.float32x4.load(om, 12);
  1600. var tm0 = SIMD.float32x4.load(tm, 0);
  1601. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1602. var tm1 = SIMD.float32x4.load(tm, 4);
  1603. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1604. var tm2 = SIMD.float32x4.load(tm, 8);
  1605. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1606. var tm3 = SIMD.float32x4.load(tm, 12);
  1607. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1608. };
  1609. Matrix.prototype.equals = function (value) {
  1610. 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]);
  1611. };
  1612. Matrix.prototype.clone = function () {
  1613. 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]);
  1614. };
  1615. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1616. translation.x = this.m[12];
  1617. translation.y = this.m[13];
  1618. translation.z = this.m[14];
  1619. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1620. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1621. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1622. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1623. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1624. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1625. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1626. rotation.x = 0;
  1627. rotation.y = 0;
  1628. rotation.z = 0;
  1629. rotation.w = 1;
  1630. return false;
  1631. }
  1632. var rotationMatrix = 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);
  1633. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1634. return true;
  1635. };
  1636. // Statics
  1637. Matrix.FromArray = function (array, offset) {
  1638. var result = new Matrix();
  1639. if (!offset) {
  1640. offset = 0;
  1641. }
  1642. Matrix.FromArrayToRef(array, offset, result);
  1643. return result;
  1644. };
  1645. Matrix.FromArrayToRef = function (array, offset, result) {
  1646. for (var index = 0; index < 16; index++) {
  1647. result.m[index] = array[index + offset];
  1648. }
  1649. };
  1650. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1651. result.m[0] = initialM11;
  1652. result.m[1] = initialM12;
  1653. result.m[2] = initialM13;
  1654. result.m[3] = initialM14;
  1655. result.m[4] = initialM21;
  1656. result.m[5] = initialM22;
  1657. result.m[6] = initialM23;
  1658. result.m[7] = initialM24;
  1659. result.m[8] = initialM31;
  1660. result.m[9] = initialM32;
  1661. result.m[10] = initialM33;
  1662. result.m[11] = initialM34;
  1663. result.m[12] = initialM41;
  1664. result.m[13] = initialM42;
  1665. result.m[14] = initialM43;
  1666. result.m[15] = initialM44;
  1667. };
  1668. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1669. var result = new Matrix();
  1670. result.m[0] = initialM11;
  1671. result.m[1] = initialM12;
  1672. result.m[2] = initialM13;
  1673. result.m[3] = initialM14;
  1674. result.m[4] = initialM21;
  1675. result.m[5] = initialM22;
  1676. result.m[6] = initialM23;
  1677. result.m[7] = initialM24;
  1678. result.m[8] = initialM31;
  1679. result.m[9] = initialM32;
  1680. result.m[10] = initialM33;
  1681. result.m[11] = initialM34;
  1682. result.m[12] = initialM41;
  1683. result.m[13] = initialM42;
  1684. result.m[14] = initialM43;
  1685. result.m[15] = initialM44;
  1686. return result;
  1687. };
  1688. Matrix.Compose = function (scale, rotation, translation) {
  1689. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1690. var rotationMatrix = Matrix.Identity();
  1691. rotation.toRotationMatrix(rotationMatrix);
  1692. result = result.multiply(rotationMatrix);
  1693. result.setTranslation(translation);
  1694. return result;
  1695. };
  1696. Matrix.Identity = function () {
  1697. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1698. };
  1699. Matrix.IdentityToRef = function (result) {
  1700. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1701. };
  1702. Matrix.Zero = function () {
  1703. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1704. };
  1705. Matrix.RotationX = function (angle) {
  1706. var result = new Matrix();
  1707. Matrix.RotationXToRef(angle, result);
  1708. return result;
  1709. };
  1710. Matrix.Invert = function (source) {
  1711. var result = new Matrix();
  1712. source.invertToRef(result);
  1713. return result;
  1714. };
  1715. Matrix.RotationXToRef = function (angle, result) {
  1716. var s = Math.sin(angle);
  1717. var c = Math.cos(angle);
  1718. result.m[0] = 1.0;
  1719. result.m[15] = 1.0;
  1720. result.m[5] = c;
  1721. result.m[10] = c;
  1722. result.m[9] = -s;
  1723. result.m[6] = s;
  1724. result.m[1] = 0;
  1725. result.m[2] = 0;
  1726. result.m[3] = 0;
  1727. result.m[4] = 0;
  1728. result.m[7] = 0;
  1729. result.m[8] = 0;
  1730. result.m[11] = 0;
  1731. result.m[12] = 0;
  1732. result.m[13] = 0;
  1733. result.m[14] = 0;
  1734. };
  1735. Matrix.RotationY = function (angle) {
  1736. var result = new Matrix();
  1737. Matrix.RotationYToRef(angle, result);
  1738. return result;
  1739. };
  1740. Matrix.RotationYToRef = function (angle, result) {
  1741. var s = Math.sin(angle);
  1742. var c = Math.cos(angle);
  1743. result.m[5] = 1.0;
  1744. result.m[15] = 1.0;
  1745. result.m[0] = c;
  1746. result.m[2] = -s;
  1747. result.m[8] = s;
  1748. result.m[10] = c;
  1749. result.m[1] = 0;
  1750. result.m[3] = 0;
  1751. result.m[4] = 0;
  1752. result.m[6] = 0;
  1753. result.m[7] = 0;
  1754. result.m[9] = 0;
  1755. result.m[11] = 0;
  1756. result.m[12] = 0;
  1757. result.m[13] = 0;
  1758. result.m[14] = 0;
  1759. };
  1760. Matrix.RotationZ = function (angle) {
  1761. var result = new Matrix();
  1762. Matrix.RotationZToRef(angle, result);
  1763. return result;
  1764. };
  1765. Matrix.RotationZToRef = function (angle, result) {
  1766. var s = Math.sin(angle);
  1767. var c = Math.cos(angle);
  1768. result.m[10] = 1.0;
  1769. result.m[15] = 1.0;
  1770. result.m[0] = c;
  1771. result.m[1] = s;
  1772. result.m[4] = -s;
  1773. result.m[5] = c;
  1774. result.m[2] = 0;
  1775. result.m[3] = 0;
  1776. result.m[6] = 0;
  1777. result.m[7] = 0;
  1778. result.m[8] = 0;
  1779. result.m[9] = 0;
  1780. result.m[11] = 0;
  1781. result.m[12] = 0;
  1782. result.m[13] = 0;
  1783. result.m[14] = 0;
  1784. };
  1785. Matrix.RotationAxis = function (axis, angle) {
  1786. var s = Math.sin(-angle);
  1787. var c = Math.cos(-angle);
  1788. var c1 = 1 - c;
  1789. axis.normalize();
  1790. var result = Matrix.Zero();
  1791. result.m[0] = (axis.x * axis.x) * c1 + c;
  1792. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1793. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1794. result.m[3] = 0.0;
  1795. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1796. result.m[5] = (axis.y * axis.y) * c1 + c;
  1797. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1798. result.m[7] = 0.0;
  1799. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1800. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1801. result.m[10] = (axis.z * axis.z) * c1 + c;
  1802. result.m[11] = 0.0;
  1803. result.m[15] = 1.0;
  1804. return result;
  1805. };
  1806. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1807. var result = new Matrix();
  1808. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1809. return result;
  1810. };
  1811. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1812. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1813. this._tempQuaternion.toRotationMatrix(result);
  1814. };
  1815. Matrix.Scaling = function (x, y, z) {
  1816. var result = Matrix.Zero();
  1817. Matrix.ScalingToRef(x, y, z, result);
  1818. return result;
  1819. };
  1820. Matrix.ScalingToRef = function (x, y, z, result) {
  1821. result.m[0] = x;
  1822. result.m[1] = 0;
  1823. result.m[2] = 0;
  1824. result.m[3] = 0;
  1825. result.m[4] = 0;
  1826. result.m[5] = y;
  1827. result.m[6] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[9] = 0;
  1831. result.m[10] = z;
  1832. result.m[11] = 0;
  1833. result.m[12] = 0;
  1834. result.m[13] = 0;
  1835. result.m[14] = 0;
  1836. result.m[15] = 1.0;
  1837. };
  1838. Matrix.Translation = function (x, y, z) {
  1839. var result = Matrix.Identity();
  1840. Matrix.TranslationToRef(x, y, z, result);
  1841. return result;
  1842. };
  1843. Matrix.TranslationToRef = function (x, y, z, result) {
  1844. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1845. };
  1846. Matrix.LookAtLH = function (eye, target, up) {
  1847. var result = Matrix.Zero();
  1848. Matrix.LookAtLHToRef(eye, target, up, result);
  1849. return result;
  1850. };
  1851. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1852. // Z axis
  1853. target.subtractToRef(eye, this._zAxis);
  1854. this._zAxis.normalize();
  1855. // X axis
  1856. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1857. this._xAxis.normalize();
  1858. // Y axis
  1859. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1860. this._yAxis.normalize();
  1861. // Eye angles
  1862. var ex = -Vector3.Dot(this._xAxis, eye);
  1863. var ey = -Vector3.Dot(this._yAxis, eye);
  1864. var ez = -Vector3.Dot(this._zAxis, eye);
  1865. 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);
  1866. };
  1867. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1868. var out = result.m;
  1869. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1870. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1871. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1872. // cc.kmVec3Subtract(f, pCenter, pEye);
  1873. var f = SIMD.float32x4.sub(center, eye);
  1874. // cc.kmVec3Normalize(f, f);
  1875. var tmp = SIMD.float32x4.mul(f, f);
  1876. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1877. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1878. // cc.kmVec3Assign(up, pUp);
  1879. // cc.kmVec3Normalize(up, up);
  1880. tmp = SIMD.float32x4.mul(up, up);
  1881. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1882. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1883. // cc.kmVec3Cross(s, f, up);
  1884. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  1885. // cc.kmVec3Normalize(s, s);
  1886. tmp = SIMD.float32x4.mul(s, s);
  1887. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1888. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1889. // cc.kmVec3Cross(u, s, f);
  1890. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  1891. // cc.kmVec3Normalize(s, s);
  1892. tmp = SIMD.float32x4.mul(s, s);
  1893. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1894. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1895. var zero = SIMD.float32x4.splat(0.0);
  1896. s = SIMD.float32x4.neg(s);
  1897. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1898. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1899. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1900. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  1901. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  1902. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  1903. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1904. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  1905. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  1906. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  1907. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  1908. var b3 = SIMD.float32x4.neg(eye);
  1909. b3 = SIMD.float32x4.withW(b3, 1.0);
  1910. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  1911. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  1912. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  1913. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  1914. };
  1915. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1916. var matrix = Matrix.Zero();
  1917. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1918. return matrix;
  1919. };
  1920. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1921. var hw = 2.0 / width;
  1922. var hh = 2.0 / height;
  1923. var id = 1.0 / (zfar - znear);
  1924. var nid = znear / (znear - zfar);
  1925. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1926. };
  1927. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1928. var matrix = Matrix.Zero();
  1929. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1930. return matrix;
  1931. };
  1932. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1933. result.m[0] = 2.0 / (right - left);
  1934. result.m[1] = result.m[2] = result.m[3] = 0;
  1935. result.m[5] = 2.0 / (top - bottom);
  1936. result.m[4] = result.m[6] = result.m[7] = 0;
  1937. result.m[10] = -1.0 / (znear - zfar);
  1938. result.m[8] = result.m[9] = result.m[11] = 0;
  1939. result.m[12] = (left + right) / (left - right);
  1940. result.m[13] = (top + bottom) / (bottom - top);
  1941. result.m[14] = znear / (znear - zfar);
  1942. result.m[15] = 1.0;
  1943. };
  1944. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1945. var matrix = Matrix.Zero();
  1946. matrix.m[0] = (2.0 * znear) / width;
  1947. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1948. matrix.m[5] = (2.0 * znear) / height;
  1949. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1950. matrix.m[10] = -zfar / (znear - zfar);
  1951. matrix.m[8] = matrix.m[9] = 0.0;
  1952. matrix.m[11] = 1.0;
  1953. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1954. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1955. return matrix;
  1956. };
  1957. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1958. var matrix = Matrix.Zero();
  1959. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1960. return matrix;
  1961. };
  1962. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1963. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1964. var tan = 1.0 / (Math.tan(fov * 0.5));
  1965. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1966. if (v_fixed) {
  1967. result.m[0] = tan / aspect;
  1968. }
  1969. else {
  1970. result.m[0] = tan;
  1971. }
  1972. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1973. if (v_fixed) {
  1974. result.m[5] = tan;
  1975. }
  1976. else {
  1977. result.m[5] = tan * aspect;
  1978. }
  1979. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1980. result.m[8] = result.m[9] = 0.0;
  1981. result.m[10] = -zfar / (znear - zfar);
  1982. result.m[11] = 1.0;
  1983. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1984. result.m[14] = (znear * zfar) / (znear - zfar);
  1985. };
  1986. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1987. var cw = viewport.width;
  1988. var ch = viewport.height;
  1989. var cx = viewport.x;
  1990. var cy = viewport.y;
  1991. 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);
  1992. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1993. };
  1994. Matrix.Transpose = function (matrix) {
  1995. var result = new Matrix();
  1996. result.m[0] = matrix.m[0];
  1997. result.m[1] = matrix.m[4];
  1998. result.m[2] = matrix.m[8];
  1999. result.m[3] = matrix.m[12];
  2000. result.m[4] = matrix.m[1];
  2001. result.m[5] = matrix.m[5];
  2002. result.m[6] = matrix.m[9];
  2003. result.m[7] = matrix.m[13];
  2004. result.m[8] = matrix.m[2];
  2005. result.m[9] = matrix.m[6];
  2006. result.m[10] = matrix.m[10];
  2007. result.m[11] = matrix.m[14];
  2008. result.m[12] = matrix.m[3];
  2009. result.m[13] = matrix.m[7];
  2010. result.m[14] = matrix.m[11];
  2011. result.m[15] = matrix.m[15];
  2012. return result;
  2013. };
  2014. Matrix.Reflection = function (plane) {
  2015. var matrix = new Matrix();
  2016. Matrix.ReflectionToRef(plane, matrix);
  2017. return matrix;
  2018. };
  2019. Matrix.ReflectionToRef = function (plane, result) {
  2020. plane.normalize();
  2021. var x = plane.normal.x;
  2022. var y = plane.normal.y;
  2023. var z = plane.normal.z;
  2024. var temp = -2 * x;
  2025. var temp2 = -2 * y;
  2026. var temp3 = -2 * z;
  2027. result.m[0] = (temp * x) + 1;
  2028. result.m[1] = temp2 * x;
  2029. result.m[2] = temp3 * x;
  2030. result.m[3] = 0.0;
  2031. result.m[4] = temp * y;
  2032. result.m[5] = (temp2 * y) + 1;
  2033. result.m[6] = temp3 * y;
  2034. result.m[7] = 0.0;
  2035. result.m[8] = temp * z;
  2036. result.m[9] = temp2 * z;
  2037. result.m[10] = (temp3 * z) + 1;
  2038. result.m[11] = 0.0;
  2039. result.m[12] = temp * plane.d;
  2040. result.m[13] = temp2 * plane.d;
  2041. result.m[14] = temp3 * plane.d;
  2042. result.m[15] = 1.0;
  2043. };
  2044. Matrix._tempQuaternion = new Quaternion();
  2045. Matrix._xAxis = Vector3.Zero();
  2046. Matrix._yAxis = Vector3.Zero();
  2047. Matrix._zAxis = Vector3.Zero();
  2048. return Matrix;
  2049. })();
  2050. BABYLON.Matrix = Matrix;
  2051. var Plane = (function () {
  2052. function Plane(a, b, c, d) {
  2053. this.normal = new Vector3(a, b, c);
  2054. this.d = d;
  2055. }
  2056. Plane.prototype.asArray = function () {
  2057. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2058. };
  2059. // Methods
  2060. Plane.prototype.clone = function () {
  2061. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2062. };
  2063. Plane.prototype.normalize = function () {
  2064. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2065. var magnitude = 0;
  2066. if (norm !== 0) {
  2067. magnitude = 1.0 / norm;
  2068. }
  2069. this.normal.x *= magnitude;
  2070. this.normal.y *= magnitude;
  2071. this.normal.z *= magnitude;
  2072. this.d *= magnitude;
  2073. return this;
  2074. };
  2075. Plane.prototype.transform = function (transformation) {
  2076. var transposedMatrix = Matrix.Transpose(transformation);
  2077. var x = this.normal.x;
  2078. var y = this.normal.y;
  2079. var z = this.normal.z;
  2080. var d = this.d;
  2081. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2082. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2083. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2084. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2085. return new Plane(normalX, normalY, normalZ, finalD);
  2086. };
  2087. Plane.prototype.dotCoordinate = function (point) {
  2088. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2089. };
  2090. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2091. var x1 = point2.x - point1.x;
  2092. var y1 = point2.y - point1.y;
  2093. var z1 = point2.z - point1.z;
  2094. var x2 = point3.x - point1.x;
  2095. var y2 = point3.y - point1.y;
  2096. var z2 = point3.z - point1.z;
  2097. var yz = (y1 * z2) - (z1 * y2);
  2098. var xz = (z1 * x2) - (x1 * z2);
  2099. var xy = (x1 * y2) - (y1 * x2);
  2100. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2101. var invPyth;
  2102. if (pyth !== 0) {
  2103. invPyth = 1.0 / pyth;
  2104. }
  2105. else {
  2106. invPyth = 0;
  2107. }
  2108. this.normal.x = yz * invPyth;
  2109. this.normal.y = xz * invPyth;
  2110. this.normal.z = xy * invPyth;
  2111. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2112. return this;
  2113. };
  2114. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2115. var dot = Vector3.Dot(this.normal, direction);
  2116. return (dot <= epsilon);
  2117. };
  2118. Plane.prototype.signedDistanceTo = function (point) {
  2119. return Vector3.Dot(point, this.normal) + this.d;
  2120. };
  2121. // Statics
  2122. Plane.FromArray = function (array) {
  2123. return new Plane(array[0], array[1], array[2], array[3]);
  2124. };
  2125. Plane.FromPoints = function (point1, point2, point3) {
  2126. var result = new Plane(0, 0, 0, 0);
  2127. result.copyFromPoints(point1, point2, point3);
  2128. return result;
  2129. };
  2130. Plane.FromPositionAndNormal = function (origin, normal) {
  2131. var result = new Plane(0, 0, 0, 0);
  2132. normal.normalize();
  2133. result.normal = normal;
  2134. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2135. return result;
  2136. };
  2137. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2138. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2139. return Vector3.Dot(point, normal) + d;
  2140. };
  2141. return Plane;
  2142. })();
  2143. BABYLON.Plane = Plane;
  2144. var Viewport = (function () {
  2145. function Viewport(x, y, width, height) {
  2146. this.x = x;
  2147. this.y = y;
  2148. this.width = width;
  2149. this.height = height;
  2150. }
  2151. Viewport.prototype.toGlobal = function (engine) {
  2152. var width = engine.getRenderWidth();
  2153. var height = engine.getRenderHeight();
  2154. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2155. };
  2156. return Viewport;
  2157. })();
  2158. BABYLON.Viewport = Viewport;
  2159. var Frustum = (function () {
  2160. function Frustum() {
  2161. }
  2162. Frustum.GetPlanes = function (transform) {
  2163. var frustumPlanes = [];
  2164. for (var index = 0; index < 6; index++) {
  2165. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2166. }
  2167. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2168. return frustumPlanes;
  2169. };
  2170. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2171. // Near
  2172. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2173. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2174. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2175. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2176. frustumPlanes[0].normalize();
  2177. // Far
  2178. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2179. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2180. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2181. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2182. frustumPlanes[1].normalize();
  2183. // Left
  2184. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2185. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2186. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2187. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2188. frustumPlanes[2].normalize();
  2189. // Right
  2190. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2191. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2192. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2193. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2194. frustumPlanes[3].normalize();
  2195. // Top
  2196. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2197. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2198. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2199. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2200. frustumPlanes[4].normalize();
  2201. // Bottom
  2202. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2203. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2204. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2205. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2206. frustumPlanes[5].normalize();
  2207. };
  2208. return Frustum;
  2209. })();
  2210. BABYLON.Frustum = Frustum;
  2211. var Ray = (function () {
  2212. function Ray(origin, direction, length) {
  2213. if (length === void 0) { length = Number.MAX_VALUE; }
  2214. this.origin = origin;
  2215. this.direction = direction;
  2216. this.length = length;
  2217. }
  2218. // Methods
  2219. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2220. var d = 0.0;
  2221. var maxValue = Number.MAX_VALUE;
  2222. if (Math.abs(this.direction.x) < 0.0000001) {
  2223. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2224. return false;
  2225. }
  2226. }
  2227. else {
  2228. var inv = 1.0 / this.direction.x;
  2229. var min = (minimum.x - this.origin.x) * inv;
  2230. var max = (maximum.x - this.origin.x) * inv;
  2231. if (max === -Infinity) {
  2232. max = Infinity;
  2233. }
  2234. if (min > max) {
  2235. var temp = min;
  2236. min = max;
  2237. max = temp;
  2238. }
  2239. d = Math.max(min, d);
  2240. maxValue = Math.min(max, maxValue);
  2241. if (d > maxValue) {
  2242. return false;
  2243. }
  2244. }
  2245. if (Math.abs(this.direction.y) < 0.0000001) {
  2246. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2247. return false;
  2248. }
  2249. }
  2250. else {
  2251. inv = 1.0 / this.direction.y;
  2252. min = (minimum.y - this.origin.y) * inv;
  2253. max = (maximum.y - this.origin.y) * inv;
  2254. if (max === -Infinity) {
  2255. max = Infinity;
  2256. }
  2257. if (min > max) {
  2258. temp = min;
  2259. min = max;
  2260. max = temp;
  2261. }
  2262. d = Math.max(min, d);
  2263. maxValue = Math.min(max, maxValue);
  2264. if (d > maxValue) {
  2265. return false;
  2266. }
  2267. }
  2268. if (Math.abs(this.direction.z) < 0.0000001) {
  2269. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2270. return false;
  2271. }
  2272. }
  2273. else {
  2274. inv = 1.0 / this.direction.z;
  2275. min = (minimum.z - this.origin.z) * inv;
  2276. max = (maximum.z - this.origin.z) * inv;
  2277. if (max === -Infinity) {
  2278. max = Infinity;
  2279. }
  2280. if (min > max) {
  2281. temp = min;
  2282. min = max;
  2283. max = temp;
  2284. }
  2285. d = Math.max(min, d);
  2286. maxValue = Math.min(max, maxValue);
  2287. if (d > maxValue) {
  2288. return false;
  2289. }
  2290. }
  2291. return true;
  2292. };
  2293. Ray.prototype.intersectsBox = function (box) {
  2294. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2295. };
  2296. Ray.prototype.intersectsSphere = function (sphere) {
  2297. var x = sphere.center.x - this.origin.x;
  2298. var y = sphere.center.y - this.origin.y;
  2299. var z = sphere.center.z - this.origin.z;
  2300. var pyth = (x * x) + (y * y) + (z * z);
  2301. var rr = sphere.radius * sphere.radius;
  2302. if (pyth <= rr) {
  2303. return true;
  2304. }
  2305. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2306. if (dot < 0.0) {
  2307. return false;
  2308. }
  2309. var temp = pyth - (dot * dot);
  2310. return temp <= rr;
  2311. };
  2312. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2313. if (!this._edge1) {
  2314. this._edge1 = Vector3.Zero();
  2315. this._edge2 = Vector3.Zero();
  2316. this._pvec = Vector3.Zero();
  2317. this._tvec = Vector3.Zero();
  2318. this._qvec = Vector3.Zero();
  2319. }
  2320. vertex1.subtractToRef(vertex0, this._edge1);
  2321. vertex2.subtractToRef(vertex0, this._edge2);
  2322. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2323. var det = Vector3.Dot(this._edge1, this._pvec);
  2324. if (det === 0) {
  2325. return null;
  2326. }
  2327. var invdet = 1 / det;
  2328. this.origin.subtractToRef(vertex0, this._tvec);
  2329. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2330. if (bu < 0 || bu > 1.0) {
  2331. return null;
  2332. }
  2333. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2334. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2335. if (bv < 0 || bu + bv > 1.0) {
  2336. return null;
  2337. }
  2338. //check if the distance is longer than the predefined length.
  2339. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2340. if (distance > this.length) {
  2341. return null;
  2342. }
  2343. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2344. };
  2345. // Statics
  2346. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2347. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2348. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2349. var direction = end.subtract(start);
  2350. direction.normalize();
  2351. return new Ray(start, direction);
  2352. };
  2353. /**
  2354. * 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
  2355. * transformed to the given world matrix.
  2356. * @param origin The origin point
  2357. * @param end The end point
  2358. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2359. */
  2360. Ray.CreateNewFromTo = function (origin, end, world) {
  2361. if (world === void 0) { world = Matrix.Identity(); }
  2362. var direction = end.subtract(origin);
  2363. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2364. direction.normalize();
  2365. return Ray.Transform(new Ray(origin, direction, length), world);
  2366. };
  2367. Ray.Transform = function (ray, matrix) {
  2368. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2369. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2370. return new Ray(newOrigin, newDirection, ray.length);
  2371. };
  2372. return Ray;
  2373. })();
  2374. BABYLON.Ray = Ray;
  2375. (function (Space) {
  2376. Space[Space["LOCAL"] = 0] = "LOCAL";
  2377. Space[Space["WORLD"] = 1] = "WORLD";
  2378. })(BABYLON.Space || (BABYLON.Space = {}));
  2379. var Space = BABYLON.Space;
  2380. var Axis = (function () {
  2381. function Axis() {
  2382. }
  2383. Axis.X = new Vector3(1, 0, 0);
  2384. Axis.Y = new Vector3(0, 1, 0);
  2385. Axis.Z = new Vector3(0, 0, 1);
  2386. return Axis;
  2387. })();
  2388. BABYLON.Axis = Axis;
  2389. ;
  2390. var BezierCurve = (function () {
  2391. function BezierCurve() {
  2392. }
  2393. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2394. // Extract X (which is equal to time here)
  2395. var f0 = 1 - 3 * x2 + 3 * x1;
  2396. var f1 = 3 * x2 - 6 * x1;
  2397. var f2 = 3 * x1;
  2398. var refinedT = t;
  2399. for (var i = 0; i < 5; i++) {
  2400. var refinedT2 = refinedT * refinedT;
  2401. var refinedT3 = refinedT2 * refinedT;
  2402. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2403. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2404. refinedT -= (x - t) * slope;
  2405. refinedT = Math.min(1, Math.max(0, refinedT));
  2406. }
  2407. // Resolve cubic bezier for the given x
  2408. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2409. };
  2410. return BezierCurve;
  2411. })();
  2412. BABYLON.BezierCurve = BezierCurve;
  2413. (function (Orientation) {
  2414. Orientation[Orientation["CW"] = 0] = "CW";
  2415. Orientation[Orientation["CCW"] = 1] = "CCW";
  2416. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2417. var Orientation = BABYLON.Orientation;
  2418. var Angle = (function () {
  2419. function Angle(radians) {
  2420. var _this = this;
  2421. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2422. this.radians = function () { return _this._radians; };
  2423. this._radians = radians;
  2424. if (this._radians < 0)
  2425. this._radians += (2 * Math.PI);
  2426. }
  2427. Angle.BetweenTwoPoints = function (a, b) {
  2428. var delta = b.subtract(a);
  2429. var theta = Math.atan2(delta.y, delta.x);
  2430. return new Angle(theta);
  2431. };
  2432. Angle.FromRadians = function (radians) {
  2433. return new Angle(radians);
  2434. };
  2435. Angle.FromDegrees = function (degrees) {
  2436. return new Angle(degrees * Math.PI / 180);
  2437. };
  2438. return Angle;
  2439. })();
  2440. BABYLON.Angle = Angle;
  2441. var Arc2 = (function () {
  2442. function Arc2(startPoint, midPoint, endPoint) {
  2443. this.startPoint = startPoint;
  2444. this.midPoint = midPoint;
  2445. this.endPoint = endPoint;
  2446. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2447. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2448. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2449. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2450. 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);
  2451. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2452. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2453. var a1 = this.startAngle.degrees();
  2454. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2455. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2456. // angles correction
  2457. if (a2 - a1 > +180.0)
  2458. a2 -= 360.0;
  2459. if (a2 - a1 < -180.0)
  2460. a2 += 360.0;
  2461. if (a3 - a2 > +180.0)
  2462. a3 -= 360.0;
  2463. if (a3 - a2 < -180.0)
  2464. a3 += 360.0;
  2465. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2466. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2467. }
  2468. return Arc2;
  2469. })();
  2470. BABYLON.Arc2 = Arc2;
  2471. var PathCursor = (function () {
  2472. function PathCursor(path) {
  2473. this.path = path;
  2474. this._onchange = new Array();
  2475. this.value = 0;
  2476. this.animations = new Array();
  2477. }
  2478. PathCursor.prototype.getPoint = function () {
  2479. var point = this.path.getPointAtLengthPosition(this.value);
  2480. return new Vector3(point.x, 0, point.y);
  2481. };
  2482. PathCursor.prototype.moveAhead = function (step) {
  2483. if (step === void 0) { step = 0.002; }
  2484. this.move(step);
  2485. return this;
  2486. };
  2487. PathCursor.prototype.moveBack = function (step) {
  2488. if (step === void 0) { step = 0.002; }
  2489. this.move(-step);
  2490. return this;
  2491. };
  2492. PathCursor.prototype.move = function (step) {
  2493. if (Math.abs(step) > 1) {
  2494. throw "step size should be less than 1.";
  2495. }
  2496. this.value += step;
  2497. this.ensureLimits();
  2498. this.raiseOnChange();
  2499. return this;
  2500. };
  2501. PathCursor.prototype.ensureLimits = function () {
  2502. while (this.value > 1) {
  2503. this.value -= 1;
  2504. }
  2505. while (this.value < 0) {
  2506. this.value += 1;
  2507. }
  2508. return this;
  2509. };
  2510. // used by animation engine
  2511. PathCursor.prototype.markAsDirty = function (propertyName) {
  2512. this.ensureLimits();
  2513. this.raiseOnChange();
  2514. return this;
  2515. };
  2516. PathCursor.prototype.raiseOnChange = function () {
  2517. var _this = this;
  2518. this._onchange.forEach(function (f) { return f(_this); });
  2519. return this;
  2520. };
  2521. PathCursor.prototype.onchange = function (f) {
  2522. this._onchange.push(f);
  2523. return this;
  2524. };
  2525. return PathCursor;
  2526. })();
  2527. BABYLON.PathCursor = PathCursor;
  2528. var Path2 = (function () {
  2529. function Path2(x, y) {
  2530. this._points = new Array();
  2531. this._length = 0;
  2532. this.closed = false;
  2533. this._points.push(new Vector2(x, y));
  2534. }
  2535. Path2.prototype.addLineTo = function (x, y) {
  2536. if (closed) {
  2537. BABYLON.Tools.Error("cannot add lines to closed paths");
  2538. return this;
  2539. }
  2540. var newPoint = new Vector2(x, y);
  2541. var previousPoint = this._points[this._points.length - 1];
  2542. this._points.push(newPoint);
  2543. this._length += newPoint.subtract(previousPoint).length();
  2544. return this;
  2545. };
  2546. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2547. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2548. if (closed) {
  2549. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2550. return this;
  2551. }
  2552. var startPoint = this._points[this._points.length - 1];
  2553. var midPoint = new Vector2(midX, midY);
  2554. var endPoint = new Vector2(endX, endY);
  2555. var arc = new Arc2(startPoint, midPoint, endPoint);
  2556. var increment = arc.angle.radians() / numberOfSegments;
  2557. if (arc.orientation === 0 /* CW */)
  2558. increment *= -1;
  2559. var currentAngle = arc.startAngle.radians() + increment;
  2560. for (var i = 0; i < numberOfSegments; i++) {
  2561. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2562. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2563. this.addLineTo(x, y);
  2564. currentAngle += increment;
  2565. }
  2566. return this;
  2567. };
  2568. Path2.prototype.close = function () {
  2569. this.closed = true;
  2570. return this;
  2571. };
  2572. Path2.prototype.length = function () {
  2573. var result = this._length;
  2574. if (!this.closed) {
  2575. var lastPoint = this._points[this._points.length - 1];
  2576. var firstPoint = this._points[0];
  2577. result += (firstPoint.subtract(lastPoint).length());
  2578. }
  2579. return result;
  2580. };
  2581. Path2.prototype.getPoints = function () {
  2582. return this._points;
  2583. };
  2584. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2585. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2586. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2587. return Vector2.Zero();
  2588. }
  2589. var lengthPosition = normalizedLengthPosition * this.length();
  2590. var previousOffset = 0;
  2591. for (var i = 0; i < this._points.length; i++) {
  2592. var j = (i + 1) % this._points.length;
  2593. var a = this._points[i];
  2594. var b = this._points[j];
  2595. var bToA = b.subtract(a);
  2596. var nextOffset = (bToA.length() + previousOffset);
  2597. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2598. var dir = bToA.normalize();
  2599. var localOffset = lengthPosition - previousOffset;
  2600. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2601. }
  2602. previousOffset = nextOffset;
  2603. }
  2604. BABYLON.Tools.Error("internal error");
  2605. return Vector2.Zero();
  2606. };
  2607. Path2.StartingAt = function (x, y) {
  2608. return new Path2(x, y);
  2609. };
  2610. return Path2;
  2611. })();
  2612. BABYLON.Path2 = Path2;
  2613. var Path3D = (function () {
  2614. function Path3D(path) {
  2615. this.path = path;
  2616. this._curve = new Array();
  2617. this._distances = new Array();
  2618. this._tangents = new Array();
  2619. this._normals = new Array();
  2620. this._binormals = new Array();
  2621. this._curve = path.slice(); // copy array
  2622. this._compute();
  2623. }
  2624. Path3D.prototype.getCurve = function () {
  2625. return this._curve;
  2626. };
  2627. Path3D.prototype.getTangents = function () {
  2628. return this._tangents;
  2629. };
  2630. Path3D.prototype.getNormals = function () {
  2631. return this._normals;
  2632. };
  2633. Path3D.prototype.getBinormals = function () {
  2634. return this._binormals;
  2635. };
  2636. Path3D.prototype.getDistances = function () {
  2637. return this._distances;
  2638. };
  2639. Path3D.prototype.update = function (path) {
  2640. for (var i = 0; i < path.length; i++) {
  2641. this._curve[i] = path[i];
  2642. }
  2643. this._compute();
  2644. return this;
  2645. };
  2646. // private function compute() : computes tangents, normals and binormals
  2647. Path3D.prototype._compute = function () {
  2648. var l = this._curve.length;
  2649. // first and last tangents
  2650. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2651. this._tangents[0].normalize();
  2652. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2653. this._tangents[l - 1].normalize();
  2654. // normals and binormals at first point : arbitrary vector with _normalVector()
  2655. var tg0 = this._tangents[0];
  2656. var pp0 = this._normalVector(this._curve[0], tg0);
  2657. this._normals[0] = pp0;
  2658. this._normals[0].normalize();
  2659. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2660. this._normals[0].normalize();
  2661. this._distances[0] = 0;
  2662. // normals and binormals : next points
  2663. var prev; // previous vector (segment)
  2664. var cur; // current vector (segment)
  2665. var curTang; // current tangent
  2666. var prevNorm; // previous normal
  2667. var prevBinor; // previous binormal
  2668. for (var i = 1; i < l; i++) {
  2669. // tangents
  2670. prev = this._curve[i].subtract(this._curve[i - 1]);
  2671. if (i < l - 1) {
  2672. cur = this._curve[i + 1].subtract(this._curve[i]);
  2673. this._tangents[i] = prev.add(cur);
  2674. this._tangents[i].normalize();
  2675. }
  2676. this._distances[i] = this._distances[i - 1] + prev.length();
  2677. // normals and binormals
  2678. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2679. curTang = this._tangents[i];
  2680. prevNorm = this._normals[i - 1];
  2681. prevBinor = this._binormals[i - 1];
  2682. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2683. this._normals[i].normalize();
  2684. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2685. this._binormals[i].normalize();
  2686. }
  2687. };
  2688. // private function normalVector(v0, vt) :
  2689. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2690. Path3D.prototype._normalVector = function (v0, vt) {
  2691. var point;
  2692. if (vt.x !== 1) {
  2693. point = new Vector3(1, 0, 0);
  2694. }
  2695. else if (vt.y !== 1) {
  2696. point = new Vector3(0, 1, 0);
  2697. }
  2698. else if (vt.z !== 1) {
  2699. point = new Vector3(0, 0, 1);
  2700. }
  2701. var normal0 = Vector3.Cross(vt, point);
  2702. normal0.normalize();
  2703. return normal0;
  2704. };
  2705. return Path3D;
  2706. })();
  2707. BABYLON.Path3D = Path3D;
  2708. var Curve3 = (function () {
  2709. function Curve3(points) {
  2710. this._points = points;
  2711. }
  2712. // QuadraticBezier(origin_V3, control_V3, destination_V3 )
  2713. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2714. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2715. var bez = new Array();
  2716. var step = 1 / nbPoints;
  2717. var equation = function (t, val0, val1, val2) {
  2718. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2719. return res;
  2720. };
  2721. for (var i = 0; i <= 1; i += step) {
  2722. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x), equation(i, v0.y, v1.y, v2.y), equation(i, v0.z, v1.z, v2.z)));
  2723. }
  2724. return new Curve3(bez);
  2725. };
  2726. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2727. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2728. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2729. var bez = new Array();
  2730. var step = 1 / nbPoints;
  2731. var equation = function (t, val0, val1, val2, val3) {
  2732. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2733. return res;
  2734. };
  2735. for (var i = 0; i <= 1; i += step) {
  2736. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x, v3.x), equation(i, v0.y, v1.y, v2.y, v3.y), equation(i, v0.z, v1.z, v2.z, v3.z)));
  2737. }
  2738. return new Curve3(bez);
  2739. };
  2740. Curve3.prototype.getPoints = function () {
  2741. return this._points;
  2742. };
  2743. Curve3.prototype.continue = function (curve) {
  2744. var lastPoint = this._points[this._points.length - 1];
  2745. var continuedPoints = this._points.slice();
  2746. var curvePoints = curve.getPoints();
  2747. for (var i = 1; i < curvePoints.length; i++) {
  2748. continuedPoints.push(curvePoints[i].add(lastPoint));
  2749. }
  2750. return new Curve3(continuedPoints);
  2751. };
  2752. return Curve3;
  2753. })();
  2754. BABYLON.Curve3 = Curve3;
  2755. // Vertex formats
  2756. var PositionNormalVertex = (function () {
  2757. function PositionNormalVertex(position, normal) {
  2758. if (position === void 0) { position = Vector3.Zero(); }
  2759. if (normal === void 0) { normal = Vector3.Up(); }
  2760. this.position = position;
  2761. this.normal = normal;
  2762. }
  2763. PositionNormalVertex.prototype.clone = function () {
  2764. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2765. };
  2766. return PositionNormalVertex;
  2767. })();
  2768. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2769. var PositionNormalTextureVertex = (function () {
  2770. function PositionNormalTextureVertex(position, normal, uv) {
  2771. if (position === void 0) { position = Vector3.Zero(); }
  2772. if (normal === void 0) { normal = Vector3.Up(); }
  2773. if (uv === void 0) { uv = Vector2.Zero(); }
  2774. this.position = position;
  2775. this.normal = normal;
  2776. this.uv = uv;
  2777. }
  2778. PositionNormalTextureVertex.prototype.clone = function () {
  2779. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2780. };
  2781. return PositionNormalTextureVertex;
  2782. })();
  2783. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2784. // SIMD
  2785. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2786. var previousInvertToRef = Matrix.prototype.invertToRef;
  2787. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2788. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2789. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2790. var SIMDHelper = (function () {
  2791. function SIMDHelper() {
  2792. }
  2793. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2794. get: function () {
  2795. return SIMDHelper._isEnabled;
  2796. },
  2797. enumerable: true,
  2798. configurable: true
  2799. });
  2800. SIMDHelper.DisableSIMD = function () {
  2801. // Replace functions
  2802. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2803. Matrix.prototype.invertToRef = previousInvertToRef;
  2804. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2805. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2806. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2807. SIMDHelper._isEnabled = false;
  2808. };
  2809. SIMDHelper.EnableSIMD = function () {
  2810. if (window.SIMD === undefined) {
  2811. return;
  2812. }
  2813. // Replace functions
  2814. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2815. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2816. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2817. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2818. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2819. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2820. get: function () {
  2821. return this._data[0];
  2822. },
  2823. set: function (value) {
  2824. if (!this._data) {
  2825. this._data = new Float32Array(3);
  2826. }
  2827. this._data[0] = value;
  2828. }
  2829. });
  2830. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2831. get: function () {
  2832. return this._data[1];
  2833. },
  2834. set: function (value) {
  2835. this._data[1] = value;
  2836. }
  2837. });
  2838. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2839. get: function () {
  2840. return this._data[2];
  2841. },
  2842. set: function (value) {
  2843. this._data[2] = value;
  2844. }
  2845. });
  2846. SIMDHelper._isEnabled = true;
  2847. };
  2848. SIMDHelper._isEnabled = false;
  2849. return SIMDHelper;
  2850. })();
  2851. BABYLON.SIMDHelper = SIMDHelper;
  2852. if (window.SIMD !== undefined) {
  2853. SIMDHelper.EnableSIMD();
  2854. }
  2855. })(BABYLON || (BABYLON = {}));
  2856. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2857. (function (BABYLON) {
  2858. // Screenshots
  2859. var screenshotCanvas;
  2860. var cloneValue = function (source, destinationObject) {
  2861. if (!source)
  2862. return null;
  2863. if (source instanceof BABYLON.Mesh) {
  2864. return null;
  2865. }
  2866. if (source instanceof BABYLON.SubMesh) {
  2867. return source.clone(destinationObject);
  2868. }
  2869. else if (source.clone) {
  2870. return source.clone();
  2871. }
  2872. return null;
  2873. };
  2874. var Tools = (function () {
  2875. function Tools() {
  2876. }
  2877. Tools.GetFilename = function (path) {
  2878. var index = path.lastIndexOf("/");
  2879. if (index < 0)
  2880. return path;
  2881. return path.substring(index + 1);
  2882. };
  2883. Tools.GetDOMTextContent = function (element) {
  2884. var result = "";
  2885. var child = element.firstChild;
  2886. while (child) {
  2887. if (child.nodeType === 3) {
  2888. result += child.textContent;
  2889. }
  2890. child = child.nextSibling;
  2891. }
  2892. return result;
  2893. };
  2894. Tools.ToDegrees = function (angle) {
  2895. return angle * 180 / Math.PI;
  2896. };
  2897. Tools.ToRadians = function (angle) {
  2898. return angle * Math.PI / 180;
  2899. };
  2900. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2901. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2902. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2903. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2904. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2905. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2906. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2907. }
  2908. return {
  2909. minimum: minimum,
  2910. maximum: maximum
  2911. };
  2912. };
  2913. Tools.ExtractMinAndMax = function (positions, start, count) {
  2914. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2915. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2916. for (var index = start; index < start + count; index++) {
  2917. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2918. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2919. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2920. }
  2921. return {
  2922. minimum: minimum,
  2923. maximum: maximum
  2924. };
  2925. };
  2926. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2927. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2928. return undefined;
  2929. return Array.isArray(obj) ? obj : [obj];
  2930. };
  2931. // Misc.
  2932. Tools.GetPointerPrefix = function () {
  2933. var eventPrefix = "pointer";
  2934. // Check if hand.js is referenced or if the browser natively supports pointer events
  2935. if (!navigator.pointerEnabled) {
  2936. eventPrefix = "mouse";
  2937. }
  2938. return eventPrefix;
  2939. };
  2940. Tools.QueueNewFrame = function (func) {
  2941. if (window.requestAnimationFrame)
  2942. window.requestAnimationFrame(func);
  2943. else if (window.msRequestAnimationFrame)
  2944. window.msRequestAnimationFrame(func);
  2945. else if (window.webkitRequestAnimationFrame)
  2946. window.webkitRequestAnimationFrame(func);
  2947. else if (window.mozRequestAnimationFrame)
  2948. window.mozRequestAnimationFrame(func);
  2949. else if (window.oRequestAnimationFrame)
  2950. window.oRequestAnimationFrame(func);
  2951. else {
  2952. window.setTimeout(func, 16);
  2953. }
  2954. };
  2955. Tools.RequestFullscreen = function (element) {
  2956. if (element.requestFullscreen)
  2957. element.requestFullscreen();
  2958. else if (element.msRequestFullscreen)
  2959. element.msRequestFullscreen();
  2960. else if (element.webkitRequestFullscreen)
  2961. element.webkitRequestFullscreen();
  2962. else if (element.mozRequestFullScreen)
  2963. element.mozRequestFullScreen();
  2964. };
  2965. Tools.ExitFullscreen = function () {
  2966. if (document.exitFullscreen) {
  2967. document.exitFullscreen();
  2968. }
  2969. else if (document.mozCancelFullScreen) {
  2970. document.mozCancelFullScreen();
  2971. }
  2972. else if (document.webkitCancelFullScreen) {
  2973. document.webkitCancelFullScreen();
  2974. }
  2975. else if (document.msCancelFullScreen) {
  2976. document.msCancelFullScreen();
  2977. }
  2978. };
  2979. // External files
  2980. Tools.CleanUrl = function (url) {
  2981. url = url.replace(/#/mg, "%23");
  2982. return url;
  2983. };
  2984. Tools.LoadImage = function (url, onload, onerror, database) {
  2985. url = Tools.CleanUrl(url);
  2986. var img = new Image();
  2987. if (url.substr(0, 5) !== "data:")
  2988. img.crossOrigin = 'anonymous';
  2989. img.onload = function () {
  2990. onload(img);
  2991. };
  2992. img.onerror = function (err) {
  2993. onerror(img, err);
  2994. };
  2995. var noIndexedDB = function () {
  2996. img.src = url;
  2997. };
  2998. var loadFromIndexedDB = function () {
  2999. database.loadImageFromDB(url, img);
  3000. };
  3001. //ANY database to do!
  3002. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  3003. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3004. }
  3005. else {
  3006. if (url.indexOf("file:") === -1) {
  3007. noIndexedDB();
  3008. }
  3009. else {
  3010. try {
  3011. var textureName = url.substring(5);
  3012. var blobURL;
  3013. try {
  3014. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  3015. }
  3016. catch (ex) {
  3017. // Chrome doesn't support oneTimeOnly parameter
  3018. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  3019. }
  3020. img.src = blobURL;
  3021. }
  3022. catch (e) {
  3023. Tools.Log("Error while trying to load texture: " + textureName);
  3024. img.src = null;
  3025. }
  3026. }
  3027. }
  3028. return img;
  3029. };
  3030. //ANY
  3031. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  3032. url = Tools.CleanUrl(url);
  3033. var noIndexedDB = function () {
  3034. var request = new XMLHttpRequest();
  3035. var loadUrl = Tools.BaseUrl + url;
  3036. request.open('GET', loadUrl, true);
  3037. if (useArrayBuffer) {
  3038. request.responseType = "arraybuffer";
  3039. }
  3040. request.onprogress = progressCallBack;
  3041. request.onreadystatechange = function () {
  3042. if (request.readyState === 4) {
  3043. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  3044. callback(!useArrayBuffer ? request.responseText : request.response);
  3045. }
  3046. else {
  3047. if (onError) {
  3048. onError();
  3049. }
  3050. else {
  3051. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  3052. }
  3053. }
  3054. }
  3055. };
  3056. request.send(null);
  3057. };
  3058. var loadFromIndexedDB = function () {
  3059. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  3060. };
  3061. if (url.indexOf("file:") !== -1) {
  3062. var fileName = url.substring(5);
  3063. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  3064. }
  3065. else {
  3066. // Caching all files
  3067. if (database && database.enableSceneOffline) {
  3068. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3069. }
  3070. else {
  3071. noIndexedDB();
  3072. }
  3073. }
  3074. };
  3075. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  3076. var reader = new FileReader();
  3077. reader.onload = function (e) {
  3078. //target doesn't have result from ts 1.3
  3079. callback(e.target['result']);
  3080. };
  3081. reader.onprogress = progressCallback;
  3082. reader.readAsDataURL(fileToLoad);
  3083. };
  3084. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  3085. var reader = new FileReader();
  3086. reader.onerror = function (e) {
  3087. Tools.Log("Error while reading file: " + fileToLoad.name);
  3088. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  3089. };
  3090. reader.onload = function (e) {
  3091. //target doesn't have result from ts 1.3
  3092. callback(e.target['result']);
  3093. };
  3094. reader.onprogress = progressCallBack;
  3095. if (!useArrayBuffer) {
  3096. // Asynchronous read
  3097. reader.readAsText(fileToLoad);
  3098. }
  3099. else {
  3100. reader.readAsArrayBuffer(fileToLoad);
  3101. }
  3102. };
  3103. // Misc.
  3104. Tools.Clamp = function (value, min, max) {
  3105. if (min === void 0) { min = 0; }
  3106. if (max === void 0) { max = 1; }
  3107. return Math.min(max, Math.max(min, value));
  3108. };
  3109. // Returns -1 when value is a negative number and
  3110. // +1 when value is a positive number.
  3111. Tools.Sign = function (value) {
  3112. value = +value; // convert to a number
  3113. if (value === 0 || isNaN(value))
  3114. return value;
  3115. return value > 0 ? 1 : -1;
  3116. };
  3117. Tools.Format = function (value, decimals) {
  3118. if (decimals === void 0) { decimals = 2; }
  3119. return value.toFixed(decimals);
  3120. };
  3121. Tools.CheckExtends = function (v, min, max) {
  3122. if (v.x < min.x)
  3123. min.x = v.x;
  3124. if (v.y < min.y)
  3125. min.y = v.y;
  3126. if (v.z < min.z)
  3127. min.z = v.z;
  3128. if (v.x > max.x)
  3129. max.x = v.x;
  3130. if (v.y > max.y)
  3131. max.y = v.y;
  3132. if (v.z > max.z)
  3133. max.z = v.z;
  3134. };
  3135. Tools.WithinEpsilon = function (a, b, epsilon) {
  3136. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  3137. var num = a - b;
  3138. return -epsilon <= num && num <= epsilon;
  3139. };
  3140. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  3141. for (var prop in source) {
  3142. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  3143. continue;
  3144. }
  3145. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  3146. continue;
  3147. }
  3148. var sourceValue = source[prop];
  3149. var typeOfSourceValue = typeof sourceValue;
  3150. if (typeOfSourceValue === "function") {
  3151. continue;
  3152. }
  3153. if (typeOfSourceValue === "object") {
  3154. if (sourceValue instanceof Array) {
  3155. destination[prop] = [];
  3156. if (sourceValue.length > 0) {
  3157. if (typeof sourceValue[0] == "object") {
  3158. for (var index = 0; index < sourceValue.length; index++) {
  3159. var clonedValue = cloneValue(sourceValue[index], destination);
  3160. if (destination[prop].indexOf(clonedValue) === -1) {
  3161. destination[prop].push(clonedValue);
  3162. }
  3163. }
  3164. }
  3165. else {
  3166. destination[prop] = sourceValue.slice(0);
  3167. }
  3168. }
  3169. }
  3170. else {
  3171. destination[prop] = cloneValue(sourceValue, destination);
  3172. }
  3173. }
  3174. else {
  3175. destination[prop] = sourceValue;
  3176. }
  3177. }
  3178. };
  3179. Tools.IsEmpty = function (obj) {
  3180. for (var i in obj) {
  3181. return false;
  3182. }
  3183. return true;
  3184. };
  3185. Tools.RegisterTopRootEvents = function (events) {
  3186. for (var index = 0; index < events.length; index++) {
  3187. var event = events[index];
  3188. window.addEventListener(event.name, event.handler, false);
  3189. try {
  3190. if (window.parent) {
  3191. window.parent.addEventListener(event.name, event.handler, false);
  3192. }
  3193. }
  3194. catch (e) {
  3195. }
  3196. }
  3197. };
  3198. Tools.UnregisterTopRootEvents = function (events) {
  3199. for (var index = 0; index < events.length; index++) {
  3200. var event = events[index];
  3201. window.removeEventListener(event.name, event.handler);
  3202. try {
  3203. if (window.parent) {
  3204. window.parent.removeEventListener(event.name, event.handler);
  3205. }
  3206. }
  3207. catch (e) {
  3208. }
  3209. }
  3210. };
  3211. Tools.DumpFramebuffer = function (width, height, engine) {
  3212. // Read the contents of the framebuffer
  3213. var numberOfChannelsByLine = width * 4;
  3214. var halfHeight = height / 2;
  3215. //Reading datas from WebGL
  3216. var data = engine.readPixels(0, 0, width, height);
  3217. for (var i = 0; i < halfHeight; i++) {
  3218. for (var j = 0; j < numberOfChannelsByLine; j++) {
  3219. var currentCell = j + i * numberOfChannelsByLine;
  3220. var targetLine = height - i - 1;
  3221. var targetCell = j + targetLine * numberOfChannelsByLine;
  3222. var temp = data[currentCell];
  3223. data[currentCell] = data[targetCell];
  3224. data[targetCell] = temp;
  3225. }
  3226. }
  3227. // Create a 2D canvas to store the result
  3228. if (!screenshotCanvas) {
  3229. screenshotCanvas = document.createElement('canvas');
  3230. }
  3231. screenshotCanvas.width = width;
  3232. screenshotCanvas.height = height;
  3233. var context = screenshotCanvas.getContext('2d');
  3234. // Copy the pixels to a 2D canvas
  3235. var imageData = context.createImageData(width, height);
  3236. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  3237. var castData = imageData.data;
  3238. castData.set(data);
  3239. context.putImageData(imageData, 0, 0);
  3240. var base64Image = screenshotCanvas.toDataURL();
  3241. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  3242. if (("download" in document.createElement("a"))) {
  3243. var a = window.document.createElement("a");
  3244. a.href = base64Image;
  3245. var date = new Date();
  3246. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  3247. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  3248. window.document.body.appendChild(a);
  3249. a.addEventListener("click", function () {
  3250. a.parentElement.removeChild(a);
  3251. });
  3252. a.click();
  3253. }
  3254. else {
  3255. var newWindow = window.open("");
  3256. var img = newWindow.document.createElement("img");
  3257. img.src = base64Image;
  3258. newWindow.document.body.appendChild(img);
  3259. }
  3260. };
  3261. Tools.CreateScreenshot = function (engine, camera, size) {
  3262. var width;
  3263. var height;
  3264. var scene = camera.getScene();
  3265. var previousCamera = null;
  3266. if (scene.activeCamera !== camera) {
  3267. previousCamera = scene.activeCamera;
  3268. scene.activeCamera = camera;
  3269. }
  3270. //If a precision value is specified
  3271. if (size.precision) {
  3272. width = Math.round(engine.getRenderWidth() * size.precision);
  3273. height = Math.round(width / engine.getAspectRatio(camera));
  3274. size = { width: width, height: height };
  3275. }
  3276. else if (size.width && size.height) {
  3277. width = size.width;
  3278. height = size.height;
  3279. }
  3280. else if (size.width && !size.height) {
  3281. width = size.width;
  3282. height = Math.round(width / engine.getAspectRatio(camera));
  3283. size = { width: width, height: height };
  3284. }
  3285. else if (size.height && !size.width) {
  3286. height = size.height;
  3287. width = Math.round(height * engine.getAspectRatio(camera));
  3288. size = { width: width, height: height };
  3289. }
  3290. else if (!isNaN(size)) {
  3291. height = size;
  3292. width = size;
  3293. }
  3294. else {
  3295. Tools.Error("Invalid 'size' parameter !");
  3296. return;
  3297. }
  3298. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  3299. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  3300. texture.renderList = scene.meshes;
  3301. texture.onAfterRender = function () {
  3302. Tools.DumpFramebuffer(width, height, engine);
  3303. };
  3304. scene.incrementRenderId();
  3305. texture.render(true);
  3306. texture.dispose();
  3307. if (previousCamera) {
  3308. scene.activeCamera = previousCamera;
  3309. }
  3310. };
  3311. // XHR response validator for local file scenario
  3312. Tools.ValidateXHRData = function (xhr, dataType) {
  3313. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  3314. if (dataType === void 0) { dataType = 7; }
  3315. try {
  3316. if (dataType & 1) {
  3317. if (xhr.responseText && xhr.responseText.length > 0) {
  3318. return true;
  3319. }
  3320. else if (dataType === 1) {
  3321. return false;
  3322. }
  3323. }
  3324. if (dataType & 2) {
  3325. // Check header width and height since there is no "TGA" magic number
  3326. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3327. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3328. return true;
  3329. }
  3330. else if (dataType === 2) {
  3331. return false;
  3332. }
  3333. }
  3334. if (dataType & 4) {
  3335. // Check for the "DDS" magic number
  3336. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3337. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3338. return true;
  3339. }
  3340. else {
  3341. return false;
  3342. }
  3343. }
  3344. }
  3345. catch (e) {
  3346. }
  3347. return false;
  3348. };
  3349. Object.defineProperty(Tools, "NoneLogLevel", {
  3350. get: function () {
  3351. return Tools._NoneLogLevel;
  3352. },
  3353. enumerable: true,
  3354. configurable: true
  3355. });
  3356. Object.defineProperty(Tools, "MessageLogLevel", {
  3357. get: function () {
  3358. return Tools._MessageLogLevel;
  3359. },
  3360. enumerable: true,
  3361. configurable: true
  3362. });
  3363. Object.defineProperty(Tools, "WarningLogLevel", {
  3364. get: function () {
  3365. return Tools._WarningLogLevel;
  3366. },
  3367. enumerable: true,
  3368. configurable: true
  3369. });
  3370. Object.defineProperty(Tools, "ErrorLogLevel", {
  3371. get: function () {
  3372. return Tools._ErrorLogLevel;
  3373. },
  3374. enumerable: true,
  3375. configurable: true
  3376. });
  3377. Object.defineProperty(Tools, "AllLogLevel", {
  3378. get: function () {
  3379. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3380. },
  3381. enumerable: true,
  3382. configurable: true
  3383. });
  3384. Tools._AddLogEntry = function (entry) {
  3385. Tools._LogCache = entry + Tools._LogCache;
  3386. if (Tools.OnNewCacheEntry) {
  3387. Tools.OnNewCacheEntry(entry);
  3388. }
  3389. };
  3390. Tools._FormatMessage = function (message) {
  3391. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3392. var date = new Date();
  3393. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3394. };
  3395. Tools._LogDisabled = function (message) {
  3396. // nothing to do
  3397. };
  3398. Tools._LogEnabled = function (message) {
  3399. var formattedMessage = Tools._FormatMessage(message);
  3400. console.log("BJS - " + formattedMessage);
  3401. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3402. Tools._AddLogEntry(entry);
  3403. };
  3404. Tools._WarnDisabled = function (message) {
  3405. // nothing to do
  3406. };
  3407. Tools._WarnEnabled = function (message) {
  3408. var formattedMessage = Tools._FormatMessage(message);
  3409. console.warn("BJS - " + formattedMessage);
  3410. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3411. Tools._AddLogEntry(entry);
  3412. };
  3413. Tools._ErrorDisabled = function (message) {
  3414. // nothing to do
  3415. };
  3416. Tools._ErrorEnabled = function (message) {
  3417. var formattedMessage = Tools._FormatMessage(message);
  3418. console.error("BJS - " + formattedMessage);
  3419. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3420. Tools._AddLogEntry(entry);
  3421. };
  3422. Object.defineProperty(Tools, "LogCache", {
  3423. get: function () {
  3424. return Tools._LogCache;
  3425. },
  3426. enumerable: true,
  3427. configurable: true
  3428. });
  3429. Object.defineProperty(Tools, "LogLevels", {
  3430. set: function (level) {
  3431. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3432. Tools.Log = Tools._LogEnabled;
  3433. }
  3434. else {
  3435. Tools.Log = Tools._LogDisabled;
  3436. }
  3437. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3438. Tools.Warn = Tools._WarnEnabled;
  3439. }
  3440. else {
  3441. Tools.Warn = Tools._WarnDisabled;
  3442. }
  3443. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3444. Tools.Error = Tools._ErrorEnabled;
  3445. }
  3446. else {
  3447. Tools.Error = Tools._ErrorDisabled;
  3448. }
  3449. },
  3450. enumerable: true,
  3451. configurable: true
  3452. });
  3453. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3454. get: function () {
  3455. return Tools._PerformanceNoneLogLevel;
  3456. },
  3457. enumerable: true,
  3458. configurable: true
  3459. });
  3460. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3461. get: function () {
  3462. return Tools._PerformanceUserMarkLogLevel;
  3463. },
  3464. enumerable: true,
  3465. configurable: true
  3466. });
  3467. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3468. get: function () {
  3469. return Tools._PerformanceConsoleLogLevel;
  3470. },
  3471. enumerable: true,
  3472. configurable: true
  3473. });
  3474. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3475. set: function (level) {
  3476. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3477. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3478. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3479. return;
  3480. }
  3481. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3482. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3483. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3484. return;
  3485. }
  3486. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3487. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3488. },
  3489. enumerable: true,
  3490. configurable: true
  3491. });
  3492. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3493. };
  3494. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3495. };
  3496. Tools._StartUserMark = function (counterName, condition) {
  3497. if (condition === void 0) { condition = true; }
  3498. if (!condition || !Tools._performance.mark) {
  3499. return;
  3500. }
  3501. Tools._performance.mark(counterName + "-Begin");
  3502. };
  3503. Tools._EndUserMark = function (counterName, condition) {
  3504. if (condition === void 0) { condition = true; }
  3505. if (!condition || !Tools._performance.mark) {
  3506. return;
  3507. }
  3508. Tools._performance.mark(counterName + "-End");
  3509. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3510. };
  3511. Tools._StartPerformanceConsole = function (counterName, condition) {
  3512. if (condition === void 0) { condition = true; }
  3513. if (!condition) {
  3514. return;
  3515. }
  3516. Tools._StartUserMark(counterName, condition);
  3517. if (console.time) {
  3518. console.time(counterName);
  3519. }
  3520. };
  3521. Tools._EndPerformanceConsole = function (counterName, condition) {
  3522. if (condition === void 0) { condition = true; }
  3523. if (!condition) {
  3524. return;
  3525. }
  3526. Tools._EndUserMark(counterName, condition);
  3527. if (console.time) {
  3528. console.timeEnd(counterName);
  3529. }
  3530. };
  3531. Object.defineProperty(Tools, "Now", {
  3532. get: function () {
  3533. if (window.performance && window.performance.now) {
  3534. return window.performance.now();
  3535. }
  3536. return new Date().getTime();
  3537. },
  3538. enumerable: true,
  3539. configurable: true
  3540. });
  3541. // Deprecated
  3542. Tools.GetFps = function () {
  3543. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3544. return 0;
  3545. };
  3546. Tools.BaseUrl = "";
  3547. Tools.GetExponantOfTwo = function (value, max) {
  3548. var count = 1;
  3549. do {
  3550. count *= 2;
  3551. } while (count < value);
  3552. if (count > max)
  3553. count = max;
  3554. return count;
  3555. };
  3556. // Logs
  3557. Tools._NoneLogLevel = 0;
  3558. Tools._MessageLogLevel = 1;
  3559. Tools._WarningLogLevel = 2;
  3560. Tools._ErrorLogLevel = 4;
  3561. Tools._LogCache = "";
  3562. Tools.Log = Tools._LogEnabled;
  3563. Tools.Warn = Tools._WarnEnabled;
  3564. Tools.Error = Tools._ErrorEnabled;
  3565. // Performances
  3566. Tools._PerformanceNoneLogLevel = 0;
  3567. Tools._PerformanceUserMarkLogLevel = 1;
  3568. Tools._PerformanceConsoleLogLevel = 2;
  3569. Tools._performance = window.performance;
  3570. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3571. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3572. return Tools;
  3573. })();
  3574. BABYLON.Tools = Tools;
  3575. /**
  3576. * An implementation of a loop for asynchronous functions.
  3577. */
  3578. var AsyncLoop = (function () {
  3579. /**
  3580. * Constroctor.
  3581. * @param iterations the number of iterations.
  3582. * @param _fn the function to run each iteration
  3583. * @param _successCallback the callback that will be called upon succesful execution
  3584. * @param offset starting offset.
  3585. */
  3586. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3587. if (offset === void 0) { offset = 0; }
  3588. this.iterations = iterations;
  3589. this._fn = _fn;
  3590. this._successCallback = _successCallback;
  3591. this.index = offset - 1;
  3592. this._done = false;
  3593. }
  3594. /**
  3595. * Execute the next iteration. Must be called after the last iteration was finished.
  3596. */
  3597. AsyncLoop.prototype.executeNext = function () {
  3598. if (!this._done) {
  3599. if (this.index + 1 < this.iterations) {
  3600. ++this.index;
  3601. this._fn(this);
  3602. }
  3603. else {
  3604. this.breakLoop();
  3605. }
  3606. }
  3607. };
  3608. /**
  3609. * Break the loop and run the success callback.
  3610. */
  3611. AsyncLoop.prototype.breakLoop = function () {
  3612. this._done = true;
  3613. this._successCallback();
  3614. };
  3615. /**
  3616. * Helper function
  3617. */
  3618. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3619. if (offset === void 0) { offset = 0; }
  3620. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3621. loop.executeNext();
  3622. return loop;
  3623. };
  3624. /**
  3625. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3626. * @param iterations total number of iterations
  3627. * @param syncedIterations number of synchronous iterations in each async iteration.
  3628. * @param fn the function to call each iteration.
  3629. * @param callback a success call back that will be called when iterating stops.
  3630. * @param breakFunction a break condition (optional)
  3631. * @param timeout timeout settings for the setTimeout function. default - 0.
  3632. * @constructor
  3633. */
  3634. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3635. if (timeout === void 0) { timeout = 0; }
  3636. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3637. if (breakFunction && breakFunction())
  3638. loop.breakLoop();
  3639. else {
  3640. setTimeout(function () {
  3641. for (var i = 0; i < syncedIterations; ++i) {
  3642. var iteration = (loop.index * syncedIterations) + i;
  3643. if (iteration >= iterations)
  3644. break;
  3645. fn(iteration);
  3646. if (breakFunction && breakFunction()) {
  3647. loop.breakLoop();
  3648. break;
  3649. }
  3650. }
  3651. loop.executeNext();
  3652. }, timeout);
  3653. }
  3654. }, callback);
  3655. };
  3656. return AsyncLoop;
  3657. })();
  3658. BABYLON.AsyncLoop = AsyncLoop;
  3659. })(BABYLON || (BABYLON = {}));
  3660. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3661. (function (BABYLON) {
  3662. var _DepthCullingState = (function () {
  3663. function _DepthCullingState() {
  3664. this._isDepthTestDirty = false;
  3665. this._isDepthMaskDirty = false;
  3666. this._isDepthFuncDirty = false;
  3667. this._isCullFaceDirty = false;
  3668. this._isCullDirty = false;
  3669. this._isZOffsetDirty = false;
  3670. }
  3671. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3672. get: function () {
  3673. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  3674. },
  3675. enumerable: true,
  3676. configurable: true
  3677. });
  3678. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  3679. get: function () {
  3680. return this._zOffset;
  3681. },
  3682. set: function (value) {
  3683. if (this._zOffset === value) {
  3684. return;
  3685. }
  3686. this._zOffset = value;
  3687. this._isZOffsetDirty = true;
  3688. },
  3689. enumerable: true,
  3690. configurable: true
  3691. });
  3692. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3693. get: function () {
  3694. return this._cullFace;
  3695. },
  3696. set: function (value) {
  3697. if (this._cullFace === value) {
  3698. return;
  3699. }
  3700. this._cullFace = value;
  3701. this._isCullFaceDirty = true;
  3702. },
  3703. enumerable: true,
  3704. configurable: true
  3705. });
  3706. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3707. get: function () {
  3708. return this._cull;
  3709. },
  3710. set: function (value) {
  3711. if (this._cull === value) {
  3712. return;
  3713. }
  3714. this._cull = value;
  3715. this._isCullDirty = true;
  3716. },
  3717. enumerable: true,
  3718. configurable: true
  3719. });
  3720. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3721. get: function () {
  3722. return this._depthFunc;
  3723. },
  3724. set: function (value) {
  3725. if (this._depthFunc === value) {
  3726. return;
  3727. }
  3728. this._depthFunc = value;
  3729. this._isDepthFuncDirty = true;
  3730. },
  3731. enumerable: true,
  3732. configurable: true
  3733. });
  3734. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3735. get: function () {
  3736. return this._depthMask;
  3737. },
  3738. set: function (value) {
  3739. if (this._depthMask === value) {
  3740. return;
  3741. }
  3742. this._depthMask = value;
  3743. this._isDepthMaskDirty = true;
  3744. },
  3745. enumerable: true,
  3746. configurable: true
  3747. });
  3748. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3749. get: function () {
  3750. return this._depthTest;
  3751. },
  3752. set: function (value) {
  3753. if (this._depthTest === value) {
  3754. return;
  3755. }
  3756. this._depthTest = value;
  3757. this._isDepthTestDirty = true;
  3758. },
  3759. enumerable: true,
  3760. configurable: true
  3761. });
  3762. _DepthCullingState.prototype.reset = function () {
  3763. this._depthMask = true;
  3764. this._depthTest = true;
  3765. this._depthFunc = null;
  3766. this._cull = null;
  3767. this._cullFace = null;
  3768. this._zOffset = 0;
  3769. this._isDepthTestDirty = true;
  3770. this._isDepthMaskDirty = true;
  3771. this._isDepthFuncDirty = false;
  3772. this._isCullFaceDirty = false;
  3773. this._isCullDirty = false;
  3774. this._isZOffsetDirty = false;
  3775. };
  3776. _DepthCullingState.prototype.apply = function (gl) {
  3777. if (!this.isDirty) {
  3778. return;
  3779. }
  3780. // Cull
  3781. if (this._isCullDirty) {
  3782. if (this.cull) {
  3783. gl.enable(gl.CULL_FACE);
  3784. }
  3785. else {
  3786. gl.disable(gl.CULL_FACE);
  3787. }
  3788. this._isCullDirty = false;
  3789. }
  3790. // Cull face
  3791. if (this._isCullFaceDirty) {
  3792. gl.cullFace(this.cullFace);
  3793. this._isCullFaceDirty = false;
  3794. }
  3795. // Depth mask
  3796. if (this._isDepthMaskDirty) {
  3797. gl.depthMask(this.depthMask);
  3798. this._isDepthMaskDirty = false;
  3799. }
  3800. // Depth test
  3801. if (this._isDepthTestDirty) {
  3802. if (this.depthTest) {
  3803. gl.enable(gl.DEPTH_TEST);
  3804. }
  3805. else {
  3806. gl.disable(gl.DEPTH_TEST);
  3807. }
  3808. this._isDepthTestDirty = false;
  3809. }
  3810. // Depth func
  3811. if (this._isDepthFuncDirty) {
  3812. gl.depthFunc(this.depthFunc);
  3813. this._isDepthFuncDirty = false;
  3814. }
  3815. // zOffset
  3816. if (this._isZOffsetDirty) {
  3817. if (this.zOffset) {
  3818. gl.enable(gl.POLYGON_OFFSET_FILL);
  3819. gl.polygonOffset(this.zOffset, 0);
  3820. }
  3821. else {
  3822. gl.disable(gl.POLYGON_OFFSET_FILL);
  3823. }
  3824. this._isZOffsetDirty = false;
  3825. }
  3826. };
  3827. return _DepthCullingState;
  3828. })();
  3829. BABYLON._DepthCullingState = _DepthCullingState;
  3830. var _AlphaState = (function () {
  3831. function _AlphaState() {
  3832. this._isAlphaBlendDirty = false;
  3833. this._isBlendFunctionParametersDirty = false;
  3834. this._alphaBlend = false;
  3835. this._blendFunctionParameters = new Array(4);
  3836. }
  3837. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3838. get: function () {
  3839. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3840. },
  3841. enumerable: true,
  3842. configurable: true
  3843. });
  3844. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3845. get: function () {
  3846. return this._alphaBlend;
  3847. },
  3848. set: function (value) {
  3849. if (this._alphaBlend === value) {
  3850. return;
  3851. }
  3852. this._alphaBlend = value;
  3853. this._isAlphaBlendDirty = true;
  3854. },
  3855. enumerable: true,
  3856. configurable: true
  3857. });
  3858. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3859. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3860. return;
  3861. }
  3862. this._blendFunctionParameters[0] = value0;
  3863. this._blendFunctionParameters[1] = value1;
  3864. this._blendFunctionParameters[2] = value2;
  3865. this._blendFunctionParameters[3] = value3;
  3866. this._isBlendFunctionParametersDirty = true;
  3867. };
  3868. _AlphaState.prototype.reset = function () {
  3869. this._alphaBlend = false;
  3870. this._blendFunctionParameters[0] = null;
  3871. this._blendFunctionParameters[1] = null;
  3872. this._blendFunctionParameters[2] = null;
  3873. this._blendFunctionParameters[3] = null;
  3874. this._isAlphaBlendDirty = true;
  3875. this._isBlendFunctionParametersDirty = false;
  3876. };
  3877. _AlphaState.prototype.apply = function (gl) {
  3878. if (!this.isDirty) {
  3879. return;
  3880. }
  3881. // Alpha blend
  3882. if (this._isAlphaBlendDirty) {
  3883. if (this._alphaBlend) {
  3884. gl.enable(gl.BLEND);
  3885. }
  3886. else {
  3887. gl.disable(gl.BLEND);
  3888. }
  3889. this._isAlphaBlendDirty = false;
  3890. }
  3891. // Alpha function
  3892. if (this._isBlendFunctionParametersDirty) {
  3893. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3894. this._isBlendFunctionParametersDirty = false;
  3895. }
  3896. };
  3897. return _AlphaState;
  3898. })();
  3899. BABYLON._AlphaState = _AlphaState;
  3900. var compileShader = function (gl, source, type, defines) {
  3901. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3902. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3903. gl.compileShader(shader);
  3904. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3905. throw new Error(gl.getShaderInfoLog(shader));
  3906. }
  3907. return shader;
  3908. };
  3909. var getWebGLTextureType = function (gl, type) {
  3910. var textureType = gl.UNSIGNED_BYTE;
  3911. if (type === Engine.TEXTURETYPE_FLOAT)
  3912. textureType = gl.FLOAT;
  3913. return textureType;
  3914. };
  3915. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3916. var magFilter = gl.NEAREST;
  3917. var minFilter = gl.NEAREST;
  3918. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3919. magFilter = gl.LINEAR;
  3920. if (generateMipMaps) {
  3921. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3922. }
  3923. else {
  3924. minFilter = gl.LINEAR;
  3925. }
  3926. }
  3927. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3928. magFilter = gl.LINEAR;
  3929. if (generateMipMaps) {
  3930. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3931. }
  3932. else {
  3933. minFilter = gl.LINEAR;
  3934. }
  3935. }
  3936. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3937. magFilter = gl.NEAREST;
  3938. if (generateMipMaps) {
  3939. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3940. }
  3941. else {
  3942. minFilter = gl.NEAREST;
  3943. }
  3944. }
  3945. return {
  3946. min: minFilter,
  3947. mag: magFilter
  3948. };
  3949. };
  3950. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3951. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3952. var engine = scene.getEngine();
  3953. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3954. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3955. gl.bindTexture(gl.TEXTURE_2D, texture);
  3956. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3957. texture._baseWidth = width;
  3958. texture._baseHeight = height;
  3959. texture._width = potWidth;
  3960. texture._height = potHeight;
  3961. texture.isReady = true;
  3962. processFunction(potWidth, potHeight);
  3963. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3964. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3965. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3966. if (!noMipmap && !isCompressed) {
  3967. gl.generateMipmap(gl.TEXTURE_2D);
  3968. }
  3969. gl.bindTexture(gl.TEXTURE_2D, null);
  3970. engine._activeTexturesCache = [];
  3971. texture.samplingMode = samplingMode;
  3972. scene._removePendingData(texture);
  3973. };
  3974. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3975. var onload = function () {
  3976. loadedImages[index] = img;
  3977. loadedImages._internalCount++;
  3978. scene._removePendingData(img);
  3979. if (loadedImages._internalCount === 6) {
  3980. onfinish(loadedImages);
  3981. }
  3982. };
  3983. var onerror = function () {
  3984. scene._removePendingData(img);
  3985. };
  3986. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3987. scene._addPendingData(img);
  3988. };
  3989. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3990. var loadedImages = [];
  3991. loadedImages._internalCount = 0;
  3992. for (var index = 0; index < 6; index++) {
  3993. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3994. }
  3995. };
  3996. var EngineCapabilities = (function () {
  3997. function EngineCapabilities() {
  3998. }
  3999. return EngineCapabilities;
  4000. })();
  4001. BABYLON.EngineCapabilities = EngineCapabilities;
  4002. /**
  4003. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  4004. */
  4005. var Engine = (function () {
  4006. /**
  4007. * @constructor
  4008. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  4009. * @param {boolean} [antialias] - enable antialias
  4010. * @param options - further options to be sent to the getContext function
  4011. */
  4012. function Engine(canvas, antialias, options) {
  4013. var _this = this;
  4014. // Public members
  4015. this.isFullscreen = false;
  4016. this.isPointerLock = false;
  4017. this.cullBackFaces = true;
  4018. this.renderEvenInBackground = true;
  4019. this.scenes = new Array();
  4020. this._windowIsBackground = false;
  4021. this._loadingDivBackgroundColor = "black";
  4022. this._drawCalls = 0;
  4023. this._renderingQueueLaunched = false;
  4024. this._activeRenderLoops = [];
  4025. // FPS
  4026. this.fpsRange = 60;
  4027. this.previousFramesDuration = [];
  4028. this.fps = 60;
  4029. this.deltaTime = 0;
  4030. // States
  4031. this._depthCullingState = new _DepthCullingState();
  4032. this._alphaState = new _AlphaState();
  4033. this._alphaMode = Engine.ALPHA_DISABLE;
  4034. // Cache
  4035. this._loadedTexturesCache = new Array();
  4036. this._activeTexturesCache = new Array();
  4037. this._compiledEffects = {};
  4038. this._uintIndicesCurrentlySet = false;
  4039. this._renderingCanvas = canvas;
  4040. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4041. options = options || {};
  4042. options.antialias = antialias;
  4043. try {
  4044. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  4045. }
  4046. catch (e) {
  4047. throw new Error("WebGL not supported");
  4048. }
  4049. if (!this._gl) {
  4050. throw new Error("WebGL not supported");
  4051. }
  4052. this._onBlur = function () {
  4053. _this._windowIsBackground = true;
  4054. };
  4055. this._onFocus = function () {
  4056. _this._windowIsBackground = false;
  4057. };
  4058. window.addEventListener("blur", this._onBlur);
  4059. window.addEventListener("focus", this._onFocus);
  4060. // Viewport
  4061. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  4062. this.resize();
  4063. // Caps
  4064. this._caps = new EngineCapabilities();
  4065. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  4066. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  4067. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  4068. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  4069. // Infos
  4070. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  4071. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  4072. if (rendererInfo != null) {
  4073. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  4074. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  4075. }
  4076. if (!this._glVendor) {
  4077. this._glVendor = "Unknown vendor";
  4078. }
  4079. if (!this._glRenderer) {
  4080. this._glRenderer = "Unknown renderer";
  4081. }
  4082. // Extensions
  4083. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  4084. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  4085. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  4086. 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');
  4087. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  4088. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  4089. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  4090. this._caps.highPrecisionShaderSupported = true;
  4091. if (this._gl.getShaderPrecisionFormat) {
  4092. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  4093. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  4094. }
  4095. // Depth buffer
  4096. this.setDepthBuffer(true);
  4097. this.setDepthFunctionToLessOrEqual();
  4098. this.setDepthWrite(true);
  4099. // Fullscreen
  4100. this._onFullscreenChange = function () {
  4101. if (document.fullscreen !== undefined) {
  4102. _this.isFullscreen = document.fullscreen;
  4103. }
  4104. else if (document.mozFullScreen !== undefined) {
  4105. _this.isFullscreen = document.mozFullScreen;
  4106. }
  4107. else if (document.webkitIsFullScreen !== undefined) {
  4108. _this.isFullscreen = document.webkitIsFullScreen;
  4109. }
  4110. else if (document.msIsFullScreen !== undefined) {
  4111. _this.isFullscreen = document.msIsFullScreen;
  4112. }
  4113. // Pointer lock
  4114. if (_this.isFullscreen && _this._pointerLockRequested) {
  4115. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  4116. if (canvas.requestPointerLock) {
  4117. canvas.requestPointerLock();
  4118. }
  4119. }
  4120. };
  4121. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  4122. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  4123. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  4124. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  4125. // Pointer lock
  4126. this._onPointerLockChange = function () {
  4127. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  4128. };
  4129. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  4130. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  4131. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  4132. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  4133. if (!Engine.audioEngine) {
  4134. Engine.audioEngine = new BABYLON.AudioEngine();
  4135. }
  4136. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  4137. }
  4138. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  4139. get: function () {
  4140. return Engine._ALPHA_DISABLE;
  4141. },
  4142. enumerable: true,
  4143. configurable: true
  4144. });
  4145. Object.defineProperty(Engine, "ALPHA_ADD", {
  4146. get: function () {
  4147. return Engine._ALPHA_ADD;
  4148. },
  4149. enumerable: true,
  4150. configurable: true
  4151. });
  4152. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  4153. get: function () {
  4154. return Engine._ALPHA_COMBINE;
  4155. },
  4156. enumerable: true,
  4157. configurable: true
  4158. });
  4159. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  4160. get: function () {
  4161. return Engine._DELAYLOADSTATE_NONE;
  4162. },
  4163. enumerable: true,
  4164. configurable: true
  4165. });
  4166. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  4167. get: function () {
  4168. return Engine._DELAYLOADSTATE_LOADED;
  4169. },
  4170. enumerable: true,
  4171. configurable: true
  4172. });
  4173. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  4174. get: function () {
  4175. return Engine._DELAYLOADSTATE_LOADING;
  4176. },
  4177. enumerable: true,
  4178. configurable: true
  4179. });
  4180. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  4181. get: function () {
  4182. return Engine._DELAYLOADSTATE_NOTLOADED;
  4183. },
  4184. enumerable: true,
  4185. configurable: true
  4186. });
  4187. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  4188. get: function () {
  4189. return Engine._TEXTUREFORMAT_ALPHA;
  4190. },
  4191. enumerable: true,
  4192. configurable: true
  4193. });
  4194. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  4195. get: function () {
  4196. return Engine._TEXTUREFORMAT_LUMINANCE;
  4197. },
  4198. enumerable: true,
  4199. configurable: true
  4200. });
  4201. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  4202. get: function () {
  4203. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  4204. },
  4205. enumerable: true,
  4206. configurable: true
  4207. });
  4208. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  4209. get: function () {
  4210. return Engine._TEXTUREFORMAT_RGB;
  4211. },
  4212. enumerable: true,
  4213. configurable: true
  4214. });
  4215. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  4216. get: function () {
  4217. return Engine._TEXTUREFORMAT_RGBA;
  4218. },
  4219. enumerable: true,
  4220. configurable: true
  4221. });
  4222. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  4223. get: function () {
  4224. return Engine._TEXTURETYPE_UNSIGNED_INT;
  4225. },
  4226. enumerable: true,
  4227. configurable: true
  4228. });
  4229. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  4230. get: function () {
  4231. return Engine._TEXTURETYPE_FLOAT;
  4232. },
  4233. enumerable: true,
  4234. configurable: true
  4235. });
  4236. Object.defineProperty(Engine, "Version", {
  4237. get: function () {
  4238. return "2.1.0 beta";
  4239. },
  4240. enumerable: true,
  4241. configurable: true
  4242. });
  4243. Engine.prototype._prepareWorkingCanvas = function () {
  4244. if (this._workingCanvas) {
  4245. return;
  4246. }
  4247. this._workingCanvas = document.createElement("canvas");
  4248. this._workingContext = this._workingCanvas.getContext("2d");
  4249. };
  4250. Engine.prototype.getGlInfo = function () {
  4251. return {
  4252. vendor: this._glVendor,
  4253. renderer: this._glRenderer,
  4254. version: this._glVersion
  4255. };
  4256. };
  4257. Engine.prototype.getAspectRatio = function (camera) {
  4258. var viewport = camera.viewport;
  4259. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  4260. };
  4261. Engine.prototype.getRenderWidth = function () {
  4262. if (this._currentRenderTarget) {
  4263. return this._currentRenderTarget._width;
  4264. }
  4265. return this._renderingCanvas.width;
  4266. };
  4267. Engine.prototype.getRenderHeight = function () {
  4268. if (this._currentRenderTarget) {
  4269. return this._currentRenderTarget._height;
  4270. }
  4271. return this._renderingCanvas.height;
  4272. };
  4273. Engine.prototype.getRenderingCanvas = function () {
  4274. return this._renderingCanvas;
  4275. };
  4276. Engine.prototype.getRenderingCanvasClientRect = function () {
  4277. return this._renderingCanvas.getBoundingClientRect();
  4278. };
  4279. Engine.prototype.setHardwareScalingLevel = function (level) {
  4280. this._hardwareScalingLevel = level;
  4281. this.resize();
  4282. };
  4283. Engine.prototype.getHardwareScalingLevel = function () {
  4284. return this._hardwareScalingLevel;
  4285. };
  4286. Engine.prototype.getLoadedTexturesCache = function () {
  4287. return this._loadedTexturesCache;
  4288. };
  4289. Engine.prototype.getCaps = function () {
  4290. return this._caps;
  4291. };
  4292. Object.defineProperty(Engine.prototype, "drawCalls", {
  4293. get: function () {
  4294. return this._drawCalls;
  4295. },
  4296. enumerable: true,
  4297. configurable: true
  4298. });
  4299. // Methods
  4300. Engine.prototype.resetDrawCalls = function () {
  4301. this._drawCalls = 0;
  4302. };
  4303. Engine.prototype.setDepthFunctionToGreater = function () {
  4304. this._depthCullingState.depthFunc = this._gl.GREATER;
  4305. };
  4306. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  4307. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  4308. };
  4309. Engine.prototype.setDepthFunctionToLess = function () {
  4310. this._depthCullingState.depthFunc = this._gl.LESS;
  4311. };
  4312. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  4313. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  4314. };
  4315. /**
  4316. * stop executing a render loop function and remove it from the execution array
  4317. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  4318. */
  4319. Engine.prototype.stopRenderLoop = function (renderFunction) {
  4320. if (!renderFunction) {
  4321. this._activeRenderLoops = [];
  4322. return;
  4323. }
  4324. var index = this._activeRenderLoops.indexOf(renderFunction);
  4325. if (index >= 0) {
  4326. this._activeRenderLoops.splice(index, 1);
  4327. }
  4328. };
  4329. Engine.prototype._renderLoop = function () {
  4330. var _this = this;
  4331. var shouldRender = true;
  4332. if (!this.renderEvenInBackground && this._windowIsBackground) {
  4333. shouldRender = false;
  4334. }
  4335. if (shouldRender) {
  4336. // Start new frame
  4337. this.beginFrame();
  4338. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  4339. var renderFunction = this._activeRenderLoops[index];
  4340. renderFunction();
  4341. }
  4342. // Present
  4343. this.endFrame();
  4344. }
  4345. if (this._activeRenderLoops.length > 0) {
  4346. // Register new frame
  4347. BABYLON.Tools.QueueNewFrame(function () {
  4348. _this._renderLoop();
  4349. });
  4350. }
  4351. else {
  4352. this._renderingQueueLaunched = false;
  4353. }
  4354. };
  4355. /**
  4356. * Register and execute a render loop. The engine can have more than one render function.
  4357. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4358. * @example
  4359. * engine.runRenderLoop(function () {
  4360. * scene.render()
  4361. * })
  4362. */
  4363. Engine.prototype.runRenderLoop = function (renderFunction) {
  4364. var _this = this;
  4365. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4366. return;
  4367. }
  4368. this._activeRenderLoops.push(renderFunction);
  4369. if (!this._renderingQueueLaunched) {
  4370. this._renderingQueueLaunched = true;
  4371. BABYLON.Tools.QueueNewFrame(function () {
  4372. _this._renderLoop();
  4373. });
  4374. }
  4375. };
  4376. /**
  4377. * Toggle full screen mode.
  4378. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4379. */
  4380. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4381. if (this.isFullscreen) {
  4382. BABYLON.Tools.ExitFullscreen();
  4383. }
  4384. else {
  4385. this._pointerLockRequested = requestPointerLock;
  4386. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4387. }
  4388. };
  4389. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4390. this.applyStates();
  4391. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4392. if (this._depthCullingState.depthMask) {
  4393. this._gl.clearDepth(1.0);
  4394. }
  4395. var mode = 0;
  4396. if (backBuffer)
  4397. mode |= this._gl.COLOR_BUFFER_BIT;
  4398. if (depthStencil && this._depthCullingState.depthMask)
  4399. mode |= this._gl.DEPTH_BUFFER_BIT;
  4400. this._gl.clear(mode);
  4401. };
  4402. /**
  4403. * Set the WebGL's viewport
  4404. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4405. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4406. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4407. */
  4408. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4409. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  4410. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  4411. var x = viewport.x || 0;
  4412. var y = viewport.y || 0;
  4413. this._cachedViewport = viewport;
  4414. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4415. };
  4416. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4417. this._cachedViewport = null;
  4418. this._gl.viewport(x, y, width, height);
  4419. };
  4420. Engine.prototype.beginFrame = function () {
  4421. this._measureFps();
  4422. };
  4423. Engine.prototype.endFrame = function () {
  4424. //this.flushFramebuffer();
  4425. };
  4426. /**
  4427. * resize the view according to the canvas' size.
  4428. * @example
  4429. * window.addEventListener("resize", function () {
  4430. * engine.resize();
  4431. * });
  4432. */
  4433. Engine.prototype.resize = function () {
  4434. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  4435. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  4436. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  4437. };
  4438. /**
  4439. * force a specific size of the canvas
  4440. * @param {number} width - the new canvas' width
  4441. * @param {number} height - the new canvas' height
  4442. */
  4443. Engine.prototype.setSize = function (width, height) {
  4444. this._renderingCanvas.width = width;
  4445. this._renderingCanvas.height = height;
  4446. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4447. for (var index = 0; index < this.scenes.length; index++) {
  4448. var scene = this.scenes[index];
  4449. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  4450. var cam = scene.cameras[camIndex];
  4451. cam._currentRenderId = 0;
  4452. }
  4453. }
  4454. };
  4455. Engine.prototype.bindFramebuffer = function (texture) {
  4456. this._currentRenderTarget = texture;
  4457. var gl = this._gl;
  4458. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4459. this._gl.viewport(0, 0, texture._width, texture._height);
  4460. this.wipeCaches();
  4461. };
  4462. Engine.prototype.unBindFramebuffer = function (texture) {
  4463. this._currentRenderTarget = null;
  4464. if (texture.generateMipMaps) {
  4465. var gl = this._gl;
  4466. gl.bindTexture(gl.TEXTURE_2D, texture);
  4467. gl.generateMipmap(gl.TEXTURE_2D);
  4468. gl.bindTexture(gl.TEXTURE_2D, null);
  4469. }
  4470. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4471. };
  4472. Engine.prototype.flushFramebuffer = function () {
  4473. this._gl.flush();
  4474. };
  4475. Engine.prototype.restoreDefaultFramebuffer = function () {
  4476. this._currentRenderTarget = null;
  4477. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4478. this.setViewport(this._cachedViewport);
  4479. this.wipeCaches();
  4480. };
  4481. // VBOs
  4482. Engine.prototype._resetVertexBufferBinding = function () {
  4483. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4484. this._cachedVertexBuffers = null;
  4485. };
  4486. Engine.prototype.createVertexBuffer = function (vertices) {
  4487. var vbo = this._gl.createBuffer();
  4488. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4489. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4490. this._resetVertexBufferBinding();
  4491. vbo.references = 1;
  4492. return vbo;
  4493. };
  4494. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4495. var vbo = this._gl.createBuffer();
  4496. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4497. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4498. this._resetVertexBufferBinding();
  4499. vbo.references = 1;
  4500. return vbo;
  4501. };
  4502. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4503. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4504. if (offset === undefined) {
  4505. offset = 0;
  4506. }
  4507. if (vertices instanceof Float32Array) {
  4508. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4509. }
  4510. else {
  4511. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4512. }
  4513. this._resetVertexBufferBinding();
  4514. };
  4515. Engine.prototype._resetIndexBufferBinding = function () {
  4516. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4517. this._cachedIndexBuffer = null;
  4518. };
  4519. Engine.prototype.createIndexBuffer = function (indices) {
  4520. var vbo = this._gl.createBuffer();
  4521. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4522. // Check for 32 bits indices
  4523. var arrayBuffer;
  4524. var need32Bits = false;
  4525. if (this._caps.uintIndices) {
  4526. for (var index = 0; index < indices.length; index++) {
  4527. if (indices[index] > 65535) {
  4528. need32Bits = true;
  4529. break;
  4530. }
  4531. }
  4532. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4533. }
  4534. else {
  4535. arrayBuffer = new Uint16Array(indices);
  4536. }
  4537. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4538. this._resetIndexBufferBinding();
  4539. vbo.references = 1;
  4540. vbo.is32Bits = need32Bits;
  4541. return vbo;
  4542. };
  4543. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4544. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4545. this._cachedVertexBuffers = vertexBuffer;
  4546. this._cachedEffectForVertexBuffers = effect;
  4547. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4548. var offset = 0;
  4549. for (var index = 0; index < vertexDeclaration.length; index++) {
  4550. var order = effect.getAttributeLocation(index);
  4551. if (order >= 0) {
  4552. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4553. }
  4554. offset += vertexDeclaration[index] * 4;
  4555. }
  4556. }
  4557. if (this._cachedIndexBuffer !== indexBuffer) {
  4558. this._cachedIndexBuffer = indexBuffer;
  4559. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4560. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4561. }
  4562. };
  4563. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4564. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4565. this._cachedVertexBuffers = vertexBuffers;
  4566. this._cachedEffectForVertexBuffers = effect;
  4567. var attributes = effect.getAttributesNames();
  4568. for (var index = 0; index < attributes.length; index++) {
  4569. var order = effect.getAttributeLocation(index);
  4570. if (order >= 0) {
  4571. var vertexBuffer = vertexBuffers[attributes[index]];
  4572. if (!vertexBuffer) {
  4573. continue;
  4574. }
  4575. var stride = vertexBuffer.getStrideSize();
  4576. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4577. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4578. }
  4579. }
  4580. }
  4581. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4582. this._cachedIndexBuffer = indexBuffer;
  4583. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4584. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4585. }
  4586. };
  4587. Engine.prototype._releaseBuffer = function (buffer) {
  4588. buffer.references--;
  4589. if (buffer.references === 0) {
  4590. this._gl.deleteBuffer(buffer);
  4591. return true;
  4592. }
  4593. return false;
  4594. };
  4595. Engine.prototype.createInstancesBuffer = function (capacity) {
  4596. var buffer = this._gl.createBuffer();
  4597. buffer.capacity = capacity;
  4598. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4599. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4600. return buffer;
  4601. };
  4602. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4603. this._gl.deleteBuffer(buffer);
  4604. };
  4605. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4606. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4607. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4608. for (var index = 0; index < 4; index++) {
  4609. var offsetLocation = offsetLocations[index];
  4610. this._gl.enableVertexAttribArray(offsetLocation);
  4611. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4612. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4613. }
  4614. };
  4615. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4616. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4617. for (var index = 0; index < 4; index++) {
  4618. var offsetLocation = offsetLocations[index];
  4619. this._gl.disableVertexAttribArray(offsetLocation);
  4620. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4621. }
  4622. };
  4623. Engine.prototype.applyStates = function () {
  4624. this._depthCullingState.apply(this._gl);
  4625. this._alphaState.apply(this._gl);
  4626. };
  4627. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4628. // Apply states
  4629. this.applyStates();
  4630. this._drawCalls++;
  4631. // Render
  4632. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4633. if (instancesCount) {
  4634. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4635. return;
  4636. }
  4637. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4638. };
  4639. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4640. // Apply states
  4641. this.applyStates();
  4642. this._drawCalls++;
  4643. if (instancesCount) {
  4644. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4645. return;
  4646. }
  4647. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4648. };
  4649. // Shaders
  4650. Engine.prototype._releaseEffect = function (effect) {
  4651. if (this._compiledEffects[effect._key]) {
  4652. delete this._compiledEffects[effect._key];
  4653. if (effect.getProgram()) {
  4654. this._gl.deleteProgram(effect.getProgram());
  4655. }
  4656. }
  4657. };
  4658. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4659. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4660. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4661. var name = vertex + "+" + fragment + "@" + defines;
  4662. if (this._compiledEffects[name]) {
  4663. return this._compiledEffects[name];
  4664. }
  4665. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4666. effect._key = name;
  4667. this._compiledEffects[name] = effect;
  4668. return effect;
  4669. };
  4670. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4671. if (uniformsNames === void 0) { uniformsNames = []; }
  4672. if (samplers === void 0) { samplers = []; }
  4673. if (defines === void 0) { defines = ""; }
  4674. return this.createEffect({
  4675. vertex: "particles",
  4676. fragmentElement: fragmentName
  4677. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4678. };
  4679. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4680. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4681. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4682. var shaderProgram = this._gl.createProgram();
  4683. this._gl.attachShader(shaderProgram, vertexShader);
  4684. this._gl.attachShader(shaderProgram, fragmentShader);
  4685. this._gl.linkProgram(shaderProgram);
  4686. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4687. if (!linked) {
  4688. var error = this._gl.getProgramInfoLog(shaderProgram);
  4689. if (error) {
  4690. throw new Error(error);
  4691. }
  4692. }
  4693. this._gl.deleteShader(vertexShader);
  4694. this._gl.deleteShader(fragmentShader);
  4695. return shaderProgram;
  4696. };
  4697. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4698. var results = [];
  4699. for (var index = 0; index < uniformsNames.length; index++) {
  4700. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4701. }
  4702. return results;
  4703. };
  4704. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4705. var results = [];
  4706. for (var index = 0; index < attributesNames.length; index++) {
  4707. try {
  4708. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4709. }
  4710. catch (e) {
  4711. results.push(-1);
  4712. }
  4713. }
  4714. return results;
  4715. };
  4716. Engine.prototype.enableEffect = function (effect) {
  4717. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4718. if (effect && effect.onBind) {
  4719. effect.onBind(effect);
  4720. }
  4721. return;
  4722. }
  4723. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4724. // Use program
  4725. this._gl.useProgram(effect.getProgram());
  4726. for (var i in this._vertexAttribArrays) {
  4727. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4728. continue;
  4729. }
  4730. this._vertexAttribArrays[i] = false;
  4731. this._gl.disableVertexAttribArray(i);
  4732. }
  4733. var attributesCount = effect.getAttributesCount();
  4734. for (var index = 0; index < attributesCount; index++) {
  4735. // Attributes
  4736. var order = effect.getAttributeLocation(index);
  4737. if (order >= 0) {
  4738. this._vertexAttribArrays[order] = true;
  4739. this._gl.enableVertexAttribArray(order);
  4740. }
  4741. }
  4742. this._currentEffect = effect;
  4743. if (effect.onBind) {
  4744. effect.onBind(effect);
  4745. }
  4746. };
  4747. Engine.prototype.setArray = function (uniform, array) {
  4748. if (!uniform)
  4749. return;
  4750. this._gl.uniform1fv(uniform, array);
  4751. };
  4752. Engine.prototype.setArray2 = function (uniform, array) {
  4753. if (!uniform || array.length % 2 !== 0)
  4754. return;
  4755. this._gl.uniform2fv(uniform, array);
  4756. };
  4757. Engine.prototype.setArray3 = function (uniform, array) {
  4758. if (!uniform || array.length % 3 !== 0)
  4759. return;
  4760. this._gl.uniform3fv(uniform, array);
  4761. };
  4762. Engine.prototype.setArray4 = function (uniform, array) {
  4763. if (!uniform || array.length % 4 !== 0)
  4764. return;
  4765. this._gl.uniform4fv(uniform, array);
  4766. };
  4767. Engine.prototype.setMatrices = function (uniform, matrices) {
  4768. if (!uniform)
  4769. return;
  4770. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4771. };
  4772. Engine.prototype.setMatrix = function (uniform, matrix) {
  4773. if (!uniform)
  4774. return;
  4775. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4776. };
  4777. Engine.prototype.setFloat = function (uniform, value) {
  4778. if (!uniform)
  4779. return;
  4780. this._gl.uniform1f(uniform, value);
  4781. };
  4782. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4783. if (!uniform)
  4784. return;
  4785. this._gl.uniform2f(uniform, x, y);
  4786. };
  4787. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4788. if (!uniform)
  4789. return;
  4790. this._gl.uniform3f(uniform, x, y, z);
  4791. };
  4792. Engine.prototype.setBool = function (uniform, bool) {
  4793. if (!uniform)
  4794. return;
  4795. this._gl.uniform1i(uniform, bool);
  4796. };
  4797. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4798. if (!uniform)
  4799. return;
  4800. this._gl.uniform4f(uniform, x, y, z, w);
  4801. };
  4802. Engine.prototype.setColor3 = function (uniform, color3) {
  4803. if (!uniform)
  4804. return;
  4805. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4806. };
  4807. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4808. if (!uniform)
  4809. return;
  4810. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4811. };
  4812. // States
  4813. Engine.prototype.setState = function (culling, zOffset, force) {
  4814. if (zOffset === void 0) { zOffset = 0; }
  4815. // Culling
  4816. if (this._depthCullingState.cull !== culling || force) {
  4817. if (culling) {
  4818. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4819. this._depthCullingState.cull = true;
  4820. }
  4821. else {
  4822. this._depthCullingState.cull = false;
  4823. }
  4824. }
  4825. // Z offset
  4826. this._depthCullingState.zOffset = zOffset;
  4827. };
  4828. Engine.prototype.setDepthBuffer = function (enable) {
  4829. this._depthCullingState.depthTest = enable;
  4830. };
  4831. Engine.prototype.getDepthWrite = function () {
  4832. return this._depthCullingState.depthMask;
  4833. };
  4834. Engine.prototype.setDepthWrite = function (enable) {
  4835. this._depthCullingState.depthMask = enable;
  4836. };
  4837. Engine.prototype.setColorWrite = function (enable) {
  4838. this._gl.colorMask(enable, enable, enable, enable);
  4839. };
  4840. Engine.prototype.setAlphaMode = function (mode) {
  4841. switch (mode) {
  4842. case Engine.ALPHA_DISABLE:
  4843. this.setDepthWrite(true);
  4844. this._alphaState.alphaBlend = false;
  4845. break;
  4846. case Engine.ALPHA_COMBINE:
  4847. this.setDepthWrite(false);
  4848. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4849. this._alphaState.alphaBlend = true;
  4850. break;
  4851. case Engine.ALPHA_ADD:
  4852. this.setDepthWrite(false);
  4853. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4854. this._alphaState.alphaBlend = true;
  4855. break;
  4856. }
  4857. this._alphaMode = mode;
  4858. };
  4859. Engine.prototype.getAlphaMode = function () {
  4860. return this._alphaMode;
  4861. };
  4862. Engine.prototype.setAlphaTesting = function (enable) {
  4863. this._alphaTest = enable;
  4864. };
  4865. Engine.prototype.getAlphaTesting = function () {
  4866. return this._alphaTest;
  4867. };
  4868. // Textures
  4869. Engine.prototype.wipeCaches = function () {
  4870. this._activeTexturesCache = [];
  4871. this._currentEffect = null;
  4872. this._depthCullingState.reset();
  4873. this._alphaState.reset();
  4874. this._cachedVertexBuffers = null;
  4875. this._cachedIndexBuffer = null;
  4876. this._cachedEffectForVertexBuffers = null;
  4877. };
  4878. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4879. var gl = this._gl;
  4880. gl.bindTexture(gl.TEXTURE_2D, texture);
  4881. var magFilter = gl.NEAREST;
  4882. var minFilter = gl.NEAREST;
  4883. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4884. magFilter = gl.LINEAR;
  4885. minFilter = gl.LINEAR;
  4886. }
  4887. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4888. magFilter = gl.LINEAR;
  4889. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4890. }
  4891. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4892. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4893. gl.bindTexture(gl.TEXTURE_2D, null);
  4894. texture.samplingMode = samplingMode;
  4895. };
  4896. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4897. var _this = this;
  4898. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4899. if (onLoad === void 0) { onLoad = null; }
  4900. if (onError === void 0) { onError = null; }
  4901. if (buffer === void 0) { buffer = null; }
  4902. var texture = this._gl.createTexture();
  4903. var extension;
  4904. var fromData = false;
  4905. if (url.substr(0, 5) === "data:") {
  4906. fromData = true;
  4907. }
  4908. if (!fromData)
  4909. extension = url.substr(url.length - 4, 4).toLowerCase();
  4910. else {
  4911. var oldUrl = url;
  4912. fromData = oldUrl.split(':');
  4913. url = oldUrl;
  4914. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4915. }
  4916. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4917. var isTGA = (extension === ".tga");
  4918. scene._addPendingData(texture);
  4919. texture.url = url;
  4920. texture.noMipmap = noMipmap;
  4921. texture.references = 1;
  4922. this._loadedTexturesCache.push(texture);
  4923. var onerror = function () {
  4924. scene._removePendingData(texture);
  4925. if (onError) {
  4926. onError();
  4927. }
  4928. };
  4929. if (isTGA) {
  4930. var callback = function (arrayBuffer) {
  4931. var data = new Uint8Array(arrayBuffer);
  4932. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4933. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4934. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4935. if (onLoad) {
  4936. onLoad();
  4937. }
  4938. }, samplingMode);
  4939. };
  4940. if (!(fromData instanceof Array))
  4941. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4942. callback(arrayBuffer);
  4943. }, onerror, scene.database, true);
  4944. else
  4945. callback(buffer);
  4946. }
  4947. else if (isDDS) {
  4948. callback = function (data) {
  4949. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4950. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4951. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4952. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4953. if (onLoad) {
  4954. onLoad();
  4955. }
  4956. }, samplingMode);
  4957. };
  4958. if (!(fromData instanceof Array))
  4959. BABYLON.Tools.LoadFile(url, function (data) {
  4960. callback(data);
  4961. }, onerror, scene.database, true);
  4962. else
  4963. callback(buffer);
  4964. }
  4965. else {
  4966. var onload = function (img) {
  4967. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4968. var isPot = (img.width === potWidth && img.height === potHeight);
  4969. if (!isPot) {
  4970. _this._prepareWorkingCanvas();
  4971. _this._workingCanvas.width = potWidth;
  4972. _this._workingCanvas.height = potHeight;
  4973. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4974. _this._workingContext.imageSmoothingEnabled = false;
  4975. _this._workingContext.mozImageSmoothingEnabled = false;
  4976. _this._workingContext.oImageSmoothingEnabled = false;
  4977. _this._workingContext.webkitImageSmoothingEnabled = false;
  4978. _this._workingContext.msImageSmoothingEnabled = false;
  4979. }
  4980. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4981. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4982. _this._workingContext.imageSmoothingEnabled = true;
  4983. _this._workingContext.mozImageSmoothingEnabled = true;
  4984. _this._workingContext.oImageSmoothingEnabled = true;
  4985. _this._workingContext.webkitImageSmoothingEnabled = true;
  4986. _this._workingContext.msImageSmoothingEnabled = true;
  4987. }
  4988. }
  4989. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4990. if (onLoad) {
  4991. onLoad();
  4992. }
  4993. }, samplingMode);
  4994. };
  4995. if (!(fromData instanceof Array))
  4996. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4997. else
  4998. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4999. }
  5000. return texture;
  5001. };
  5002. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  5003. var texture = this._gl.createTexture();
  5004. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5005. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5006. // Format
  5007. var internalFormat = this._gl.RGBA;
  5008. switch (format) {
  5009. case Engine.TEXTUREFORMAT_ALPHA:
  5010. internalFormat = this._gl.ALPHA;
  5011. break;
  5012. case Engine.TEXTUREFORMAT_LUMINANCE:
  5013. internalFormat = this._gl.LUMINANCE;
  5014. break;
  5015. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  5016. internalFormat = this._gl.LUMINANCE_ALPHA;
  5017. break;
  5018. case Engine.TEXTUREFORMAT_RGB:
  5019. internalFormat = this._gl.RGB;
  5020. break;
  5021. case Engine.TEXTUREFORMAT_RGBA:
  5022. internalFormat = this._gl.RGBA;
  5023. break;
  5024. }
  5025. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  5026. if (generateMipMaps) {
  5027. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5028. }
  5029. // Filters
  5030. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  5031. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5032. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5033. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5034. this._activeTexturesCache = [];
  5035. texture._baseWidth = width;
  5036. texture._baseHeight = height;
  5037. texture._width = width;
  5038. texture._height = height;
  5039. texture.isReady = true;
  5040. texture.references = 1;
  5041. texture.samplingMode = samplingMode;
  5042. this._loadedTexturesCache.push(texture);
  5043. return texture;
  5044. };
  5045. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  5046. var texture = this._gl.createTexture();
  5047. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  5048. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  5049. this._activeTexturesCache = [];
  5050. texture._baseWidth = width;
  5051. texture._baseHeight = height;
  5052. texture._width = width;
  5053. texture._height = height;
  5054. texture.isReady = false;
  5055. texture.generateMipMaps = generateMipMaps;
  5056. texture.references = 1;
  5057. texture.samplingMode = samplingMode;
  5058. this.updateTextureSamplingMode(samplingMode, texture);
  5059. this._loadedTexturesCache.push(texture);
  5060. return texture;
  5061. };
  5062. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  5063. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  5064. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5065. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5066. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5067. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5068. };
  5069. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  5070. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5071. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  5072. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  5073. if (texture.generateMipMaps) {
  5074. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5075. }
  5076. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5077. this._activeTexturesCache = [];
  5078. texture.isReady = true;
  5079. };
  5080. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  5081. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5082. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  5083. // Scale the video if it is a NPOT using the current working canvas
  5084. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  5085. if (!texture._workingCanvas) {
  5086. texture._workingCanvas = document.createElement("canvas");
  5087. texture._workingContext = texture._workingCanvas.getContext("2d");
  5088. texture._workingCanvas.width = texture._width;
  5089. texture._workingCanvas.height = texture._height;
  5090. }
  5091. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  5092. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  5093. }
  5094. else {
  5095. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  5096. }
  5097. if (texture.generateMipMaps) {
  5098. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5099. }
  5100. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5101. this._activeTexturesCache = [];
  5102. texture.isReady = true;
  5103. };
  5104. Engine.prototype.createRenderTargetTexture = function (size, options) {
  5105. // old version had a "generateMipMaps" arg instead of options.
  5106. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  5107. // in the same way, generateDepthBuffer is defaulted to true
  5108. var generateMipMaps = false;
  5109. var generateDepthBuffer = true;
  5110. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5111. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  5112. if (options !== undefined) {
  5113. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  5114. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  5115. type = options.type === undefined ? type : options.type;
  5116. if (options.samplingMode !== undefined) {
  5117. samplingMode = options.samplingMode;
  5118. }
  5119. if (type === Engine.TEXTURETYPE_FLOAT) {
  5120. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  5121. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  5122. }
  5123. }
  5124. var gl = this._gl;
  5125. var texture = gl.createTexture();
  5126. gl.bindTexture(gl.TEXTURE_2D, texture);
  5127. var width = size.width || size;
  5128. var height = size.height || size;
  5129. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  5130. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  5131. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5132. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  5133. }
  5134. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5135. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5136. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5137. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5138. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  5139. var depthBuffer;
  5140. // Create the depth buffer
  5141. if (generateDepthBuffer) {
  5142. depthBuffer = gl.createRenderbuffer();
  5143. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  5144. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  5145. }
  5146. // Create the framebuffer
  5147. var framebuffer = gl.createFramebuffer();
  5148. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  5149. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5150. if (generateDepthBuffer) {
  5151. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  5152. }
  5153. // Unbind
  5154. gl.bindTexture(gl.TEXTURE_2D, null);
  5155. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  5156. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5157. texture._framebuffer = framebuffer;
  5158. if (generateDepthBuffer) {
  5159. texture._depthBuffer = depthBuffer;
  5160. }
  5161. texture._width = width;
  5162. texture._height = height;
  5163. texture.isReady = true;
  5164. texture.generateMipMaps = generateMipMaps;
  5165. texture.references = 1;
  5166. texture.samplingMode = samplingMode;
  5167. this._activeTexturesCache = [];
  5168. this._loadedTexturesCache.push(texture);
  5169. return texture;
  5170. };
  5171. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  5172. var _this = this;
  5173. var gl = this._gl;
  5174. var texture = gl.createTexture();
  5175. texture.isCube = true;
  5176. texture.url = rootUrl;
  5177. texture.references = 1;
  5178. this._loadedTexturesCache.push(texture);
  5179. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  5180. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  5181. if (isDDS) {
  5182. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  5183. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  5184. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  5185. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5186. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  5187. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  5188. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  5189. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5190. }
  5191. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5192. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  5193. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5194. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5195. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5196. _this._activeTexturesCache = [];
  5197. texture._width = info.width;
  5198. texture._height = info.height;
  5199. texture.isReady = true;
  5200. }, null, null, true);
  5201. }
  5202. else {
  5203. cascadeLoad(rootUrl, scene, function (imgs) {
  5204. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  5205. var height = width;
  5206. _this._prepareWorkingCanvas();
  5207. _this._workingCanvas.width = width;
  5208. _this._workingCanvas.height = height;
  5209. var faces = [
  5210. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  5211. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  5212. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  5213. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  5214. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  5215. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  5216. ];
  5217. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5218. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  5219. for (var index = 0; index < faces.length; index++) {
  5220. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  5221. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  5222. }
  5223. if (!noMipmap) {
  5224. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5225. }
  5226. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5227. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  5228. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5229. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5230. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5231. _this._activeTexturesCache = [];
  5232. texture._width = width;
  5233. texture._height = height;
  5234. texture.isReady = true;
  5235. }, extensions);
  5236. }
  5237. return texture;
  5238. };
  5239. Engine.prototype._releaseTexture = function (texture) {
  5240. var gl = this._gl;
  5241. if (texture._framebuffer) {
  5242. gl.deleteFramebuffer(texture._framebuffer);
  5243. }
  5244. if (texture._depthBuffer) {
  5245. gl.deleteRenderbuffer(texture._depthBuffer);
  5246. }
  5247. gl.deleteTexture(texture);
  5248. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  5249. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5250. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5251. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5252. this._activeTexturesCache[channel] = null;
  5253. }
  5254. var index = this._loadedTexturesCache.indexOf(texture);
  5255. if (index !== -1) {
  5256. this._loadedTexturesCache.splice(index, 1);
  5257. }
  5258. };
  5259. Engine.prototype.bindSamplers = function (effect) {
  5260. this._gl.useProgram(effect.getProgram());
  5261. var samplers = effect.getSamplers();
  5262. for (var index = 0; index < samplers.length; index++) {
  5263. var uniform = effect.getUniform(samplers[index]);
  5264. this._gl.uniform1i(uniform, index);
  5265. }
  5266. this._currentEffect = null;
  5267. };
  5268. Engine.prototype._bindTexture = function (channel, texture) {
  5269. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5270. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5271. this._activeTexturesCache[channel] = null;
  5272. };
  5273. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  5274. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  5275. };
  5276. Engine.prototype.setTexture = function (channel, texture) {
  5277. if (channel < 0) {
  5278. return;
  5279. }
  5280. // Not ready?
  5281. if (!texture || !texture.isReady()) {
  5282. if (this._activeTexturesCache[channel] != null) {
  5283. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5284. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5285. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5286. this._activeTexturesCache[channel] = null;
  5287. }
  5288. return;
  5289. }
  5290. // Video
  5291. if (texture instanceof BABYLON.VideoTexture) {
  5292. if (texture.update()) {
  5293. this._activeTexturesCache[channel] = null;
  5294. }
  5295. }
  5296. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  5297. texture.delayLoad();
  5298. return;
  5299. }
  5300. if (this._activeTexturesCache[channel] === texture) {
  5301. return;
  5302. }
  5303. this._activeTexturesCache[channel] = texture;
  5304. var internalTexture = texture.getInternalTexture();
  5305. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5306. if (internalTexture.isCube) {
  5307. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  5308. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5309. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5310. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5311. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5312. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  5313. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5314. }
  5315. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5316. }
  5317. else {
  5318. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  5319. if (internalTexture._cachedWrapU !== texture.wrapU) {
  5320. internalTexture._cachedWrapU = texture.wrapU;
  5321. switch (texture.wrapU) {
  5322. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5323. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  5324. break;
  5325. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5326. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  5327. break;
  5328. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5329. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  5330. break;
  5331. }
  5332. }
  5333. if (internalTexture._cachedWrapV !== texture.wrapV) {
  5334. internalTexture._cachedWrapV = texture.wrapV;
  5335. switch (texture.wrapV) {
  5336. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5337. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  5338. break;
  5339. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5340. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  5341. break;
  5342. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5343. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  5344. break;
  5345. }
  5346. }
  5347. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5348. }
  5349. };
  5350. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  5351. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5352. var value = texture.anisotropicFilteringLevel;
  5353. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5354. value = 1;
  5355. }
  5356. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  5357. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  5358. texture._cachedAnisotropicFilteringLevel = value;
  5359. }
  5360. };
  5361. Engine.prototype.readPixels = function (x, y, width, height) {
  5362. var data = new Uint8Array(height * width * 4);
  5363. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5364. return data;
  5365. };
  5366. // Dispose
  5367. Engine.prototype.dispose = function () {
  5368. this.hideLoadingUI();
  5369. this.stopRenderLoop();
  5370. while (this.scenes.length) {
  5371. this.scenes[0].dispose();
  5372. }
  5373. // Release audio engine
  5374. Engine.audioEngine.dispose();
  5375. for (var name in this._compiledEffects) {
  5376. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5377. }
  5378. for (var i in this._vertexAttribArrays) {
  5379. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5380. continue;
  5381. }
  5382. this._gl.disableVertexAttribArray(i);
  5383. }
  5384. // Events
  5385. window.removeEventListener("blur", this._onBlur);
  5386. window.removeEventListener("focus", this._onFocus);
  5387. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5388. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5389. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5390. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5391. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5392. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5393. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5394. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5395. };
  5396. // Loading screen
  5397. Engine.prototype.displayLoadingUI = function () {
  5398. var _this = this;
  5399. this._loadingDiv = document.createElement("div");
  5400. this._loadingDiv.style.opacity = "0";
  5401. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5402. // Loading text
  5403. this._loadingTextDiv = document.createElement("div");
  5404. this._loadingTextDiv.style.position = "absolute";
  5405. this._loadingTextDiv.style.left = "0";
  5406. this._loadingTextDiv.style.top = "50%";
  5407. this._loadingTextDiv.style.marginTop = "80px";
  5408. this._loadingTextDiv.style.width = "100%";
  5409. this._loadingTextDiv.style.height = "20px";
  5410. this._loadingTextDiv.style.fontFamily = "Arial";
  5411. this._loadingTextDiv.style.fontSize = "14px";
  5412. this._loadingTextDiv.style.color = "white";
  5413. this._loadingTextDiv.style.textAlign = "center";
  5414. this._loadingTextDiv.innerHTML = "Loading";
  5415. this._loadingDiv.appendChild(this._loadingTextDiv);
  5416. // Loading img
  5417. var imgBack = new Image();
  5418. 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==";
  5419. imgBack.style.position = "absolute";
  5420. imgBack.style.left = "50%";
  5421. imgBack.style.top = "50%";
  5422. imgBack.style.marginLeft = "-50px";
  5423. imgBack.style.marginTop = "-50px";
  5424. imgBack.style.transition = "transform 1.0s ease";
  5425. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5426. var deg = 360;
  5427. var onTransitionEnd = function () {
  5428. deg += 360;
  5429. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5430. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5431. };
  5432. imgBack.addEventListener("transitionend", onTransitionEnd);
  5433. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5434. this._loadingDiv.appendChild(imgBack);
  5435. // front image
  5436. var imgFront = new Image();
  5437. 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=";
  5438. imgFront.style.position = "absolute";
  5439. imgFront.style.left = "50%";
  5440. imgFront.style.top = "50%";
  5441. imgFront.style.marginLeft = "-50px";
  5442. imgFront.style.marginTop = "-50px";
  5443. this._loadingDiv.appendChild(imgFront);
  5444. // Resize
  5445. this._resizeLoadingUI = function () {
  5446. var canvasRect = _this.getRenderingCanvasClientRect();
  5447. _this._loadingDiv.style.position = "absolute";
  5448. _this._loadingDiv.style.left = canvasRect.left + "px";
  5449. _this._loadingDiv.style.top = canvasRect.top + "px";
  5450. _this._loadingDiv.style.width = canvasRect.width + "px";
  5451. _this._loadingDiv.style.height = canvasRect.height + "px";
  5452. };
  5453. this._resizeLoadingUI();
  5454. window.addEventListener("resize", this._resizeLoadingUI);
  5455. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5456. document.body.appendChild(this._loadingDiv);
  5457. setTimeout(function () {
  5458. _this._loadingDiv.style.opacity = "1";
  5459. imgBack.style.transform = "rotateZ(360deg)";
  5460. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5461. }, 0);
  5462. };
  5463. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5464. set: function (text) {
  5465. if (!this._loadingDiv) {
  5466. return;
  5467. }
  5468. this._loadingTextDiv.innerHTML = text;
  5469. },
  5470. enumerable: true,
  5471. configurable: true
  5472. });
  5473. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5474. get: function () {
  5475. return this._loadingDivBackgroundColor;
  5476. },
  5477. set: function (color) {
  5478. this._loadingDivBackgroundColor = color;
  5479. if (!this._loadingDiv) {
  5480. return;
  5481. }
  5482. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5483. },
  5484. enumerable: true,
  5485. configurable: true
  5486. });
  5487. Engine.prototype.hideLoadingUI = function () {
  5488. var _this = this;
  5489. if (!this._loadingDiv) {
  5490. return;
  5491. }
  5492. var onTransitionEnd = function () {
  5493. if (!_this._loadingDiv) {
  5494. return;
  5495. }
  5496. document.body.removeChild(_this._loadingDiv);
  5497. window.removeEventListener("resize", _this._resizeLoadingUI);
  5498. _this._loadingDiv = null;
  5499. };
  5500. this._loadingDiv.style.opacity = "0";
  5501. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5502. };
  5503. // FPS
  5504. Engine.prototype.getFps = function () {
  5505. return this.fps;
  5506. };
  5507. Engine.prototype.getDeltaTime = function () {
  5508. return this.deltaTime;
  5509. };
  5510. Engine.prototype._measureFps = function () {
  5511. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5512. var length = this.previousFramesDuration.length;
  5513. if (length >= 2) {
  5514. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5515. }
  5516. if (length >= this.fpsRange) {
  5517. if (length > this.fpsRange) {
  5518. this.previousFramesDuration.splice(0, 1);
  5519. length = this.previousFramesDuration.length;
  5520. }
  5521. var sum = 0;
  5522. for (var id = 0; id < length - 1; id++) {
  5523. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5524. }
  5525. this.fps = 1000.0 / (sum / (length - 1));
  5526. }
  5527. };
  5528. // Statics
  5529. Engine.isSupported = function () {
  5530. try {
  5531. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5532. if (navigator.isCocoonJS) {
  5533. return true;
  5534. }
  5535. var tempcanvas = document.createElement("canvas");
  5536. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5537. return gl != null && !!window.WebGLRenderingContext;
  5538. }
  5539. catch (e) {
  5540. return false;
  5541. }
  5542. };
  5543. // Const statics
  5544. Engine._ALPHA_DISABLE = 0;
  5545. Engine._ALPHA_ADD = 1;
  5546. Engine._ALPHA_COMBINE = 2;
  5547. Engine._DELAYLOADSTATE_NONE = 0;
  5548. Engine._DELAYLOADSTATE_LOADED = 1;
  5549. Engine._DELAYLOADSTATE_LOADING = 2;
  5550. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5551. Engine._TEXTUREFORMAT_ALPHA = 0;
  5552. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5553. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5554. Engine._TEXTUREFORMAT_RGB = 4;
  5555. Engine._TEXTUREFORMAT_RGBA = 4;
  5556. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5557. Engine._TEXTURETYPE_FLOAT = 1;
  5558. // Updatable statics so stick with vars here
  5559. Engine.Epsilon = 0.001;
  5560. Engine.CollisionsEpsilon = 0.001;
  5561. Engine.ShadersRepository = "Babylon/Shaders/";
  5562. return Engine;
  5563. })();
  5564. BABYLON.Engine = Engine;
  5565. })(BABYLON || (BABYLON = {}));
  5566. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5567. (function (BABYLON) {
  5568. /**
  5569. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5570. */
  5571. var Node = (function () {
  5572. /**
  5573. * @constructor
  5574. * @param {string} name - the name and id to be given to this node
  5575. * @param {BABYLON.Scene} the scene this node will be added to
  5576. */
  5577. function Node(name, scene) {
  5578. this.state = "";
  5579. this.animations = new Array();
  5580. this._childrenFlag = -1;
  5581. this._isEnabled = true;
  5582. this._isReady = true;
  5583. this._currentRenderId = -1;
  5584. this._parentRenderId = -1;
  5585. this.name = name;
  5586. this.id = name;
  5587. this._scene = scene;
  5588. this._initCache();
  5589. }
  5590. Node.prototype.getScene = function () {
  5591. return this._scene;
  5592. };
  5593. Node.prototype.getEngine = function () {
  5594. return this._scene.getEngine();
  5595. };
  5596. // override it in derived class
  5597. Node.prototype.getWorldMatrix = function () {
  5598. return BABYLON.Matrix.Identity();
  5599. };
  5600. // override it in derived class if you add new variables to the cache
  5601. // and call the parent class method
  5602. Node.prototype._initCache = function () {
  5603. this._cache = {};
  5604. this._cache.parent = undefined;
  5605. };
  5606. Node.prototype.updateCache = function (force) {
  5607. if (!force && this.isSynchronized())
  5608. return;
  5609. this._cache.parent = this.parent;
  5610. this._updateCache();
  5611. };
  5612. // override it in derived class if you add new variables to the cache
  5613. // and call the parent class method if !ignoreParentClass
  5614. Node.prototype._updateCache = function (ignoreParentClass) {
  5615. };
  5616. // override it in derived class if you add new variables to the cache
  5617. Node.prototype._isSynchronized = function () {
  5618. return true;
  5619. };
  5620. Node.prototype._markSyncedWithParent = function () {
  5621. this._parentRenderId = this.parent._currentRenderId;
  5622. };
  5623. Node.prototype.isSynchronizedWithParent = function () {
  5624. if (!this.parent) {
  5625. return true;
  5626. }
  5627. if (this._parentRenderId !== this.parent._currentRenderId) {
  5628. return false;
  5629. }
  5630. return this.parent.isSynchronized();
  5631. };
  5632. Node.prototype.isSynchronized = function (updateCache) {
  5633. var check = this.hasNewParent();
  5634. check = check || !this.isSynchronizedWithParent();
  5635. check = check || !this._isSynchronized();
  5636. if (updateCache)
  5637. this.updateCache(true);
  5638. return !check;
  5639. };
  5640. Node.prototype.hasNewParent = function (update) {
  5641. if (this._cache.parent === this.parent)
  5642. return false;
  5643. if (update)
  5644. this._cache.parent = this.parent;
  5645. return true;
  5646. };
  5647. /**
  5648. * Is this node ready to be used/rendered
  5649. * @return {boolean} is it ready
  5650. */
  5651. Node.prototype.isReady = function () {
  5652. return this._isReady;
  5653. };
  5654. /**
  5655. * Is this node enabled.
  5656. * If the node has a parent and is enabled, the parent will be inspected as well.
  5657. * @return {boolean} whether this node (and its parent) is enabled.
  5658. * @see setEnabled
  5659. */
  5660. Node.prototype.isEnabled = function () {
  5661. if (!this._isEnabled) {
  5662. return false;
  5663. }
  5664. if (this.parent) {
  5665. return this.parent.isEnabled();
  5666. }
  5667. return true;
  5668. };
  5669. /**
  5670. * Set the enabled state of this node.
  5671. * @param {boolean} value - the new enabled state
  5672. * @see isEnabled
  5673. */
  5674. Node.prototype.setEnabled = function (value) {
  5675. this._isEnabled = value;
  5676. };
  5677. /**
  5678. * Is this node a descendant of the given node.
  5679. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5680. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5681. * @see parent
  5682. */
  5683. Node.prototype.isDescendantOf = function (ancestor) {
  5684. if (this.parent) {
  5685. if (this.parent === ancestor) {
  5686. return true;
  5687. }
  5688. return this.parent.isDescendantOf(ancestor);
  5689. }
  5690. return false;
  5691. };
  5692. Node.prototype._getDescendants = function (list, results) {
  5693. for (var index = 0; index < list.length; index++) {
  5694. var item = list[index];
  5695. if (item.isDescendantOf(this)) {
  5696. results.push(item);
  5697. }
  5698. }
  5699. };
  5700. /**
  5701. * Will return all nodes that have this node as parent.
  5702. * @return {BABYLON.Node[]} all children nodes of all types.
  5703. */
  5704. Node.prototype.getDescendants = function () {
  5705. var results = [];
  5706. this._getDescendants(this._scene.meshes, results);
  5707. this._getDescendants(this._scene.lights, results);
  5708. this._getDescendants(this._scene.cameras, results);
  5709. return results;
  5710. };
  5711. Node.prototype._setReady = function (state) {
  5712. if (state == this._isReady) {
  5713. return;
  5714. }
  5715. if (!state) {
  5716. this._isReady = false;
  5717. return;
  5718. }
  5719. this._isReady = true;
  5720. if (this.onReady) {
  5721. this.onReady(this);
  5722. }
  5723. };
  5724. return Node;
  5725. })();
  5726. BABYLON.Node = Node;
  5727. })(BABYLON || (BABYLON = {}));
  5728. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5729. (function (BABYLON) {
  5730. var BoundingSphere = (function () {
  5731. function BoundingSphere(minimum, maximum) {
  5732. this.minimum = minimum;
  5733. this.maximum = maximum;
  5734. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5735. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5736. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5737. this.radius = distance * 0.5;
  5738. this.centerWorld = BABYLON.Vector3.Zero();
  5739. this._update(BABYLON.Matrix.Identity());
  5740. }
  5741. // Methods
  5742. BoundingSphere.prototype._update = function (world) {
  5743. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5744. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5745. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5746. };
  5747. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5748. for (var i = 0; i < 6; i++) {
  5749. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5750. return false;
  5751. }
  5752. return true;
  5753. };
  5754. BoundingSphere.prototype.intersectsPoint = function (point) {
  5755. var x = this.centerWorld.x - point.x;
  5756. var y = this.centerWorld.y - point.y;
  5757. var z = this.centerWorld.z - point.z;
  5758. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5759. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5760. return false;
  5761. return true;
  5762. };
  5763. // Statics
  5764. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5765. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5766. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5767. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5768. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5769. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5770. return false;
  5771. return true;
  5772. };
  5773. return BoundingSphere;
  5774. })();
  5775. BABYLON.BoundingSphere = BoundingSphere;
  5776. })(BABYLON || (BABYLON = {}));
  5777. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5778. (function (BABYLON) {
  5779. var BoundingBox = (function () {
  5780. function BoundingBox(minimum, maximum) {
  5781. this.minimum = minimum;
  5782. this.maximum = maximum;
  5783. this.vectors = new Array();
  5784. this.vectorsWorld = new Array();
  5785. // Bounding vectors
  5786. this.vectors.push(this.minimum.clone());
  5787. this.vectors.push(this.maximum.clone());
  5788. this.vectors.push(this.minimum.clone());
  5789. this.vectors[2].x = this.maximum.x;
  5790. this.vectors.push(this.minimum.clone());
  5791. this.vectors[3].y = this.maximum.y;
  5792. this.vectors.push(this.minimum.clone());
  5793. this.vectors[4].z = this.maximum.z;
  5794. this.vectors.push(this.maximum.clone());
  5795. this.vectors[5].z = this.minimum.z;
  5796. this.vectors.push(this.maximum.clone());
  5797. this.vectors[6].x = this.minimum.x;
  5798. this.vectors.push(this.maximum.clone());
  5799. this.vectors[7].y = this.minimum.y;
  5800. // OBB
  5801. this.center = this.maximum.add(this.minimum).scale(0.5);
  5802. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5803. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5804. for (var index = 0; index < this.vectors.length; index++) {
  5805. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5806. }
  5807. this.minimumWorld = BABYLON.Vector3.Zero();
  5808. this.maximumWorld = BABYLON.Vector3.Zero();
  5809. this._update(BABYLON.Matrix.Identity());
  5810. }
  5811. // Methods
  5812. BoundingBox.prototype.getWorldMatrix = function () {
  5813. return this._worldMatrix;
  5814. };
  5815. BoundingBox.prototype._update = function (world) {
  5816. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5817. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5818. for (var index = 0; index < this.vectors.length; index++) {
  5819. var v = this.vectorsWorld[index];
  5820. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5821. if (v.x < this.minimumWorld.x)
  5822. this.minimumWorld.x = v.x;
  5823. if (v.y < this.minimumWorld.y)
  5824. this.minimumWorld.y = v.y;
  5825. if (v.z < this.minimumWorld.z)
  5826. this.minimumWorld.z = v.z;
  5827. if (v.x > this.maximumWorld.x)
  5828. this.maximumWorld.x = v.x;
  5829. if (v.y > this.maximumWorld.y)
  5830. this.maximumWorld.y = v.y;
  5831. if (v.z > this.maximumWorld.z)
  5832. this.maximumWorld.z = v.z;
  5833. }
  5834. // OBB
  5835. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5836. this.center.scaleInPlace(0.5);
  5837. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5838. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5839. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5840. this._worldMatrix = world;
  5841. };
  5842. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5843. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5844. };
  5845. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5846. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5847. };
  5848. BoundingBox.prototype.intersectsPoint = function (point) {
  5849. var delta = BABYLON.Engine.Epsilon;
  5850. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5851. return false;
  5852. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5853. return false;
  5854. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5855. return false;
  5856. return true;
  5857. };
  5858. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5859. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5860. };
  5861. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5862. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5863. return false;
  5864. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5865. return false;
  5866. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5867. return false;
  5868. return true;
  5869. };
  5870. // Statics
  5871. BoundingBox.Intersects = function (box0, box1) {
  5872. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5873. return false;
  5874. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5875. return false;
  5876. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5877. return false;
  5878. return true;
  5879. };
  5880. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5881. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5882. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5883. return (num <= (sphereRadius * sphereRadius));
  5884. };
  5885. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5886. for (var p = 0; p < 6; p++) {
  5887. for (var i = 0; i < 8; i++) {
  5888. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5889. return false;
  5890. }
  5891. }
  5892. }
  5893. return true;
  5894. };
  5895. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5896. for (var p = 0; p < 6; p++) {
  5897. var inCount = 8;
  5898. for (var i = 0; i < 8; i++) {
  5899. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5900. --inCount;
  5901. }
  5902. else {
  5903. break;
  5904. }
  5905. }
  5906. if (inCount === 0)
  5907. return false;
  5908. }
  5909. return true;
  5910. };
  5911. return BoundingBox;
  5912. })();
  5913. BABYLON.BoundingBox = BoundingBox;
  5914. })(BABYLON || (BABYLON = {}));
  5915. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5916. (function (BABYLON) {
  5917. var computeBoxExtents = function (axis, box) {
  5918. var p = BABYLON.Vector3.Dot(box.center, axis);
  5919. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5920. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5921. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5922. var r = r0 + r1 + r2;
  5923. return {
  5924. min: p - r,
  5925. max: p + r
  5926. };
  5927. };
  5928. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5929. var axisOverlap = function (axis, box0, box1) {
  5930. var result0 = computeBoxExtents(axis, box0);
  5931. var result1 = computeBoxExtents(axis, box1);
  5932. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5933. };
  5934. var BoundingInfo = (function () {
  5935. function BoundingInfo(minimum, maximum) {
  5936. this.minimum = minimum;
  5937. this.maximum = maximum;
  5938. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5939. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5940. }
  5941. // Methods
  5942. BoundingInfo.prototype._update = function (world) {
  5943. this.boundingBox._update(world);
  5944. this.boundingSphere._update(world);
  5945. };
  5946. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5947. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5948. return false;
  5949. return this.boundingBox.isInFrustum(frustumPlanes);
  5950. };
  5951. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5952. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5953. };
  5954. BoundingInfo.prototype._checkCollision = function (collider) {
  5955. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5956. };
  5957. BoundingInfo.prototype.intersectsPoint = function (point) {
  5958. if (!this.boundingSphere.centerWorld) {
  5959. return false;
  5960. }
  5961. if (!this.boundingSphere.intersectsPoint(point)) {
  5962. return false;
  5963. }
  5964. if (!this.boundingBox.intersectsPoint(point)) {
  5965. return false;
  5966. }
  5967. return true;
  5968. };
  5969. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5970. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5971. return false;
  5972. }
  5973. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5974. return false;
  5975. }
  5976. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5977. return false;
  5978. }
  5979. if (!precise) {
  5980. return true;
  5981. }
  5982. var box0 = this.boundingBox;
  5983. var box1 = boundingInfo.boundingBox;
  5984. if (!axisOverlap(box0.directions[0], box0, box1))
  5985. return false;
  5986. if (!axisOverlap(box0.directions[1], box0, box1))
  5987. return false;
  5988. if (!axisOverlap(box0.directions[2], box0, box1))
  5989. return false;
  5990. if (!axisOverlap(box1.directions[0], box0, box1))
  5991. return false;
  5992. if (!axisOverlap(box1.directions[1], box0, box1))
  5993. return false;
  5994. if (!axisOverlap(box1.directions[2], box0, box1))
  5995. return false;
  5996. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5997. return false;
  5998. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5999. return false;
  6000. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  6001. return false;
  6002. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  6003. return false;
  6004. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  6005. return false;
  6006. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  6007. return false;
  6008. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  6009. return false;
  6010. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  6011. return false;
  6012. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  6013. return false;
  6014. return true;
  6015. };
  6016. return BoundingInfo;
  6017. })();
  6018. BABYLON.BoundingInfo = BoundingInfo;
  6019. })(BABYLON || (BABYLON = {}));
  6020. //# sourceMappingURL=babylon.boundingInfo.js.map
  6021. var BABYLON;
  6022. (function (BABYLON) {
  6023. var Light = (function (_super) {
  6024. __extends(Light, _super);
  6025. function Light(name, scene) {
  6026. _super.call(this, name, scene);
  6027. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  6028. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  6029. this.intensity = 1.0;
  6030. this.range = Number.MAX_VALUE;
  6031. this.includeOnlyWithLayerMask = 0;
  6032. this.includedOnlyMeshes = new Array();
  6033. this.excludedMeshes = new Array();
  6034. this.excludeWithLayerMask = 0;
  6035. this._excludedMeshesIds = new Array();
  6036. this._includedOnlyMeshesIds = new Array();
  6037. scene.addLight(this);
  6038. }
  6039. Light.prototype.getShadowGenerator = function () {
  6040. return this._shadowGenerator;
  6041. };
  6042. Light.prototype.getAbsolutePosition = function () {
  6043. return BABYLON.Vector3.Zero();
  6044. };
  6045. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  6046. };
  6047. Light.prototype._getWorldMatrix = function () {
  6048. return BABYLON.Matrix.Identity();
  6049. };
  6050. Light.prototype.canAffectMesh = function (mesh) {
  6051. if (!mesh) {
  6052. return true;
  6053. }
  6054. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  6055. return false;
  6056. }
  6057. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  6058. return false;
  6059. }
  6060. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  6061. return false;
  6062. }
  6063. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  6064. return false;
  6065. }
  6066. return true;
  6067. };
  6068. Light.prototype.getWorldMatrix = function () {
  6069. this._currentRenderId = this.getScene().getRenderId();
  6070. var worldMatrix = this._getWorldMatrix();
  6071. if (this.parent && this.parent.getWorldMatrix) {
  6072. if (!this._parentedWorldMatrix) {
  6073. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  6074. }
  6075. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  6076. this._markSyncedWithParent();
  6077. return this._parentedWorldMatrix;
  6078. }
  6079. return worldMatrix;
  6080. };
  6081. Light.prototype.dispose = function () {
  6082. if (this._shadowGenerator) {
  6083. this._shadowGenerator.dispose();
  6084. this._shadowGenerator = null;
  6085. }
  6086. // Remove from scene
  6087. this.getScene().removeLight(this);
  6088. };
  6089. return Light;
  6090. })(BABYLON.Node);
  6091. BABYLON.Light = Light;
  6092. })(BABYLON || (BABYLON = {}));
  6093. //# sourceMappingURL=babylon.light.js.map
  6094. var BABYLON;
  6095. (function (BABYLON) {
  6096. var PointLight = (function (_super) {
  6097. __extends(PointLight, _super);
  6098. function PointLight(name, position, scene) {
  6099. _super.call(this, name, scene);
  6100. this.position = position;
  6101. }
  6102. PointLight.prototype.getAbsolutePosition = function () {
  6103. return this._transformedPosition ? this._transformedPosition : this.position;
  6104. };
  6105. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  6106. if (this.parent && this.parent.getWorldMatrix) {
  6107. if (!this._transformedPosition) {
  6108. this._transformedPosition = BABYLON.Vector3.Zero();
  6109. }
  6110. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  6111. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  6112. return;
  6113. }
  6114. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  6115. };
  6116. PointLight.prototype.getShadowGenerator = function () {
  6117. return null;
  6118. };
  6119. PointLight.prototype._getWorldMatrix = function () {
  6120. if (!this._worldMatrix) {
  6121. this._worldMatrix = BABYLON.Matrix.Identity();
  6122. }
  6123. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6124. return this._worldMatrix;
  6125. };
  6126. return PointLight;
  6127. })(BABYLON.Light);
  6128. BABYLON.PointLight = PointLight;
  6129. })(BABYLON || (BABYLON = {}));
  6130. //# sourceMappingURL=babylon.pointLight.js.map
  6131. var BABYLON;
  6132. (function (BABYLON) {
  6133. var SpotLight = (function (_super) {
  6134. __extends(SpotLight, _super);
  6135. function SpotLight(name, position, direction, angle, exponent, scene) {
  6136. _super.call(this, name, scene);
  6137. this.position = position;
  6138. this.direction = direction;
  6139. this.angle = angle;
  6140. this.exponent = exponent;
  6141. }
  6142. SpotLight.prototype.getAbsolutePosition = function () {
  6143. return this.transformedPosition ? this.transformedPosition : this.position;
  6144. };
  6145. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6146. var activeCamera = this.getScene().activeCamera;
  6147. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  6148. };
  6149. SpotLight.prototype.supportsVSM = function () {
  6150. return true;
  6151. };
  6152. SpotLight.prototype.needRefreshPerFrame = function () {
  6153. return false;
  6154. };
  6155. SpotLight.prototype.setDirectionToTarget = function (target) {
  6156. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6157. return this.direction;
  6158. };
  6159. SpotLight.prototype.computeTransformedPosition = function () {
  6160. if (this.parent && this.parent.getWorldMatrix) {
  6161. if (!this.transformedPosition) {
  6162. this.transformedPosition = BABYLON.Vector3.Zero();
  6163. }
  6164. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6165. return true;
  6166. }
  6167. return false;
  6168. };
  6169. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  6170. var normalizeDirection;
  6171. if (this.parent && this.parent.getWorldMatrix) {
  6172. if (!this._transformedDirection) {
  6173. this._transformedDirection = BABYLON.Vector3.Zero();
  6174. }
  6175. this.computeTransformedPosition();
  6176. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6177. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  6178. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  6179. }
  6180. else {
  6181. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  6182. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6183. }
  6184. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  6185. };
  6186. SpotLight.prototype._getWorldMatrix = function () {
  6187. if (!this._worldMatrix) {
  6188. this._worldMatrix = BABYLON.Matrix.Identity();
  6189. }
  6190. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6191. return this._worldMatrix;
  6192. };
  6193. return SpotLight;
  6194. })(BABYLON.Light);
  6195. BABYLON.SpotLight = SpotLight;
  6196. })(BABYLON || (BABYLON = {}));
  6197. //# sourceMappingURL=babylon.spotLight.js.map
  6198. var BABYLON;
  6199. (function (BABYLON) {
  6200. var DirectionalLight = (function (_super) {
  6201. __extends(DirectionalLight, _super);
  6202. function DirectionalLight(name, direction, scene) {
  6203. _super.call(this, name, scene);
  6204. this.direction = direction;
  6205. this.shadowOrthoScale = 0.5;
  6206. this.position = direction.scale(-1);
  6207. }
  6208. DirectionalLight.prototype.getAbsolutePosition = function () {
  6209. return this.transformedPosition ? this.transformedPosition : this.position;
  6210. };
  6211. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  6212. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6213. return this.direction;
  6214. };
  6215. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6216. var orthoLeft = Number.MAX_VALUE;
  6217. var orthoRight = Number.MIN_VALUE;
  6218. var orthoTop = Number.MIN_VALUE;
  6219. var orthoBottom = Number.MAX_VALUE;
  6220. var tempVector3 = BABYLON.Vector3.Zero();
  6221. var activeCamera = this.getScene().activeCamera;
  6222. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  6223. var mesh = renderList[meshIndex];
  6224. if (!mesh) {
  6225. continue;
  6226. }
  6227. var boundingInfo = mesh.getBoundingInfo();
  6228. if (!boundingInfo) {
  6229. continue;
  6230. }
  6231. var boundingBox = boundingInfo.boundingBox;
  6232. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  6233. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  6234. if (tempVector3.x < orthoLeft)
  6235. orthoLeft = tempVector3.x;
  6236. if (tempVector3.y < orthoBottom)
  6237. orthoBottom = tempVector3.y;
  6238. if (tempVector3.x > orthoRight)
  6239. orthoRight = tempVector3.x;
  6240. if (tempVector3.y > orthoTop)
  6241. orthoTop = tempVector3.y;
  6242. }
  6243. }
  6244. var xOffset = orthoRight - orthoLeft;
  6245. var yOffset = orthoTop - orthoBottom;
  6246. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  6247. };
  6248. DirectionalLight.prototype.supportsVSM = function () {
  6249. return true;
  6250. };
  6251. DirectionalLight.prototype.needRefreshPerFrame = function () {
  6252. return true;
  6253. };
  6254. DirectionalLight.prototype.computeTransformedPosition = function () {
  6255. if (this.parent && this.parent.getWorldMatrix) {
  6256. if (!this.transformedPosition) {
  6257. this.transformedPosition = BABYLON.Vector3.Zero();
  6258. }
  6259. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6260. return true;
  6261. }
  6262. return false;
  6263. };
  6264. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  6265. if (this.parent && this.parent.getWorldMatrix) {
  6266. if (!this._transformedDirection) {
  6267. this._transformedDirection = BABYLON.Vector3.Zero();
  6268. }
  6269. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6270. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  6271. return;
  6272. }
  6273. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  6274. };
  6275. DirectionalLight.prototype._getWorldMatrix = function () {
  6276. if (!this._worldMatrix) {
  6277. this._worldMatrix = BABYLON.Matrix.Identity();
  6278. }
  6279. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6280. return this._worldMatrix;
  6281. };
  6282. return DirectionalLight;
  6283. })(BABYLON.Light);
  6284. BABYLON.DirectionalLight = DirectionalLight;
  6285. })(BABYLON || (BABYLON = {}));
  6286. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  6287. (function (BABYLON) {
  6288. var ShadowGenerator = (function () {
  6289. function ShadowGenerator(mapSize, light) {
  6290. var _this = this;
  6291. // Members
  6292. this._filter = ShadowGenerator.FILTER_NONE;
  6293. this.blurScale = 2;
  6294. this._blurBoxOffset = 0;
  6295. this._bias = 0.00005;
  6296. this._darkness = 0;
  6297. this._transparencyShadow = false;
  6298. this._viewMatrix = BABYLON.Matrix.Zero();
  6299. this._projectionMatrix = BABYLON.Matrix.Zero();
  6300. this._transformMatrix = BABYLON.Matrix.Zero();
  6301. this._worldViewProjection = BABYLON.Matrix.Zero();
  6302. this._light = light;
  6303. this._scene = light.getScene();
  6304. this._mapSize = mapSize;
  6305. light._shadowGenerator = this;
  6306. // Render target
  6307. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  6308. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6309. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6310. this._shadowMap.anisotropicFilteringLevel = 1;
  6311. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6312. this._shadowMap.renderParticles = false;
  6313. this._shadowMap.onAfterUnbind = function () {
  6314. if (!_this.useBlurVarianceShadowMap) {
  6315. return;
  6316. }
  6317. if (!_this._shadowMap2) {
  6318. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  6319. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6320. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6321. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  6322. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  6323. _this._downSamplePostprocess.onApply = function (effect) {
  6324. effect.setTexture("textureSampler", _this._shadowMap);
  6325. };
  6326. _this.blurBoxOffset = 1;
  6327. }
  6328. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  6329. };
  6330. // Custom render function
  6331. var renderSubMesh = function (subMesh) {
  6332. var mesh = subMesh.getRenderingMesh();
  6333. var scene = _this._scene;
  6334. var engine = scene.getEngine();
  6335. // Culling
  6336. engine.setState(subMesh.getMaterial().backFaceCulling);
  6337. // Managing instances
  6338. var batch = mesh._getInstancesRenderList(subMesh._id);
  6339. if (batch.mustReturn) {
  6340. return;
  6341. }
  6342. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  6343. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  6344. engine.enableEffect(_this._effect);
  6345. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  6346. var material = subMesh.getMaterial();
  6347. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  6348. // Alpha test
  6349. if (material && material.needAlphaTesting()) {
  6350. var alphaTexture = material.getAlphaTestTexture();
  6351. _this._effect.setTexture("diffuseSampler", alphaTexture);
  6352. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  6353. }
  6354. // Bones
  6355. if (mesh.useBones) {
  6356. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  6357. }
  6358. // Draw
  6359. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  6360. }
  6361. else {
  6362. // Need to reset refresh rate of the shadowMap
  6363. _this._shadowMap.resetRefreshCounter();
  6364. }
  6365. };
  6366. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  6367. var index;
  6368. for (index = 0; index < opaqueSubMeshes.length; index++) {
  6369. renderSubMesh(opaqueSubMeshes.data[index]);
  6370. }
  6371. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  6372. renderSubMesh(alphaTestSubMeshes.data[index]);
  6373. }
  6374. if (_this._transparencyShadow) {
  6375. for (index = 0; index < transparentSubMeshes.length; index++) {
  6376. renderSubMesh(transparentSubMeshes.data[index]);
  6377. }
  6378. }
  6379. };
  6380. this._shadowMap.onClear = function (engine) {
  6381. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  6382. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  6383. }
  6384. else {
  6385. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  6386. }
  6387. };
  6388. }
  6389. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  6390. // Static
  6391. get: function () {
  6392. return ShadowGenerator._FILTER_NONE;
  6393. },
  6394. enumerable: true,
  6395. configurable: true
  6396. });
  6397. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6398. get: function () {
  6399. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6400. },
  6401. enumerable: true,
  6402. configurable: true
  6403. });
  6404. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6405. get: function () {
  6406. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6407. },
  6408. enumerable: true,
  6409. configurable: true
  6410. });
  6411. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6412. get: function () {
  6413. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6414. },
  6415. enumerable: true,
  6416. configurable: true
  6417. });
  6418. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6419. get: function () {
  6420. return this._bias;
  6421. },
  6422. set: function (bias) {
  6423. this._bias = bias;
  6424. },
  6425. enumerable: true,
  6426. configurable: true
  6427. });
  6428. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6429. get: function () {
  6430. return this._blurBoxOffset;
  6431. },
  6432. set: function (value) {
  6433. var _this = this;
  6434. if (this._blurBoxOffset === value) {
  6435. return;
  6436. }
  6437. this._blurBoxOffset = value;
  6438. if (this._boxBlurPostprocess) {
  6439. this._boxBlurPostprocess.dispose();
  6440. }
  6441. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  6442. this._boxBlurPostprocess.onApply = function (effect) {
  6443. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6444. };
  6445. },
  6446. enumerable: true,
  6447. configurable: true
  6448. });
  6449. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  6450. get: function () {
  6451. return this._filter;
  6452. },
  6453. set: function (value) {
  6454. if (this._filter === value) {
  6455. return;
  6456. }
  6457. this._filter = value;
  6458. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6459. this._shadowMap.anisotropicFilteringLevel = 16;
  6460. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  6461. }
  6462. else {
  6463. this._shadowMap.anisotropicFilteringLevel = 1;
  6464. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6465. }
  6466. },
  6467. enumerable: true,
  6468. configurable: true
  6469. });
  6470. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6471. get: function () {
  6472. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6473. },
  6474. set: function (value) {
  6475. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6476. },
  6477. enumerable: true,
  6478. configurable: true
  6479. });
  6480. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6481. get: function () {
  6482. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6483. },
  6484. set: function (value) {
  6485. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6486. },
  6487. enumerable: true,
  6488. configurable: true
  6489. });
  6490. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6491. get: function () {
  6492. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6493. },
  6494. set: function (value) {
  6495. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6496. },
  6497. enumerable: true,
  6498. configurable: true
  6499. });
  6500. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6501. var defines = [];
  6502. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6503. defines.push("#define VSM");
  6504. }
  6505. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6506. var mesh = subMesh.getMesh();
  6507. var material = subMesh.getMaterial();
  6508. // Alpha test
  6509. if (material && material.needAlphaTesting()) {
  6510. defines.push("#define ALPHATEST");
  6511. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6512. attribs.push(BABYLON.VertexBuffer.UVKind);
  6513. defines.push("#define UV1");
  6514. }
  6515. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6516. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6517. defines.push("#define UV2");
  6518. }
  6519. }
  6520. // Bones
  6521. if (mesh.useBones) {
  6522. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6523. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6524. defines.push("#define BONES");
  6525. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6526. }
  6527. // Instances
  6528. if (useInstances) {
  6529. defines.push("#define INSTANCES");
  6530. attribs.push("world0");
  6531. attribs.push("world1");
  6532. attribs.push("world2");
  6533. attribs.push("world3");
  6534. }
  6535. // Get correct effect
  6536. var join = defines.join("\n");
  6537. if (this._cachedDefines !== join) {
  6538. this._cachedDefines = join;
  6539. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6540. }
  6541. return this._effect.isReady();
  6542. };
  6543. ShadowGenerator.prototype.getShadowMap = function () {
  6544. return this._shadowMap;
  6545. };
  6546. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6547. if (this._shadowMap2) {
  6548. return this._shadowMap2;
  6549. }
  6550. return this._shadowMap;
  6551. };
  6552. ShadowGenerator.prototype.getLight = function () {
  6553. return this._light;
  6554. };
  6555. // Methods
  6556. ShadowGenerator.prototype.getTransformMatrix = function () {
  6557. var scene = this._scene;
  6558. if (this._currentRenderID === scene.getRenderId()) {
  6559. return this._transformMatrix;
  6560. }
  6561. this._currentRenderID = scene.getRenderId();
  6562. var lightPosition = this._light.position;
  6563. var lightDirection = this._light.direction;
  6564. if (this._light.computeTransformedPosition()) {
  6565. lightPosition = this._light.transformedPosition;
  6566. }
  6567. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6568. this._cachedPosition = lightPosition.clone();
  6569. this._cachedDirection = lightDirection.clone();
  6570. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6571. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6572. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6573. }
  6574. return this._transformMatrix;
  6575. };
  6576. ShadowGenerator.prototype.getDarkness = function () {
  6577. return this._darkness;
  6578. };
  6579. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6580. if (darkness >= 1.0)
  6581. this._darkness = 1.0;
  6582. else if (darkness <= 0.0)
  6583. this._darkness = 0.0;
  6584. else
  6585. this._darkness = darkness;
  6586. };
  6587. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6588. this._transparencyShadow = hasShadow;
  6589. };
  6590. ShadowGenerator.prototype._packHalf = function (depth) {
  6591. var scale = depth * 255.0;
  6592. var fract = scale - Math.floor(scale);
  6593. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6594. };
  6595. ShadowGenerator.prototype.dispose = function () {
  6596. this._shadowMap.dispose();
  6597. if (this._shadowMap2) {
  6598. this._shadowMap2.dispose();
  6599. }
  6600. if (this._downSamplePostprocess) {
  6601. this._downSamplePostprocess.dispose();
  6602. }
  6603. if (this._boxBlurPostprocess) {
  6604. this._boxBlurPostprocess.dispose();
  6605. }
  6606. };
  6607. ShadowGenerator._FILTER_NONE = 0;
  6608. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6609. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6610. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6611. return ShadowGenerator;
  6612. })();
  6613. BABYLON.ShadowGenerator = ShadowGenerator;
  6614. })(BABYLON || (BABYLON = {}));
  6615. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6616. var BABYLON;
  6617. (function (BABYLON) {
  6618. var HemisphericLight = (function (_super) {
  6619. __extends(HemisphericLight, _super);
  6620. function HemisphericLight(name, direction, scene) {
  6621. _super.call(this, name, scene);
  6622. this.direction = direction;
  6623. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6624. }
  6625. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6626. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6627. return this.direction;
  6628. };
  6629. HemisphericLight.prototype.getShadowGenerator = function () {
  6630. return null;
  6631. };
  6632. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6633. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6634. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6635. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6636. };
  6637. HemisphericLight.prototype._getWorldMatrix = function () {
  6638. if (!this._worldMatrix) {
  6639. this._worldMatrix = BABYLON.Matrix.Identity();
  6640. }
  6641. return this._worldMatrix;
  6642. };
  6643. return HemisphericLight;
  6644. })(BABYLON.Light);
  6645. BABYLON.HemisphericLight = HemisphericLight;
  6646. })(BABYLON || (BABYLON = {}));
  6647. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6648. (function (BABYLON) {
  6649. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6650. if (boxMin.x > sphereCenter.x + sphereRadius)
  6651. return false;
  6652. if (sphereCenter.x - sphereRadius > boxMax.x)
  6653. return false;
  6654. if (boxMin.y > sphereCenter.y + sphereRadius)
  6655. return false;
  6656. if (sphereCenter.y - sphereRadius > boxMax.y)
  6657. return false;
  6658. if (boxMin.z > sphereCenter.z + sphereRadius)
  6659. return false;
  6660. if (sphereCenter.z - sphereRadius > boxMax.z)
  6661. return false;
  6662. return true;
  6663. };
  6664. var getLowestRoot = function (a, b, c, maxR) {
  6665. var determinant = b * b - 4.0 * a * c;
  6666. var result = { root: 0, found: false };
  6667. if (determinant < 0)
  6668. return result;
  6669. var sqrtD = Math.sqrt(determinant);
  6670. var r1 = (-b - sqrtD) / (2.0 * a);
  6671. var r2 = (-b + sqrtD) / (2.0 * a);
  6672. if (r1 > r2) {
  6673. var temp = r2;
  6674. r2 = r1;
  6675. r1 = temp;
  6676. }
  6677. if (r1 > 0 && r1 < maxR) {
  6678. result.root = r1;
  6679. result.found = true;
  6680. return result;
  6681. }
  6682. if (r2 > 0 && r2 < maxR) {
  6683. result.root = r2;
  6684. result.found = true;
  6685. return result;
  6686. }
  6687. return result;
  6688. };
  6689. var Collider = (function () {
  6690. function Collider() {
  6691. this.radius = new BABYLON.Vector3(1, 1, 1);
  6692. this.retry = 0;
  6693. this.basePointWorld = BABYLON.Vector3.Zero();
  6694. this.velocityWorld = BABYLON.Vector3.Zero();
  6695. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6696. this._collisionPoint = BABYLON.Vector3.Zero();
  6697. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6698. this._tempVector = BABYLON.Vector3.Zero();
  6699. this._tempVector2 = BABYLON.Vector3.Zero();
  6700. this._tempVector3 = BABYLON.Vector3.Zero();
  6701. this._tempVector4 = BABYLON.Vector3.Zero();
  6702. this._edge = BABYLON.Vector3.Zero();
  6703. this._baseToVertex = BABYLON.Vector3.Zero();
  6704. this._destinationPoint = BABYLON.Vector3.Zero();
  6705. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6706. this._displacementVector = BABYLON.Vector3.Zero();
  6707. }
  6708. // Methods
  6709. Collider.prototype._initialize = function (source, dir, e) {
  6710. this.velocity = dir;
  6711. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6712. this.basePoint = source;
  6713. source.multiplyToRef(this.radius, this.basePointWorld);
  6714. dir.multiplyToRef(this.radius, this.velocityWorld);
  6715. this.velocityWorldLength = this.velocityWorld.length();
  6716. this.epsilon = e;
  6717. this.collisionFound = false;
  6718. };
  6719. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6720. pa.subtractToRef(point, this._tempVector);
  6721. pb.subtractToRef(point, this._tempVector2);
  6722. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6723. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6724. if (d < 0)
  6725. return false;
  6726. pc.subtractToRef(point, this._tempVector3);
  6727. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6728. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6729. if (d < 0)
  6730. return false;
  6731. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6732. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6733. return d >= 0;
  6734. };
  6735. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6736. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6737. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6738. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6739. return false;
  6740. }
  6741. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6742. return false;
  6743. return true;
  6744. };
  6745. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6746. var t0;
  6747. var embeddedInPlane = false;
  6748. if (!subMesh._trianglePlanes) {
  6749. subMesh._trianglePlanes = [];
  6750. }
  6751. if (!subMesh._trianglePlanes[faceIndex]) {
  6752. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6753. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6754. }
  6755. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6756. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6757. return;
  6758. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6759. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6760. if (normalDotVelocity == 0) {
  6761. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6762. return;
  6763. embeddedInPlane = true;
  6764. t0 = 0;
  6765. }
  6766. else {
  6767. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6768. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6769. if (t0 > t1) {
  6770. var temp = t1;
  6771. t1 = t0;
  6772. t0 = temp;
  6773. }
  6774. if (t0 > 1.0 || t1 < 0.0)
  6775. return;
  6776. if (t0 < 0)
  6777. t0 = 0;
  6778. if (t0 > 1.0)
  6779. t0 = 1.0;
  6780. }
  6781. this._collisionPoint.copyFromFloats(0, 0, 0);
  6782. var found = false;
  6783. var t = 1.0;
  6784. if (!embeddedInPlane) {
  6785. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6786. this.velocity.scaleToRef(t0, this._tempVector);
  6787. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6788. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6789. found = true;
  6790. t = t0;
  6791. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6792. }
  6793. }
  6794. if (!found) {
  6795. var velocitySquaredLength = this.velocity.lengthSquared();
  6796. var a = velocitySquaredLength;
  6797. this.basePoint.subtractToRef(p1, this._tempVector);
  6798. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6799. var c = this._tempVector.lengthSquared() - 1.0;
  6800. var lowestRoot = getLowestRoot(a, b, c, t);
  6801. if (lowestRoot.found) {
  6802. t = lowestRoot.root;
  6803. found = true;
  6804. this._collisionPoint.copyFrom(p1);
  6805. }
  6806. this.basePoint.subtractToRef(p2, this._tempVector);
  6807. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6808. c = this._tempVector.lengthSquared() - 1.0;
  6809. lowestRoot = getLowestRoot(a, b, c, t);
  6810. if (lowestRoot.found) {
  6811. t = lowestRoot.root;
  6812. found = true;
  6813. this._collisionPoint.copyFrom(p2);
  6814. }
  6815. this.basePoint.subtractToRef(p3, this._tempVector);
  6816. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6817. c = this._tempVector.lengthSquared() - 1.0;
  6818. lowestRoot = getLowestRoot(a, b, c, t);
  6819. if (lowestRoot.found) {
  6820. t = lowestRoot.root;
  6821. found = true;
  6822. this._collisionPoint.copyFrom(p3);
  6823. }
  6824. p2.subtractToRef(p1, this._edge);
  6825. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6826. var edgeSquaredLength = this._edge.lengthSquared();
  6827. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6828. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6829. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6830. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6831. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6832. lowestRoot = getLowestRoot(a, b, c, t);
  6833. if (lowestRoot.found) {
  6834. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6835. if (f >= 0.0 && f <= 1.0) {
  6836. t = lowestRoot.root;
  6837. found = true;
  6838. this._edge.scaleInPlace(f);
  6839. p1.addToRef(this._edge, this._collisionPoint);
  6840. }
  6841. }
  6842. p3.subtractToRef(p2, this._edge);
  6843. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6844. edgeSquaredLength = this._edge.lengthSquared();
  6845. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6846. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6847. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6848. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6849. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6850. lowestRoot = getLowestRoot(a, b, c, t);
  6851. if (lowestRoot.found) {
  6852. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6853. if (f >= 0.0 && f <= 1.0) {
  6854. t = lowestRoot.root;
  6855. found = true;
  6856. this._edge.scaleInPlace(f);
  6857. p2.addToRef(this._edge, this._collisionPoint);
  6858. }
  6859. }
  6860. p1.subtractToRef(p3, this._edge);
  6861. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6862. edgeSquaredLength = this._edge.lengthSquared();
  6863. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6864. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6865. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6866. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6867. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6868. lowestRoot = getLowestRoot(a, b, c, t);
  6869. if (lowestRoot.found) {
  6870. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6871. if (f >= 0.0 && f <= 1.0) {
  6872. t = lowestRoot.root;
  6873. found = true;
  6874. this._edge.scaleInPlace(f);
  6875. p3.addToRef(this._edge, this._collisionPoint);
  6876. }
  6877. }
  6878. }
  6879. if (found) {
  6880. var distToCollision = t * this.velocity.length();
  6881. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6882. if (!this.intersectionPoint) {
  6883. this.intersectionPoint = this._collisionPoint.clone();
  6884. }
  6885. else {
  6886. this.intersectionPoint.copyFrom(this._collisionPoint);
  6887. }
  6888. this.nearestDistance = distToCollision;
  6889. this.collisionFound = true;
  6890. this.collidedMesh = subMesh.getMesh();
  6891. }
  6892. }
  6893. };
  6894. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6895. for (var i = indexStart; i < indexEnd; i += 3) {
  6896. var p1 = pts[indices[i] - decal];
  6897. var p2 = pts[indices[i + 1] - decal];
  6898. var p3 = pts[indices[i + 2] - decal];
  6899. this._testTriangle(i, subMesh, p3, p2, p1);
  6900. }
  6901. };
  6902. Collider.prototype._getResponse = function (pos, vel) {
  6903. pos.addToRef(vel, this._destinationPoint);
  6904. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6905. this.basePoint.addToRef(vel, pos);
  6906. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6907. this._slidePlaneNormal.normalize();
  6908. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6909. pos.addInPlace(this._displacementVector);
  6910. this.intersectionPoint.addInPlace(this._displacementVector);
  6911. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6912. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6913. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6914. };
  6915. return Collider;
  6916. })();
  6917. BABYLON.Collider = Collider;
  6918. })(BABYLON || (BABYLON = {}));
  6919. //# sourceMappingURL=babylon.collider.js.map
  6920. var BABYLON;
  6921. (function (BABYLON) {
  6922. var Camera = (function (_super) {
  6923. __extends(Camera, _super);
  6924. function Camera(name, position, scene) {
  6925. _super.call(this, name, scene);
  6926. this.position = position;
  6927. // Members
  6928. this.upVector = BABYLON.Vector3.Up();
  6929. this.orthoLeft = null;
  6930. this.orthoRight = null;
  6931. this.orthoBottom = null;
  6932. this.orthoTop = null;
  6933. this.fov = 0.8;
  6934. this.minZ = 1.0;
  6935. this.maxZ = 10000.0;
  6936. this.inertia = 0.9;
  6937. this.mode = Camera.PERSPECTIVE_CAMERA;
  6938. this.isIntermediate = false;
  6939. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6940. this.subCameras = [];
  6941. this.layerMask = 0xFFFFFFFF;
  6942. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6943. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6944. this._projectionMatrix = new BABYLON.Matrix();
  6945. this._postProcesses = new Array();
  6946. this._postProcessesTakenIndices = [];
  6947. this._activeMeshes = new BABYLON.SmartArray(256);
  6948. this._globalPosition = BABYLON.Vector3.Zero();
  6949. scene.addCamera(this);
  6950. if (!scene.activeCamera) {
  6951. scene.activeCamera = this;
  6952. }
  6953. }
  6954. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6955. get: function () {
  6956. return Camera._PERSPECTIVE_CAMERA;
  6957. },
  6958. enumerable: true,
  6959. configurable: true
  6960. });
  6961. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6962. get: function () {
  6963. return Camera._ORTHOGRAPHIC_CAMERA;
  6964. },
  6965. enumerable: true,
  6966. configurable: true
  6967. });
  6968. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6969. get: function () {
  6970. return Camera._FOVMODE_VERTICAL_FIXED;
  6971. },
  6972. enumerable: true,
  6973. configurable: true
  6974. });
  6975. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6976. get: function () {
  6977. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6978. },
  6979. enumerable: true,
  6980. configurable: true
  6981. });
  6982. Object.defineProperty(Camera.prototype, "globalPosition", {
  6983. get: function () {
  6984. return this._globalPosition;
  6985. },
  6986. enumerable: true,
  6987. configurable: true
  6988. });
  6989. Camera.prototype.getActiveMeshes = function () {
  6990. return this._activeMeshes;
  6991. };
  6992. Camera.prototype.isActiveMesh = function (mesh) {
  6993. return (this._activeMeshes.indexOf(mesh) !== -1);
  6994. };
  6995. //Cache
  6996. Camera.prototype._initCache = function () {
  6997. _super.prototype._initCache.call(this);
  6998. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6999. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7000. this._cache.mode = undefined;
  7001. this._cache.minZ = undefined;
  7002. this._cache.maxZ = undefined;
  7003. this._cache.fov = undefined;
  7004. this._cache.aspectRatio = undefined;
  7005. this._cache.orthoLeft = undefined;
  7006. this._cache.orthoRight = undefined;
  7007. this._cache.orthoBottom = undefined;
  7008. this._cache.orthoTop = undefined;
  7009. this._cache.renderWidth = undefined;
  7010. this._cache.renderHeight = undefined;
  7011. };
  7012. Camera.prototype._updateCache = function (ignoreParentClass) {
  7013. if (!ignoreParentClass) {
  7014. _super.prototype._updateCache.call(this);
  7015. }
  7016. var engine = this.getEngine();
  7017. this._cache.position.copyFrom(this.position);
  7018. this._cache.upVector.copyFrom(this.upVector);
  7019. this._cache.mode = this.mode;
  7020. this._cache.minZ = this.minZ;
  7021. this._cache.maxZ = this.maxZ;
  7022. this._cache.fov = this.fov;
  7023. this._cache.aspectRatio = engine.getAspectRatio(this);
  7024. this._cache.orthoLeft = this.orthoLeft;
  7025. this._cache.orthoRight = this.orthoRight;
  7026. this._cache.orthoBottom = this.orthoBottom;
  7027. this._cache.orthoTop = this.orthoTop;
  7028. this._cache.renderWidth = engine.getRenderWidth();
  7029. this._cache.renderHeight = engine.getRenderHeight();
  7030. };
  7031. Camera.prototype._updateFromScene = function () {
  7032. this.updateCache();
  7033. this._update();
  7034. };
  7035. // Synchronized
  7036. Camera.prototype._isSynchronized = function () {
  7037. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  7038. };
  7039. Camera.prototype._isSynchronizedViewMatrix = function () {
  7040. if (!_super.prototype._isSynchronized.call(this))
  7041. return false;
  7042. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  7043. };
  7044. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  7045. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  7046. if (!check) {
  7047. return false;
  7048. }
  7049. var engine = this.getEngine();
  7050. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7051. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  7052. }
  7053. else {
  7054. 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();
  7055. }
  7056. return check;
  7057. };
  7058. // Controls
  7059. Camera.prototype.attachControl = function (element) {
  7060. };
  7061. Camera.prototype.detachControl = function (element) {
  7062. };
  7063. Camera.prototype._update = function () {
  7064. };
  7065. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  7066. if (insertAt === void 0) { insertAt = null; }
  7067. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  7068. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  7069. return 0;
  7070. }
  7071. if (insertAt == null || insertAt < 0) {
  7072. this._postProcesses.push(postProcess);
  7073. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  7074. return this._postProcesses.length - 1;
  7075. }
  7076. var add = 0;
  7077. if (this._postProcesses[insertAt]) {
  7078. var start = this._postProcesses.length - 1;
  7079. for (var i = start; i >= insertAt + 1; --i) {
  7080. this._postProcesses[i + 1] = this._postProcesses[i];
  7081. }
  7082. add = 1;
  7083. }
  7084. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7085. if (this._postProcessesTakenIndices[i] < insertAt) {
  7086. continue;
  7087. }
  7088. start = this._postProcessesTakenIndices.length - 1;
  7089. for (var j = start; j >= i; --j) {
  7090. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  7091. }
  7092. this._postProcessesTakenIndices[i] = insertAt;
  7093. break;
  7094. }
  7095. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  7096. this._postProcessesTakenIndices.push(insertAt);
  7097. }
  7098. var result = insertAt + add;
  7099. this._postProcesses[result] = postProcess;
  7100. return result;
  7101. };
  7102. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  7103. if (atIndices === void 0) { atIndices = null; }
  7104. var result = [];
  7105. if (!atIndices) {
  7106. var length = this._postProcesses.length;
  7107. for (var i = 0; i < length; i++) {
  7108. if (this._postProcesses[i] !== postProcess) {
  7109. continue;
  7110. }
  7111. delete this._postProcesses[i];
  7112. var index = this._postProcessesTakenIndices.indexOf(i);
  7113. this._postProcessesTakenIndices.splice(index, 1);
  7114. }
  7115. }
  7116. else {
  7117. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  7118. for (i = 0; i < atIndices.length; i++) {
  7119. var foundPostProcess = this._postProcesses[atIndices[i]];
  7120. if (foundPostProcess !== postProcess) {
  7121. result.push(i);
  7122. continue;
  7123. }
  7124. delete this._postProcesses[atIndices[i]];
  7125. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  7126. this._postProcessesTakenIndices.splice(index, 1);
  7127. }
  7128. }
  7129. return result;
  7130. };
  7131. Camera.prototype.getWorldMatrix = function () {
  7132. if (!this._worldMatrix) {
  7133. this._worldMatrix = BABYLON.Matrix.Identity();
  7134. }
  7135. var viewMatrix = this.getViewMatrix();
  7136. viewMatrix.invertToRef(this._worldMatrix);
  7137. return this._worldMatrix;
  7138. };
  7139. Camera.prototype._getViewMatrix = function () {
  7140. return BABYLON.Matrix.Identity();
  7141. };
  7142. Camera.prototype.getViewMatrix = function (force) {
  7143. this._computedViewMatrix = this._computeViewMatrix(force);
  7144. if (!force && this._isSynchronizedViewMatrix()) {
  7145. return this._computedViewMatrix;
  7146. }
  7147. if (!this.parent || !this.parent.getWorldMatrix) {
  7148. this._globalPosition.copyFrom(this.position);
  7149. }
  7150. else {
  7151. if (!this._worldMatrix) {
  7152. this._worldMatrix = BABYLON.Matrix.Identity();
  7153. }
  7154. this._computedViewMatrix.invertToRef(this._worldMatrix);
  7155. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  7156. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  7157. this._computedViewMatrix.invert();
  7158. this._markSyncedWithParent();
  7159. }
  7160. this._currentRenderId = this.getScene().getRenderId();
  7161. return this._computedViewMatrix;
  7162. };
  7163. Camera.prototype._computeViewMatrix = function (force) {
  7164. if (!force && this._isSynchronizedViewMatrix()) {
  7165. return this._computedViewMatrix;
  7166. }
  7167. this._computedViewMatrix = this._getViewMatrix();
  7168. this._currentRenderId = this.getScene().getRenderId();
  7169. return this._computedViewMatrix;
  7170. };
  7171. Camera.prototype.getProjectionMatrix = function (force) {
  7172. if (!force && this._isSynchronizedProjectionMatrix()) {
  7173. return this._projectionMatrix;
  7174. }
  7175. var engine = this.getEngine();
  7176. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7177. if (this.minZ <= 0) {
  7178. this.minZ = 0.1;
  7179. }
  7180. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  7181. return this._projectionMatrix;
  7182. }
  7183. var halfWidth = engine.getRenderWidth() / 2.0;
  7184. var halfHeight = engine.getRenderHeight() / 2.0;
  7185. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  7186. return this._projectionMatrix;
  7187. };
  7188. Camera.prototype.dispose = function () {
  7189. // Remove from scene
  7190. this.getScene().removeCamera(this);
  7191. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7192. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  7193. }
  7194. };
  7195. // Statics
  7196. Camera._PERSPECTIVE_CAMERA = 0;
  7197. Camera._ORTHOGRAPHIC_CAMERA = 1;
  7198. Camera._FOVMODE_VERTICAL_FIXED = 0;
  7199. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  7200. return Camera;
  7201. })(BABYLON.Node);
  7202. BABYLON.Camera = Camera;
  7203. })(BABYLON || (BABYLON = {}));
  7204. //# sourceMappingURL=babylon.camera.js.map
  7205. var BABYLON;
  7206. (function (BABYLON) {
  7207. var TargetCamera = (function (_super) {
  7208. __extends(TargetCamera, _super);
  7209. function TargetCamera(name, position, scene) {
  7210. _super.call(this, name, position, scene);
  7211. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7212. this.cameraRotation = new BABYLON.Vector2(0, 0);
  7213. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7214. this.speed = 2.0;
  7215. this.noRotationConstraint = false;
  7216. this.lockedTarget = null;
  7217. this._currentTarget = BABYLON.Vector3.Zero();
  7218. this._viewMatrix = BABYLON.Matrix.Zero();
  7219. this._camMatrix = BABYLON.Matrix.Zero();
  7220. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  7221. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  7222. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  7223. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  7224. this._lookAtTemp = BABYLON.Matrix.Zero();
  7225. this._tempMatrix = BABYLON.Matrix.Zero();
  7226. }
  7227. TargetCamera.prototype._getLockedTargetPosition = function () {
  7228. if (!this.lockedTarget) {
  7229. return null;
  7230. }
  7231. return this.lockedTarget.position || this.lockedTarget;
  7232. };
  7233. // Cache
  7234. TargetCamera.prototype._initCache = function () {
  7235. _super.prototype._initCache.call(this);
  7236. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7237. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7238. };
  7239. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  7240. if (!ignoreParentClass) {
  7241. _super.prototype._updateCache.call(this);
  7242. }
  7243. var lockedTargetPosition = this._getLockedTargetPosition();
  7244. if (!lockedTargetPosition) {
  7245. this._cache.lockedTarget = null;
  7246. }
  7247. else {
  7248. if (!this._cache.lockedTarget) {
  7249. this._cache.lockedTarget = lockedTargetPosition.clone();
  7250. }
  7251. else {
  7252. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  7253. }
  7254. }
  7255. this._cache.rotation.copyFrom(this.rotation);
  7256. };
  7257. // Synchronized
  7258. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  7259. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  7260. return false;
  7261. }
  7262. var lockedTargetPosition = this._getLockedTargetPosition();
  7263. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  7264. };
  7265. // Methods
  7266. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  7267. var engine = this.getEngine();
  7268. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  7269. };
  7270. // Target
  7271. TargetCamera.prototype.setTarget = function (target) {
  7272. this.upVector.normalize();
  7273. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  7274. this._camMatrix.invert();
  7275. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  7276. var vDir = target.subtract(this.position);
  7277. if (vDir.x >= 0.0) {
  7278. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  7279. }
  7280. else {
  7281. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  7282. }
  7283. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  7284. if (isNaN(this.rotation.x)) {
  7285. this.rotation.x = 0;
  7286. }
  7287. if (isNaN(this.rotation.y)) {
  7288. this.rotation.y = 0;
  7289. }
  7290. if (isNaN(this.rotation.z)) {
  7291. this.rotation.z = 0;
  7292. }
  7293. };
  7294. TargetCamera.prototype.getTarget = function () {
  7295. return this._currentTarget;
  7296. };
  7297. TargetCamera.prototype._decideIfNeedsToMove = function () {
  7298. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7299. };
  7300. TargetCamera.prototype._updatePosition = function () {
  7301. this.position.addInPlace(this.cameraDirection);
  7302. };
  7303. TargetCamera.prototype._update = function () {
  7304. var needToMove = this._decideIfNeedsToMove();
  7305. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  7306. // Move
  7307. if (needToMove) {
  7308. this._updatePosition();
  7309. }
  7310. // Rotate
  7311. if (needToRotate) {
  7312. this.rotation.x += this.cameraRotation.x;
  7313. this.rotation.y += this.cameraRotation.y;
  7314. if (!this.noRotationConstraint) {
  7315. var limit = (Math.PI / 2) * 0.95;
  7316. if (this.rotation.x > limit)
  7317. this.rotation.x = limit;
  7318. if (this.rotation.x < -limit)
  7319. this.rotation.x = -limit;
  7320. }
  7321. }
  7322. // Inertia
  7323. if (needToMove) {
  7324. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  7325. this.cameraDirection.x = 0;
  7326. }
  7327. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  7328. this.cameraDirection.y = 0;
  7329. }
  7330. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  7331. this.cameraDirection.z = 0;
  7332. }
  7333. this.cameraDirection.scaleInPlace(this.inertia);
  7334. }
  7335. if (needToRotate) {
  7336. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  7337. this.cameraRotation.x = 0;
  7338. }
  7339. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  7340. this.cameraRotation.y = 0;
  7341. }
  7342. this.cameraRotation.scaleInPlace(this.inertia);
  7343. }
  7344. };
  7345. TargetCamera.prototype._getViewMatrix = function () {
  7346. if (!this.lockedTarget) {
  7347. // Compute
  7348. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  7349. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  7350. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7351. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  7352. this._lookAtTemp.invert();
  7353. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  7354. }
  7355. else {
  7356. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7357. }
  7358. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  7359. // Computing target and final matrix
  7360. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  7361. }
  7362. else {
  7363. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  7364. }
  7365. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  7366. return this._viewMatrix;
  7367. };
  7368. return TargetCamera;
  7369. })(BABYLON.Camera);
  7370. BABYLON.TargetCamera = TargetCamera;
  7371. })(BABYLON || (BABYLON = {}));
  7372. //# sourceMappingURL=babylon.targetCamera.js.map
  7373. var BABYLON;
  7374. (function (BABYLON) {
  7375. var FollowCamera = (function (_super) {
  7376. __extends(FollowCamera, _super);
  7377. function FollowCamera(name, position, scene) {
  7378. _super.call(this, name, position, scene);
  7379. this.radius = 12;
  7380. this.rotationOffset = 0;
  7381. this.heightOffset = 4;
  7382. this.cameraAcceleration = 0.05;
  7383. this.maxCameraSpeed = 20;
  7384. }
  7385. FollowCamera.prototype.getRadians = function (degrees) {
  7386. return degrees * Math.PI / 180;
  7387. };
  7388. FollowCamera.prototype.follow = function (cameraTarget) {
  7389. if (!cameraTarget)
  7390. return;
  7391. var yRotation;
  7392. if (cameraTarget.rotationQuaternion) {
  7393. var rotMatrix = new BABYLON.Matrix();
  7394. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  7395. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  7396. }
  7397. else {
  7398. yRotation = cameraTarget.rotation.y;
  7399. }
  7400. var radians = this.getRadians(this.rotationOffset) + yRotation;
  7401. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  7402. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  7403. var dx = targetX - this.position.x;
  7404. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  7405. var dz = (targetZ) - this.position.z;
  7406. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  7407. var vy = dy * this.cameraAcceleration;
  7408. var vz = dz * this.cameraAcceleration * 2;
  7409. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  7410. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7411. }
  7412. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  7413. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7414. }
  7415. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  7416. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7417. }
  7418. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  7419. this.setTarget(cameraTarget.position);
  7420. };
  7421. FollowCamera.prototype._update = function () {
  7422. _super.prototype._update.call(this);
  7423. this.follow(this.target);
  7424. };
  7425. return FollowCamera;
  7426. })(BABYLON.TargetCamera);
  7427. BABYLON.FollowCamera = FollowCamera;
  7428. })(BABYLON || (BABYLON = {}));
  7429. //# sourceMappingURL=babylon.followCamera.js.map
  7430. var BABYLON;
  7431. (function (BABYLON) {
  7432. var FreeCamera = (function (_super) {
  7433. __extends(FreeCamera, _super);
  7434. function FreeCamera(name, position, scene) {
  7435. _super.call(this, name, position, scene);
  7436. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7437. this.keysUp = [38];
  7438. this.keysDown = [40];
  7439. this.keysLeft = [37];
  7440. this.keysRight = [39];
  7441. this.checkCollisions = false;
  7442. this.applyGravity = false;
  7443. this.angularSensibility = 2000.0;
  7444. this._keys = [];
  7445. this._collider = new BABYLON.Collider();
  7446. this._needMoveForGravity = true;
  7447. this._oldPosition = BABYLON.Vector3.Zero();
  7448. this._diffPosition = BABYLON.Vector3.Zero();
  7449. this._newPosition = BABYLON.Vector3.Zero();
  7450. }
  7451. // Controls
  7452. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7453. var _this = this;
  7454. var previousPosition;
  7455. var engine = this.getEngine();
  7456. if (this._attachedElement) {
  7457. return;
  7458. }
  7459. this._attachedElement = element;
  7460. if (this._onMouseDown === undefined) {
  7461. this._onMouseDown = function (evt) {
  7462. previousPosition = {
  7463. x: evt.clientX,
  7464. y: evt.clientY
  7465. };
  7466. if (!noPreventDefault) {
  7467. evt.preventDefault();
  7468. }
  7469. };
  7470. this._onMouseUp = function (evt) {
  7471. previousPosition = null;
  7472. if (!noPreventDefault) {
  7473. evt.preventDefault();
  7474. }
  7475. };
  7476. this._onMouseOut = function (evt) {
  7477. previousPosition = null;
  7478. _this._keys = [];
  7479. if (!noPreventDefault) {
  7480. evt.preventDefault();
  7481. }
  7482. };
  7483. this._onMouseMove = function (evt) {
  7484. if (!previousPosition && !engine.isPointerLock) {
  7485. return;
  7486. }
  7487. var offsetX;
  7488. var offsetY;
  7489. if (!engine.isPointerLock) {
  7490. offsetX = evt.clientX - previousPosition.x;
  7491. offsetY = evt.clientY - previousPosition.y;
  7492. }
  7493. else {
  7494. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7495. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7496. }
  7497. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7498. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7499. previousPosition = {
  7500. x: evt.clientX,
  7501. y: evt.clientY
  7502. };
  7503. if (!noPreventDefault) {
  7504. evt.preventDefault();
  7505. }
  7506. };
  7507. this._onKeyDown = function (evt) {
  7508. 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) {
  7509. var index = _this._keys.indexOf(evt.keyCode);
  7510. if (index === -1) {
  7511. _this._keys.push(evt.keyCode);
  7512. }
  7513. if (!noPreventDefault) {
  7514. evt.preventDefault();
  7515. }
  7516. }
  7517. };
  7518. this._onKeyUp = function (evt) {
  7519. 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) {
  7520. var index = _this._keys.indexOf(evt.keyCode);
  7521. if (index >= 0) {
  7522. _this._keys.splice(index, 1);
  7523. }
  7524. if (!noPreventDefault) {
  7525. evt.preventDefault();
  7526. }
  7527. }
  7528. };
  7529. this._onLostFocus = function () {
  7530. _this._keys = [];
  7531. };
  7532. this._reset = function () {
  7533. _this._keys = [];
  7534. previousPosition = null;
  7535. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7536. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7537. };
  7538. }
  7539. element.addEventListener("mousedown", this._onMouseDown, false);
  7540. element.addEventListener("mouseup", this._onMouseUp, false);
  7541. element.addEventListener("mouseout", this._onMouseOut, false);
  7542. element.addEventListener("mousemove", this._onMouseMove, false);
  7543. BABYLON.Tools.RegisterTopRootEvents([
  7544. { name: "keydown", handler: this._onKeyDown },
  7545. { name: "keyup", handler: this._onKeyUp },
  7546. { name: "blur", handler: this._onLostFocus }
  7547. ]);
  7548. };
  7549. FreeCamera.prototype.detachControl = function (element) {
  7550. if (this._attachedElement != element) {
  7551. return;
  7552. }
  7553. element.removeEventListener("mousedown", this._onMouseDown);
  7554. element.removeEventListener("mouseup", this._onMouseUp);
  7555. element.removeEventListener("mouseout", this._onMouseOut);
  7556. element.removeEventListener("mousemove", this._onMouseMove);
  7557. BABYLON.Tools.UnregisterTopRootEvents([
  7558. { name: "keydown", handler: this._onKeyDown },
  7559. { name: "keyup", handler: this._onKeyUp },
  7560. { name: "blur", handler: this._onLostFocus }
  7561. ]);
  7562. this._attachedElement = null;
  7563. if (this._reset) {
  7564. this._reset();
  7565. }
  7566. };
  7567. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7568. var globalPosition;
  7569. if (this.parent) {
  7570. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7571. }
  7572. else {
  7573. globalPosition = this.position;
  7574. }
  7575. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7576. this._collider.radius = this.ellipsoid;
  7577. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7578. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7579. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7580. this.position.addInPlace(this._diffPosition);
  7581. if (this.onCollide) {
  7582. this.onCollide(this._collider.collidedMesh);
  7583. }
  7584. }
  7585. };
  7586. FreeCamera.prototype._checkInputs = function () {
  7587. if (!this._localDirection) {
  7588. this._localDirection = BABYLON.Vector3.Zero();
  7589. this._transformedDirection = BABYLON.Vector3.Zero();
  7590. }
  7591. for (var index = 0; index < this._keys.length; index++) {
  7592. var keyCode = this._keys[index];
  7593. var speed = this._computeLocalCameraSpeed();
  7594. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7595. this._localDirection.copyFromFloats(-speed, 0, 0);
  7596. }
  7597. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7598. this._localDirection.copyFromFloats(0, 0, speed);
  7599. }
  7600. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7601. this._localDirection.copyFromFloats(speed, 0, 0);
  7602. }
  7603. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7604. this._localDirection.copyFromFloats(0, 0, -speed);
  7605. }
  7606. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7607. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7608. this.cameraDirection.addInPlace(this._transformedDirection);
  7609. }
  7610. };
  7611. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7612. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7613. };
  7614. FreeCamera.prototype._updatePosition = function () {
  7615. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7616. this._collideWithWorld(this.cameraDirection);
  7617. if (this.applyGravity) {
  7618. var oldPosition = this.position;
  7619. this._collideWithWorld(this.getScene().gravity);
  7620. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7621. }
  7622. }
  7623. else {
  7624. this.position.addInPlace(this.cameraDirection);
  7625. }
  7626. };
  7627. FreeCamera.prototype._update = function () {
  7628. this._checkInputs();
  7629. _super.prototype._update.call(this);
  7630. };
  7631. return FreeCamera;
  7632. })(BABYLON.TargetCamera);
  7633. BABYLON.FreeCamera = FreeCamera;
  7634. })(BABYLON || (BABYLON = {}));
  7635. //# sourceMappingURL=babylon.freeCamera.js.map
  7636. var BABYLON;
  7637. (function (BABYLON) {
  7638. // We're mainly based on the logic defined into the FreeCamera code
  7639. var TouchCamera = (function (_super) {
  7640. __extends(TouchCamera, _super);
  7641. function TouchCamera(name, position, scene) {
  7642. _super.call(this, name, position, scene);
  7643. this._offsetX = null;
  7644. this._offsetY = null;
  7645. this._pointerCount = 0;
  7646. this._pointerPressed = [];
  7647. this.angularSensibility = 200000.0;
  7648. this.moveSensibility = 500.0;
  7649. }
  7650. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7651. var _this = this;
  7652. var previousPosition;
  7653. if (this._attachedCanvas) {
  7654. return;
  7655. }
  7656. this._attachedCanvas = canvas;
  7657. if (this._onPointerDown === undefined) {
  7658. this._onPointerDown = function (evt) {
  7659. if (!noPreventDefault) {
  7660. evt.preventDefault();
  7661. }
  7662. _this._pointerPressed.push(evt.pointerId);
  7663. if (_this._pointerPressed.length !== 1) {
  7664. return;
  7665. }
  7666. previousPosition = {
  7667. x: evt.clientX,
  7668. y: evt.clientY
  7669. };
  7670. };
  7671. this._onPointerUp = function (evt) {
  7672. if (!noPreventDefault) {
  7673. evt.preventDefault();
  7674. }
  7675. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7676. if (index === -1) {
  7677. return;
  7678. }
  7679. _this._pointerPressed.splice(index, 1);
  7680. if (index != 0) {
  7681. return;
  7682. }
  7683. previousPosition = null;
  7684. _this._offsetX = null;
  7685. _this._offsetY = null;
  7686. };
  7687. this._onPointerMove = function (evt) {
  7688. if (!noPreventDefault) {
  7689. evt.preventDefault();
  7690. }
  7691. if (!previousPosition) {
  7692. return;
  7693. }
  7694. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7695. if (index != 0) {
  7696. return;
  7697. }
  7698. _this._offsetX = evt.clientX - previousPosition.x;
  7699. _this._offsetY = -(evt.clientY - previousPosition.y);
  7700. };
  7701. this._onLostFocus = function () {
  7702. _this._offsetX = null;
  7703. _this._offsetY = null;
  7704. };
  7705. }
  7706. canvas.addEventListener("pointerdown", this._onPointerDown);
  7707. canvas.addEventListener("pointerup", this._onPointerUp);
  7708. canvas.addEventListener("pointerout", this._onPointerUp);
  7709. canvas.addEventListener("pointermove", this._onPointerMove);
  7710. BABYLON.Tools.RegisterTopRootEvents([
  7711. { name: "blur", handler: this._onLostFocus }
  7712. ]);
  7713. };
  7714. TouchCamera.prototype.detachControl = function (canvas) {
  7715. if (this._attachedCanvas != canvas) {
  7716. return;
  7717. }
  7718. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7719. canvas.removeEventListener("pointerup", this._onPointerUp);
  7720. canvas.removeEventListener("pointerout", this._onPointerUp);
  7721. canvas.removeEventListener("pointermove", this._onPointerMove);
  7722. BABYLON.Tools.UnregisterTopRootEvents([
  7723. { name: "blur", handler: this._onLostFocus }
  7724. ]);
  7725. this._attachedCanvas = null;
  7726. };
  7727. TouchCamera.prototype._checkInputs = function () {
  7728. if (!this._offsetX) {
  7729. return;
  7730. }
  7731. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7732. if (this._pointerPressed.length > 1) {
  7733. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7734. }
  7735. else {
  7736. var speed = this._computeLocalCameraSpeed();
  7737. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7738. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7739. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7740. }
  7741. };
  7742. return TouchCamera;
  7743. })(BABYLON.FreeCamera);
  7744. BABYLON.TouchCamera = TouchCamera;
  7745. })(BABYLON || (BABYLON = {}));
  7746. //# sourceMappingURL=babylon.touchCamera.js.map
  7747. var BABYLON;
  7748. (function (BABYLON) {
  7749. // We're mainly based on the logic defined into the FreeCamera code
  7750. var DeviceOrientationCamera = (function (_super) {
  7751. __extends(DeviceOrientationCamera, _super);
  7752. function DeviceOrientationCamera(name, position, scene) {
  7753. var _this = this;
  7754. _super.call(this, name, position, scene);
  7755. this._offsetX = null;
  7756. this._offsetY = null;
  7757. this._orientationGamma = 0;
  7758. this._orientationBeta = 0;
  7759. this._initialOrientationGamma = 0;
  7760. this._initialOrientationBeta = 0;
  7761. this.angularSensibility = 10000.0;
  7762. this.moveSensibility = 50.0;
  7763. window.addEventListener("resize", function () {
  7764. _this._initialOrientationGamma = null;
  7765. }, false);
  7766. }
  7767. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7768. var _this = this;
  7769. if (this._attachedCanvas) {
  7770. return;
  7771. }
  7772. this._attachedCanvas = canvas;
  7773. if (!this._orientationChanged) {
  7774. this._orientationChanged = function (evt) {
  7775. if (!_this._initialOrientationGamma) {
  7776. _this._initialOrientationGamma = evt.gamma;
  7777. _this._initialOrientationBeta = evt.beta;
  7778. }
  7779. _this._orientationGamma = evt.gamma;
  7780. _this._orientationBeta = evt.beta;
  7781. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7782. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7783. };
  7784. }
  7785. window.addEventListener("deviceorientation", this._orientationChanged);
  7786. };
  7787. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7788. if (this._attachedCanvas != canvas) {
  7789. return;
  7790. }
  7791. window.removeEventListener("deviceorientation", this._orientationChanged);
  7792. this._attachedCanvas = null;
  7793. this._orientationGamma = 0;
  7794. this._orientationBeta = 0;
  7795. this._initialOrientationGamma = 0;
  7796. this._initialOrientationBeta = 0;
  7797. };
  7798. DeviceOrientationCamera.prototype._checkInputs = function () {
  7799. if (!this._offsetX) {
  7800. return;
  7801. }
  7802. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7803. var speed = this._computeLocalCameraSpeed();
  7804. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7805. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7806. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7807. };
  7808. return DeviceOrientationCamera;
  7809. })(BABYLON.FreeCamera);
  7810. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7811. })(BABYLON || (BABYLON = {}));
  7812. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7813. var BABYLON;
  7814. (function (BABYLON) {
  7815. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7816. var ArcRotateCamera = (function (_super) {
  7817. __extends(ArcRotateCamera, _super);
  7818. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7819. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7820. this.alpha = alpha;
  7821. this.beta = beta;
  7822. this.radius = radius;
  7823. this.target = target;
  7824. this.inertialAlphaOffset = 0;
  7825. this.inertialBetaOffset = 0;
  7826. this.inertialRadiusOffset = 0;
  7827. this.lowerAlphaLimit = null;
  7828. this.upperAlphaLimit = null;
  7829. this.lowerBetaLimit = 0.01;
  7830. this.upperBetaLimit = Math.PI;
  7831. this.lowerRadiusLimit = null;
  7832. this.upperRadiusLimit = null;
  7833. this.angularSensibility = 1000.0;
  7834. this.wheelPrecision = 3.0;
  7835. this.pinchPrecision = 2.0;
  7836. this.keysUp = [38];
  7837. this.keysDown = [40];
  7838. this.keysLeft = [37];
  7839. this.keysRight = [39];
  7840. this.zoomOnFactor = 1;
  7841. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7842. this._keys = [];
  7843. this._viewMatrix = new BABYLON.Matrix();
  7844. this.checkCollisions = false;
  7845. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7846. this._collider = new BABYLON.Collider();
  7847. this._previousPosition = BABYLON.Vector3.Zero();
  7848. this._collisionVelocity = BABYLON.Vector3.Zero();
  7849. this._newPosition = BABYLON.Vector3.Zero();
  7850. if (!this.target) {
  7851. this.target = BABYLON.Vector3.Zero();
  7852. }
  7853. this.getViewMatrix();
  7854. }
  7855. ArcRotateCamera.prototype._getTargetPosition = function () {
  7856. return this.target.position || this.target;
  7857. };
  7858. // Cache
  7859. ArcRotateCamera.prototype._initCache = function () {
  7860. _super.prototype._initCache.call(this);
  7861. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7862. this._cache.alpha = undefined;
  7863. this._cache.beta = undefined;
  7864. this._cache.radius = undefined;
  7865. this._cache.targetScreenOffset = undefined;
  7866. };
  7867. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7868. if (!ignoreParentClass) {
  7869. _super.prototype._updateCache.call(this);
  7870. }
  7871. this._cache.target.copyFrom(this._getTargetPosition());
  7872. this._cache.alpha = this.alpha;
  7873. this._cache.beta = this.beta;
  7874. this._cache.radius = this.radius;
  7875. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7876. };
  7877. // Synchronized
  7878. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7879. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7880. return false;
  7881. 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);
  7882. };
  7883. // Methods
  7884. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7885. var _this = this;
  7886. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  7887. var previousPinchDistance = 0;
  7888. var pointers = new BABYLON.SmartCollection();
  7889. if (this._attachedElement) {
  7890. return;
  7891. }
  7892. this._attachedElement = element;
  7893. var engine = this.getEngine();
  7894. if (this._onPointerDown === undefined) {
  7895. this._onPointerDown = function (evt) {
  7896. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  7897. cacheSoloPointer = pointers.item(evt.pointerId);
  7898. if (!noPreventDefault) {
  7899. evt.preventDefault();
  7900. }
  7901. };
  7902. this._onPointerUp = function (evt) {
  7903. cacheSoloPointer = null;
  7904. previousPinchDistance = 0;
  7905. pointers.remove(evt.pointerId);
  7906. if (!noPreventDefault) {
  7907. evt.preventDefault();
  7908. }
  7909. };
  7910. this._onPointerMove = function (evt) {
  7911. if (!noPreventDefault) {
  7912. evt.preventDefault();
  7913. }
  7914. switch (pointers.count) {
  7915. case 1:
  7916. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  7917. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  7918. var offsetX = evt.clientX - cacheSoloPointer.x;
  7919. var offsetY = evt.clientY - cacheSoloPointer.y;
  7920. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7921. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7922. //pointers.item(evt.pointerId).x = evt.clientX;
  7923. //pointers.item(evt.pointerId).y = evt.clientY;
  7924. cacheSoloPointer.x = evt.clientX;
  7925. cacheSoloPointer.y = evt.clientY;
  7926. break;
  7927. case 2:
  7928. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  7929. pointers.item(evt.pointerId).x = evt.clientX;
  7930. pointers.item(evt.pointerId).y = evt.clientY;
  7931. var direction = 1;
  7932. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  7933. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  7934. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  7935. if (previousPinchDistance === 0) {
  7936. previousPinchDistance = pinchSquaredDistance;
  7937. return;
  7938. }
  7939. if (pinchSquaredDistance !== previousPinchDistance) {
  7940. if (pinchSquaredDistance > previousPinchDistance) {
  7941. direction = -1;
  7942. }
  7943. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility);
  7944. previousPinchDistance = pinchSquaredDistance;
  7945. }
  7946. break;
  7947. default:
  7948. if (pointers.item(evt.pointerId)) {
  7949. pointers.item(evt.pointerId).x = evt.clientX;
  7950. pointers.item(evt.pointerId).y = evt.clientY;
  7951. }
  7952. }
  7953. };
  7954. this._onMouseMove = function (evt) {
  7955. if (!engine.isPointerLock) {
  7956. return;
  7957. }
  7958. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7959. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7960. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7961. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7962. if (!noPreventDefault) {
  7963. evt.preventDefault();
  7964. }
  7965. };
  7966. this._wheel = function (event) {
  7967. var delta = 0;
  7968. if (event.wheelDelta) {
  7969. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7970. }
  7971. else if (event.detail) {
  7972. delta = -event.detail / _this.wheelPrecision;
  7973. }
  7974. if (delta)
  7975. _this.inertialRadiusOffset += delta;
  7976. if (event.preventDefault) {
  7977. if (!noPreventDefault) {
  7978. event.preventDefault();
  7979. }
  7980. }
  7981. };
  7982. this._onKeyDown = function (evt) {
  7983. 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) {
  7984. var index = _this._keys.indexOf(evt.keyCode);
  7985. if (index === -1) {
  7986. _this._keys.push(evt.keyCode);
  7987. }
  7988. if (evt.preventDefault) {
  7989. if (!noPreventDefault) {
  7990. evt.preventDefault();
  7991. }
  7992. }
  7993. }
  7994. };
  7995. this._onKeyUp = function (evt) {
  7996. 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) {
  7997. var index = _this._keys.indexOf(evt.keyCode);
  7998. if (index >= 0) {
  7999. _this._keys.splice(index, 1);
  8000. }
  8001. if (evt.preventDefault) {
  8002. if (!noPreventDefault) {
  8003. evt.preventDefault();
  8004. }
  8005. }
  8006. }
  8007. };
  8008. this._onLostFocus = function () {
  8009. _this._keys = [];
  8010. pointers.empty();
  8011. previousPinchDistance = 0;
  8012. cacheSoloPointer = null;
  8013. };
  8014. this._onGestureStart = function (e) {
  8015. if (window.MSGesture === undefined) {
  8016. return;
  8017. }
  8018. if (!_this._MSGestureHandler) {
  8019. _this._MSGestureHandler = new MSGesture();
  8020. _this._MSGestureHandler.target = element;
  8021. }
  8022. _this._MSGestureHandler.addPointer(e.pointerId);
  8023. };
  8024. this._onGesture = function (e) {
  8025. _this.radius *= e.scale;
  8026. if (e.preventDefault) {
  8027. if (!noPreventDefault) {
  8028. e.stopPropagation();
  8029. e.preventDefault();
  8030. }
  8031. }
  8032. };
  8033. this._reset = function () {
  8034. _this._keys = [];
  8035. _this.inertialAlphaOffset = 0;
  8036. _this.inertialBetaOffset = 0;
  8037. _this.inertialRadiusOffset = 0;
  8038. pointers.empty();
  8039. previousPinchDistance = 0;
  8040. cacheSoloPointer = null;
  8041. };
  8042. }
  8043. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8044. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  8045. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  8046. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8047. element.addEventListener("mousemove", this._onMouseMove, false);
  8048. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  8049. element.addEventListener("MSGestureChange", this._onGesture, false);
  8050. element.addEventListener('mousewheel', this._wheel, false);
  8051. element.addEventListener('DOMMouseScroll', this._wheel, false);
  8052. BABYLON.Tools.RegisterTopRootEvents([
  8053. { name: "keydown", handler: this._onKeyDown },
  8054. { name: "keyup", handler: this._onKeyUp },
  8055. { name: "blur", handler: this._onLostFocus }
  8056. ]);
  8057. };
  8058. ArcRotateCamera.prototype.detachControl = function (element) {
  8059. if (this._attachedElement !== element) {
  8060. return;
  8061. }
  8062. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  8063. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  8064. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  8065. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  8066. element.removeEventListener("mousemove", this._onMouseMove);
  8067. element.removeEventListener("MSPointerDown", this._onGestureStart);
  8068. element.removeEventListener("MSGestureChange", this._onGesture);
  8069. element.removeEventListener('mousewheel', this._wheel);
  8070. element.removeEventListener('DOMMouseScroll', this._wheel);
  8071. BABYLON.Tools.UnregisterTopRootEvents([
  8072. { name: "keydown", handler: this._onKeyDown },
  8073. { name: "keyup", handler: this._onKeyUp },
  8074. { name: "blur", handler: this._onLostFocus }
  8075. ]);
  8076. this._MSGestureHandler = null;
  8077. this._attachedElement = null;
  8078. if (this._reset) {
  8079. this._reset();
  8080. }
  8081. };
  8082. ArcRotateCamera.prototype._update = function () {
  8083. for (var index = 0; index < this._keys.length; index++) {
  8084. var keyCode = this._keys[index];
  8085. if (this.keysLeft.indexOf(keyCode) !== -1) {
  8086. this.inertialAlphaOffset -= 0.01;
  8087. }
  8088. else if (this.keysUp.indexOf(keyCode) !== -1) {
  8089. this.inertialBetaOffset -= 0.01;
  8090. }
  8091. else if (this.keysRight.indexOf(keyCode) !== -1) {
  8092. this.inertialAlphaOffset += 0.01;
  8093. }
  8094. else if (this.keysDown.indexOf(keyCode) !== -1) {
  8095. this.inertialBetaOffset += 0.01;
  8096. }
  8097. }
  8098. // Inertia
  8099. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  8100. this.alpha += this.inertialAlphaOffset;
  8101. this.beta += this.inertialBetaOffset;
  8102. this.radius -= this.inertialRadiusOffset;
  8103. this.inertialAlphaOffset *= this.inertia;
  8104. this.inertialBetaOffset *= this.inertia;
  8105. this.inertialRadiusOffset *= this.inertia;
  8106. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  8107. this.inertialAlphaOffset = 0;
  8108. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  8109. this.inertialBetaOffset = 0;
  8110. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  8111. this.inertialRadiusOffset = 0;
  8112. }
  8113. // Limits
  8114. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  8115. this.alpha = this.lowerAlphaLimit;
  8116. }
  8117. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  8118. this.alpha = this.upperAlphaLimit;
  8119. }
  8120. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  8121. this.beta = this.lowerBetaLimit;
  8122. }
  8123. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  8124. this.beta = this.upperBetaLimit;
  8125. }
  8126. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  8127. this.radius = this.lowerRadiusLimit;
  8128. }
  8129. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  8130. this.radius = this.upperRadiusLimit;
  8131. }
  8132. };
  8133. ArcRotateCamera.prototype.setPosition = function (position) {
  8134. var radiusv3 = position.subtract(this._getTargetPosition());
  8135. this.radius = radiusv3.length();
  8136. // Alpha
  8137. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  8138. if (radiusv3.z < 0) {
  8139. this.alpha = 2 * Math.PI - this.alpha;
  8140. }
  8141. // Beta
  8142. this.beta = Math.acos(radiusv3.y / this.radius);
  8143. };
  8144. ArcRotateCamera.prototype._getViewMatrix = function () {
  8145. // Compute
  8146. var cosa = Math.cos(this.alpha);
  8147. var sina = Math.sin(this.alpha);
  8148. var cosb = Math.cos(this.beta);
  8149. var sinb = Math.sin(this.beta);
  8150. var target = this._getTargetPosition();
  8151. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  8152. if (this.checkCollisions) {
  8153. this._collider.radius = this.collisionRadius;
  8154. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  8155. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  8156. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  8157. this.position.copyFrom(this._previousPosition);
  8158. this.alpha = this._previousAlpha;
  8159. this.beta = this._previousBeta;
  8160. this.radius = this._previousRadius;
  8161. if (this.onCollide) {
  8162. this.onCollide(this._collider.collidedMesh);
  8163. }
  8164. }
  8165. }
  8166. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  8167. this._previousAlpha = this.alpha;
  8168. this._previousBeta = this.beta;
  8169. this._previousRadius = this.radius;
  8170. this._previousPosition.copyFrom(this.position);
  8171. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  8172. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  8173. return this._viewMatrix;
  8174. };
  8175. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  8176. meshes = meshes || this.getScene().meshes;
  8177. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  8178. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  8179. this.radius = distance * this.zoomOnFactor;
  8180. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  8181. };
  8182. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  8183. var meshesOrMinMaxVector;
  8184. var distance;
  8185. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  8186. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  8187. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8188. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  8189. }
  8190. else {
  8191. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  8192. distance = meshesOrMinMaxVectorAndDistance.distance;
  8193. }
  8194. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  8195. this.maxZ = distance * 2;
  8196. };
  8197. return ArcRotateCamera;
  8198. })(BABYLON.Camera);
  8199. BABYLON.ArcRotateCamera = ArcRotateCamera;
  8200. })(BABYLON || (BABYLON = {}));
  8201. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  8202. (function (BABYLON) {
  8203. /**
  8204. * Represents a scene to be rendered by the engine.
  8205. * @see http://doc.babylonjs.com/page.php?p=21911
  8206. */
  8207. var Scene = (function () {
  8208. /**
  8209. * @constructor
  8210. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  8211. */
  8212. function Scene(engine) {
  8213. // Members
  8214. this.autoClear = true;
  8215. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8216. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  8217. this.forceWireframe = false;
  8218. this.forcePointsCloud = false;
  8219. this.forceShowBoundingBoxes = false;
  8220. this.animationsEnabled = true;
  8221. 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
  8222. // Fog
  8223. /**
  8224. * is fog enabled on this scene.
  8225. * @type {boolean}
  8226. */
  8227. this.fogEnabled = true;
  8228. this.fogMode = Scene.FOGMODE_NONE;
  8229. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8230. this.fogDensity = 0.1;
  8231. this.fogStart = 0;
  8232. this.fogEnd = 1000.0;
  8233. // Lights
  8234. /**
  8235. * is shadow enabled on this scene.
  8236. * @type {boolean}
  8237. */
  8238. this.shadowsEnabled = true;
  8239. /**
  8240. * is light enabled on this scene.
  8241. * @type {boolean}
  8242. */
  8243. this.lightsEnabled = true;
  8244. /**
  8245. * All of the lights added to this scene.
  8246. * @see BABYLON.Light
  8247. * @type {BABYLON.Light[]}
  8248. */
  8249. this.lights = new Array();
  8250. // Cameras
  8251. /**
  8252. * All of the cameras added to this scene.
  8253. * @see BABYLON.Camera
  8254. * @type {BABYLON.Camera[]}
  8255. */
  8256. this.cameras = new Array();
  8257. this.activeCameras = new Array();
  8258. // Meshes
  8259. /**
  8260. * All of the (abstract) meshes added to this scene.
  8261. * @see BABYLON.AbstractMesh
  8262. * @type {BABYLON.AbstractMesh[]}
  8263. */
  8264. this.meshes = new Array();
  8265. // Geometries
  8266. this._geometries = new Array();
  8267. this.materials = new Array();
  8268. this.multiMaterials = new Array();
  8269. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  8270. // Textures
  8271. this.texturesEnabled = true;
  8272. this.textures = new Array();
  8273. // Particles
  8274. this.particlesEnabled = true;
  8275. this.particleSystems = new Array();
  8276. // Sprites
  8277. this.spritesEnabled = true;
  8278. this.spriteManagers = new Array();
  8279. // Layers
  8280. this.layers = new Array();
  8281. // Skeletons
  8282. this.skeletonsEnabled = true;
  8283. this.skeletons = new Array();
  8284. // Lens flares
  8285. this.lensFlaresEnabled = true;
  8286. this.lensFlareSystems = new Array();
  8287. // Collisions
  8288. this.collisionsEnabled = true;
  8289. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  8290. // Postprocesses
  8291. this.postProcessesEnabled = true;
  8292. // Customs render targets
  8293. this.renderTargetsEnabled = true;
  8294. this.dumpNextRenderTargets = false;
  8295. this.customRenderTargets = new Array();
  8296. // Imported meshes
  8297. this.importedMeshesFiles = new Array();
  8298. this._actionManagers = new Array();
  8299. this._meshesForIntersections = new BABYLON.SmartArray(256);
  8300. // Procedural textures
  8301. this.proceduralTexturesEnabled = true;
  8302. this._proceduralTextures = new Array();
  8303. this.soundTracks = new Array();
  8304. this._audioEnabled = true;
  8305. this._headphone = false;
  8306. this._totalVertices = 0;
  8307. this._activeIndices = 0;
  8308. this._activeParticles = 0;
  8309. this._lastFrameDuration = 0;
  8310. this._evaluateActiveMeshesDuration = 0;
  8311. this._renderTargetsDuration = 0;
  8312. this._particlesDuration = 0;
  8313. this._renderDuration = 0;
  8314. this._spritesDuration = 0;
  8315. this._animationRatio = 0;
  8316. this._renderId = 0;
  8317. this._executeWhenReadyTimeoutId = -1;
  8318. this._toBeDisposed = new BABYLON.SmartArray(256);
  8319. this._onReadyCallbacks = new Array();
  8320. this._pendingData = []; //ANY
  8321. this._onBeforeRenderCallbacks = new Array();
  8322. this._onAfterRenderCallbacks = new Array();
  8323. this._activeMeshes = new BABYLON.SmartArray(256);
  8324. this._processedMaterials = new BABYLON.SmartArray(256);
  8325. this._renderTargets = new BABYLON.SmartArray(256);
  8326. this._activeParticleSystems = new BABYLON.SmartArray(256);
  8327. this._activeSkeletons = new BABYLON.SmartArray(32);
  8328. this._activeBones = 0;
  8329. this._activeAnimatables = new Array();
  8330. this._transformMatrix = BABYLON.Matrix.Zero();
  8331. this._scaledPosition = BABYLON.Vector3.Zero();
  8332. this._scaledVelocity = BABYLON.Vector3.Zero();
  8333. this._uniqueIdCounter = 0;
  8334. this._engine = engine;
  8335. engine.scenes.push(this);
  8336. this._renderingManager = new BABYLON.RenderingManager(this);
  8337. this.postProcessManager = new BABYLON.PostProcessManager(this);
  8338. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  8339. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  8340. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  8341. this.attachControl();
  8342. this._debugLayer = new BABYLON.DebugLayer(this);
  8343. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  8344. //simplification queue
  8345. this.simplificationQueue = new BABYLON.SimplificationQueue();
  8346. }
  8347. Object.defineProperty(Scene, "FOGMODE_NONE", {
  8348. get: function () {
  8349. return Scene._FOGMODE_NONE;
  8350. },
  8351. enumerable: true,
  8352. configurable: true
  8353. });
  8354. Object.defineProperty(Scene, "FOGMODE_EXP", {
  8355. get: function () {
  8356. return Scene._FOGMODE_EXP;
  8357. },
  8358. enumerable: true,
  8359. configurable: true
  8360. });
  8361. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  8362. get: function () {
  8363. return Scene._FOGMODE_EXP2;
  8364. },
  8365. enumerable: true,
  8366. configurable: true
  8367. });
  8368. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  8369. get: function () {
  8370. return Scene._FOGMODE_LINEAR;
  8371. },
  8372. enumerable: true,
  8373. configurable: true
  8374. });
  8375. Object.defineProperty(Scene.prototype, "debugLayer", {
  8376. // Properties
  8377. get: function () {
  8378. return this._debugLayer;
  8379. },
  8380. enumerable: true,
  8381. configurable: true
  8382. });
  8383. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  8384. /**
  8385. * The mesh that is currently under the pointer.
  8386. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  8387. */
  8388. get: function () {
  8389. return this._meshUnderPointer;
  8390. },
  8391. enumerable: true,
  8392. configurable: true
  8393. });
  8394. Object.defineProperty(Scene.prototype, "pointerX", {
  8395. /**
  8396. * Current on-screen X position of the pointer
  8397. * @return {number} X position of the pointer
  8398. */
  8399. get: function () {
  8400. return this._pointerX;
  8401. },
  8402. enumerable: true,
  8403. configurable: true
  8404. });
  8405. Object.defineProperty(Scene.prototype, "pointerY", {
  8406. /**
  8407. * Current on-screen Y position of the pointer
  8408. * @return {number} Y position of the pointer
  8409. */
  8410. get: function () {
  8411. return this._pointerY;
  8412. },
  8413. enumerable: true,
  8414. configurable: true
  8415. });
  8416. Scene.prototype.getCachedMaterial = function () {
  8417. return this._cachedMaterial;
  8418. };
  8419. Scene.prototype.getBoundingBoxRenderer = function () {
  8420. return this._boundingBoxRenderer;
  8421. };
  8422. Scene.prototype.getOutlineRenderer = function () {
  8423. return this._outlineRenderer;
  8424. };
  8425. Scene.prototype.getEngine = function () {
  8426. return this._engine;
  8427. };
  8428. Scene.prototype.getTotalVertices = function () {
  8429. return this._totalVertices;
  8430. };
  8431. Scene.prototype.getActiveIndices = function () {
  8432. return this._activeIndices;
  8433. };
  8434. Scene.prototype.getActiveParticles = function () {
  8435. return this._activeParticles;
  8436. };
  8437. Scene.prototype.getActiveBones = function () {
  8438. return this._activeBones;
  8439. };
  8440. // Stats
  8441. Scene.prototype.getLastFrameDuration = function () {
  8442. return this._lastFrameDuration;
  8443. };
  8444. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8445. return this._evaluateActiveMeshesDuration;
  8446. };
  8447. Scene.prototype.getActiveMeshes = function () {
  8448. return this._activeMeshes;
  8449. };
  8450. Scene.prototype.getRenderTargetsDuration = function () {
  8451. return this._renderTargetsDuration;
  8452. };
  8453. Scene.prototype.getRenderDuration = function () {
  8454. return this._renderDuration;
  8455. };
  8456. Scene.prototype.getParticlesDuration = function () {
  8457. return this._particlesDuration;
  8458. };
  8459. Scene.prototype.getSpritesDuration = function () {
  8460. return this._spritesDuration;
  8461. };
  8462. Scene.prototype.getAnimationRatio = function () {
  8463. return this._animationRatio;
  8464. };
  8465. Scene.prototype.getRenderId = function () {
  8466. return this._renderId;
  8467. };
  8468. Scene.prototype.incrementRenderId = function () {
  8469. this._renderId++;
  8470. };
  8471. Scene.prototype._updatePointerPosition = function (evt) {
  8472. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8473. this._pointerX = evt.clientX - canvasRect.left;
  8474. this._pointerY = evt.clientY - canvasRect.top;
  8475. if (this.cameraToUseForPointers) {
  8476. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8477. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8478. }
  8479. };
  8480. // Pointers handling
  8481. Scene.prototype.attachControl = function () {
  8482. var _this = this;
  8483. this._onPointerMove = function (evt) {
  8484. var canvas = _this._engine.getRenderingCanvas();
  8485. _this._updatePointerPosition(evt);
  8486. 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);
  8487. if (pickResult.hit) {
  8488. _this._meshUnderPointer = pickResult.pickedMesh;
  8489. _this.setPointerOverMesh(pickResult.pickedMesh);
  8490. canvas.style.cursor = "pointer";
  8491. }
  8492. else {
  8493. _this.setPointerOverMesh(null);
  8494. canvas.style.cursor = "";
  8495. _this._meshUnderPointer = null;
  8496. }
  8497. };
  8498. this._onPointerDown = function (evt) {
  8499. var predicate = null;
  8500. if (!_this.onPointerDown) {
  8501. predicate = function (mesh) {
  8502. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8503. };
  8504. }
  8505. _this._updatePointerPosition(evt);
  8506. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8507. if (pickResult.hit) {
  8508. if (pickResult.pickedMesh.actionManager) {
  8509. switch (evt.button) {
  8510. case 0:
  8511. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8512. break;
  8513. case 1:
  8514. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8515. break;
  8516. case 2:
  8517. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8518. break;
  8519. }
  8520. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8521. }
  8522. }
  8523. if (_this.onPointerDown) {
  8524. _this.onPointerDown(evt, pickResult);
  8525. }
  8526. };
  8527. this._onPointerUp = function (evt) {
  8528. var predicate = null;
  8529. if (!_this.onPointerUp) {
  8530. predicate = function (mesh) {
  8531. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  8532. };
  8533. }
  8534. _this._updatePointerPosition(evt);
  8535. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8536. if (pickResult.hit) {
  8537. if (pickResult.pickedMesh.actionManager) {
  8538. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8539. }
  8540. }
  8541. if (_this.onPointerUp) {
  8542. _this.onPointerUp(evt, pickResult);
  8543. }
  8544. };
  8545. this._onKeyDown = function (evt) {
  8546. if (_this.actionManager) {
  8547. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8548. }
  8549. };
  8550. this._onKeyUp = function (evt) {
  8551. if (_this.actionManager) {
  8552. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8553. }
  8554. };
  8555. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8556. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8557. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8558. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  8559. BABYLON.Tools.RegisterTopRootEvents([
  8560. { name: "keydown", handler: this._onKeyDown },
  8561. { name: "keyup", handler: this._onKeyUp }
  8562. ]);
  8563. };
  8564. Scene.prototype.detachControl = function () {
  8565. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8566. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8567. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8568. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  8569. BABYLON.Tools.UnregisterTopRootEvents([
  8570. { name: "keydown", handler: this._onKeyDown },
  8571. { name: "keyup", handler: this._onKeyUp }
  8572. ]);
  8573. };
  8574. // Ready
  8575. Scene.prototype.isReady = function () {
  8576. if (this._pendingData.length > 0) {
  8577. return false;
  8578. }
  8579. for (var index = 0; index < this._geometries.length; index++) {
  8580. var geometry = this._geometries[index];
  8581. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8582. return false;
  8583. }
  8584. }
  8585. for (index = 0; index < this.meshes.length; index++) {
  8586. var mesh = this.meshes[index];
  8587. if (!mesh.isReady()) {
  8588. return false;
  8589. }
  8590. var mat = mesh.material;
  8591. if (mat) {
  8592. if (!mat.isReady(mesh)) {
  8593. return false;
  8594. }
  8595. }
  8596. }
  8597. return true;
  8598. };
  8599. Scene.prototype.resetCachedMaterial = function () {
  8600. this._cachedMaterial = null;
  8601. };
  8602. Scene.prototype.registerBeforeRender = function (func) {
  8603. this._onBeforeRenderCallbacks.push(func);
  8604. };
  8605. Scene.prototype.unregisterBeforeRender = function (func) {
  8606. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8607. if (index > -1) {
  8608. this._onBeforeRenderCallbacks.splice(index, 1);
  8609. }
  8610. };
  8611. Scene.prototype.registerAfterRender = function (func) {
  8612. this._onAfterRenderCallbacks.push(func);
  8613. };
  8614. Scene.prototype.unregisterAfterRender = function (func) {
  8615. var index = this._onAfterRenderCallbacks.indexOf(func);
  8616. if (index > -1) {
  8617. this._onAfterRenderCallbacks.splice(index, 1);
  8618. }
  8619. };
  8620. Scene.prototype._addPendingData = function (data) {
  8621. this._pendingData.push(data);
  8622. };
  8623. Scene.prototype._removePendingData = function (data) {
  8624. var index = this._pendingData.indexOf(data);
  8625. if (index !== -1) {
  8626. this._pendingData.splice(index, 1);
  8627. }
  8628. };
  8629. Scene.prototype.getWaitingItemsCount = function () {
  8630. return this._pendingData.length;
  8631. };
  8632. /**
  8633. * Registers a function to be executed when the scene is ready.
  8634. * @param {Function} func - the function to be executed.
  8635. */
  8636. Scene.prototype.executeWhenReady = function (func) {
  8637. var _this = this;
  8638. this._onReadyCallbacks.push(func);
  8639. if (this._executeWhenReadyTimeoutId !== -1) {
  8640. return;
  8641. }
  8642. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8643. _this._checkIsReady();
  8644. }, 150);
  8645. };
  8646. Scene.prototype._checkIsReady = function () {
  8647. var _this = this;
  8648. if (this.isReady()) {
  8649. this._onReadyCallbacks.forEach(function (func) {
  8650. func();
  8651. });
  8652. this._onReadyCallbacks = [];
  8653. this._executeWhenReadyTimeoutId = -1;
  8654. return;
  8655. }
  8656. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8657. _this._checkIsReady();
  8658. }, 150);
  8659. };
  8660. // Animations
  8661. /**
  8662. * Will start the animation sequence of a given target
  8663. * @param target - the target
  8664. * @param {number} from - from which frame should animation start
  8665. * @param {number} to - till which frame should animation run.
  8666. * @param {boolean} [loop] - should the animation loop
  8667. * @param {number} [speedRatio] - the speed in which to run the animation
  8668. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8669. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8670. * @return {BABYLON.Animatable} the animatable object created for this animation
  8671. * @see BABYLON.Animatable
  8672. * @see http://doc.babylonjs.com/page.php?p=22081
  8673. */
  8674. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8675. if (speedRatio === undefined) {
  8676. speedRatio = 1.0;
  8677. }
  8678. this.stopAnimation(target);
  8679. if (!animatable) {
  8680. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8681. }
  8682. // Local animations
  8683. if (target.animations) {
  8684. animatable.appendAnimations(target, target.animations);
  8685. }
  8686. // Children animations
  8687. if (target.getAnimatables) {
  8688. var animatables = target.getAnimatables();
  8689. for (var index = 0; index < animatables.length; index++) {
  8690. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8691. }
  8692. }
  8693. return animatable;
  8694. };
  8695. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8696. if (speedRatio === undefined) {
  8697. speedRatio = 1.0;
  8698. }
  8699. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8700. return animatable;
  8701. };
  8702. Scene.prototype.getAnimatableByTarget = function (target) {
  8703. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8704. if (this._activeAnimatables[index].target === target) {
  8705. return this._activeAnimatables[index];
  8706. }
  8707. }
  8708. return null;
  8709. };
  8710. /**
  8711. * Will stop the animation of the given target
  8712. * @param target - the target
  8713. * @see beginAnimation
  8714. */
  8715. Scene.prototype.stopAnimation = function (target) {
  8716. var animatable = this.getAnimatableByTarget(target);
  8717. if (animatable) {
  8718. animatable.stop();
  8719. }
  8720. };
  8721. Scene.prototype._animate = function () {
  8722. if (!this.animationsEnabled) {
  8723. return;
  8724. }
  8725. if (!this._animationStartDate) {
  8726. this._animationStartDate = BABYLON.Tools.Now;
  8727. }
  8728. // Getting time
  8729. var now = BABYLON.Tools.Now;
  8730. var delay = now - this._animationStartDate;
  8731. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8732. this._activeAnimatables[index]._animate(delay);
  8733. }
  8734. };
  8735. // Matrix
  8736. Scene.prototype.getViewMatrix = function () {
  8737. return this._viewMatrix;
  8738. };
  8739. Scene.prototype.getProjectionMatrix = function () {
  8740. return this._projectionMatrix;
  8741. };
  8742. Scene.prototype.getTransformMatrix = function () {
  8743. return this._transformMatrix;
  8744. };
  8745. Scene.prototype.setTransformMatrix = function (view, projection) {
  8746. this._viewMatrix = view;
  8747. this._projectionMatrix = projection;
  8748. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8749. };
  8750. // Methods
  8751. Scene.prototype.addMesh = function (newMesh) {
  8752. newMesh.uniqueId = this._uniqueIdCounter++;
  8753. var position = this.meshes.push(newMesh);
  8754. if (this.onNewMeshAdded) {
  8755. this.onNewMeshAdded(newMesh, position, this);
  8756. }
  8757. };
  8758. Scene.prototype.removeMesh = function (toRemove) {
  8759. var index = this.meshes.indexOf(toRemove);
  8760. if (index !== -1) {
  8761. // Remove from the scene if mesh found
  8762. this.meshes.splice(index, 1);
  8763. }
  8764. if (this.onMeshRemoved) {
  8765. this.onMeshRemoved(toRemove);
  8766. }
  8767. return index;
  8768. };
  8769. Scene.prototype.removeLight = function (toRemove) {
  8770. var index = this.lights.indexOf(toRemove);
  8771. if (index !== -1) {
  8772. // Remove from the scene if mesh found
  8773. this.lights.splice(index, 1);
  8774. }
  8775. if (this.onLightRemoved) {
  8776. this.onLightRemoved(toRemove);
  8777. }
  8778. return index;
  8779. };
  8780. Scene.prototype.removeCamera = function (toRemove) {
  8781. var index = this.cameras.indexOf(toRemove);
  8782. if (index !== -1) {
  8783. // Remove from the scene if mesh found
  8784. this.cameras.splice(index, 1);
  8785. }
  8786. // Remove from activeCameras
  8787. var index2 = this.activeCameras.indexOf(toRemove);
  8788. if (index2 !== -1) {
  8789. // Remove from the scene if mesh found
  8790. this.activeCameras.splice(index2, 1);
  8791. }
  8792. // Reset the activeCamera
  8793. if (this.activeCamera === toRemove) {
  8794. if (this.cameras.length > 0) {
  8795. this.activeCamera = this.cameras[0];
  8796. }
  8797. else {
  8798. this.activeCamera = null;
  8799. }
  8800. }
  8801. if (this.onCameraRemoved) {
  8802. this.onCameraRemoved(toRemove);
  8803. }
  8804. return index;
  8805. };
  8806. Scene.prototype.addLight = function (newLight) {
  8807. newLight.uniqueId = this._uniqueIdCounter++;
  8808. var position = this.lights.push(newLight);
  8809. if (this.onNewLightAdded) {
  8810. this.onNewLightAdded(newLight, position, this);
  8811. }
  8812. };
  8813. Scene.prototype.addCamera = function (newCamera) {
  8814. newCamera.uniqueId = this._uniqueIdCounter++;
  8815. var position = this.cameras.push(newCamera);
  8816. if (this.onNewCameraAdded) {
  8817. this.onNewCameraAdded(newCamera, position, this);
  8818. }
  8819. };
  8820. /**
  8821. * sets the active camera of the scene using its ID
  8822. * @param {string} id - the camera's ID
  8823. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8824. * @see activeCamera
  8825. */
  8826. Scene.prototype.setActiveCameraByID = function (id) {
  8827. var camera = this.getCameraByID(id);
  8828. if (camera) {
  8829. this.activeCamera = camera;
  8830. return camera;
  8831. }
  8832. return null;
  8833. };
  8834. /**
  8835. * sets the active camera of the scene using its name
  8836. * @param {string} name - the camera's name
  8837. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8838. * @see activeCamera
  8839. */
  8840. Scene.prototype.setActiveCameraByName = function (name) {
  8841. var camera = this.getCameraByName(name);
  8842. if (camera) {
  8843. this.activeCamera = camera;
  8844. return camera;
  8845. }
  8846. return null;
  8847. };
  8848. /**
  8849. * get a material using its id
  8850. * @param {string} the material's ID
  8851. * @return {BABYLON.Material|null} the material or null if none found.
  8852. */
  8853. Scene.prototype.getMaterialByID = function (id) {
  8854. for (var index = 0; index < this.materials.length; index++) {
  8855. if (this.materials[index].id === id) {
  8856. return this.materials[index];
  8857. }
  8858. }
  8859. return null;
  8860. };
  8861. /**
  8862. * get a material using its name
  8863. * @param {string} the material's name
  8864. * @return {BABYLON.Material|null} the material or null if none found.
  8865. */
  8866. Scene.prototype.getMaterialByName = function (name) {
  8867. for (var index = 0; index < this.materials.length; index++) {
  8868. if (this.materials[index].name === name) {
  8869. return this.materials[index];
  8870. }
  8871. }
  8872. return null;
  8873. };
  8874. Scene.prototype.getCameraByID = function (id) {
  8875. for (var index = 0; index < this.cameras.length; index++) {
  8876. if (this.cameras[index].id === id) {
  8877. return this.cameras[index];
  8878. }
  8879. }
  8880. return null;
  8881. };
  8882. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  8883. for (var index = 0; index < this.cameras.length; index++) {
  8884. if (this.cameras[index].uniqueId === uniqueId) {
  8885. return this.cameras[index];
  8886. }
  8887. }
  8888. return null;
  8889. };
  8890. /**
  8891. * get a camera using its name
  8892. * @param {string} the camera's name
  8893. * @return {BABYLON.Camera|null} the camera or null if none found.
  8894. */
  8895. Scene.prototype.getCameraByName = function (name) {
  8896. for (var index = 0; index < this.cameras.length; index++) {
  8897. if (this.cameras[index].name === name) {
  8898. return this.cameras[index];
  8899. }
  8900. }
  8901. return null;
  8902. };
  8903. /**
  8904. * get a light node using its name
  8905. * @param {string} the light's name
  8906. * @return {BABYLON.Light|null} the light or null if none found.
  8907. */
  8908. Scene.prototype.getLightByName = function (name) {
  8909. for (var index = 0; index < this.lights.length; index++) {
  8910. if (this.lights[index].name === name) {
  8911. return this.lights[index];
  8912. }
  8913. }
  8914. return null;
  8915. };
  8916. /**
  8917. * get a light node using its ID
  8918. * @param {string} the light's id
  8919. * @return {BABYLON.Light|null} the light or null if none found.
  8920. */
  8921. Scene.prototype.getLightByID = function (id) {
  8922. for (var index = 0; index < this.lights.length; index++) {
  8923. if (this.lights[index].id === id) {
  8924. return this.lights[index];
  8925. }
  8926. }
  8927. return null;
  8928. };
  8929. /**
  8930. * get a light node using its scene-generated unique ID
  8931. * @param {number} the light's unique id
  8932. * @return {BABYLON.Light|null} the light or null if none found.
  8933. */
  8934. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  8935. for (var index = 0; index < this.lights.length; index++) {
  8936. if (this.lights[index].uniqueId === uniqueId) {
  8937. return this.lights[index];
  8938. }
  8939. }
  8940. return null;
  8941. };
  8942. /**
  8943. * get a geometry using its ID
  8944. * @param {string} the geometry's id
  8945. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8946. */
  8947. Scene.prototype.getGeometryByID = function (id) {
  8948. for (var index = 0; index < this._geometries.length; index++) {
  8949. if (this._geometries[index].id === id) {
  8950. return this._geometries[index];
  8951. }
  8952. }
  8953. return null;
  8954. };
  8955. /**
  8956. * add a new geometry to this scene.
  8957. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8958. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8959. * @return {boolean} was the geometry added or not
  8960. */
  8961. Scene.prototype.pushGeometry = function (geometry, force) {
  8962. if (!force && this.getGeometryByID(geometry.id)) {
  8963. return false;
  8964. }
  8965. this._geometries.push(geometry);
  8966. if (this.onGeometryAdded) {
  8967. this.onGeometryAdded(geometry);
  8968. }
  8969. return true;
  8970. };
  8971. /**
  8972. * Removes an existing geometry
  8973. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  8974. * @return {boolean} was the geometry removed or not
  8975. */
  8976. Scene.prototype.removeGeometry = function (geometry) {
  8977. var index = this._geometries.indexOf(geometry);
  8978. if (index > -1) {
  8979. this._geometries.splice(index, 1);
  8980. if (this.onGeometryRemoved) {
  8981. this.onGeometryRemoved(geometry);
  8982. }
  8983. return true;
  8984. }
  8985. return false;
  8986. };
  8987. Scene.prototype.getGeometries = function () {
  8988. return this._geometries;
  8989. };
  8990. /**
  8991. * Get the first added mesh found of a given ID
  8992. * @param {string} id - the id to search for
  8993. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8994. */
  8995. Scene.prototype.getMeshByID = function (id) {
  8996. for (var index = 0; index < this.meshes.length; index++) {
  8997. if (this.meshes[index].id === id) {
  8998. return this.meshes[index];
  8999. }
  9000. }
  9001. return null;
  9002. };
  9003. /**
  9004. * Get a mesh with its auto-generated unique id
  9005. * @param {number} uniqueId - the unique id to search for
  9006. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  9007. */
  9008. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  9009. for (var index = 0; index < this.meshes.length; index++) {
  9010. if (this.meshes[index].uniqueId === uniqueId) {
  9011. return this.meshes[index];
  9012. }
  9013. }
  9014. return null;
  9015. };
  9016. /**
  9017. * Get a the last added mesh found of a given ID
  9018. * @param {string} id - the id to search for
  9019. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  9020. */
  9021. Scene.prototype.getLastMeshByID = function (id) {
  9022. for (var index = this.meshes.length - 1; index >= 0; index--) {
  9023. if (this.meshes[index].id === id) {
  9024. return this.meshes[index];
  9025. }
  9026. }
  9027. return null;
  9028. };
  9029. /**
  9030. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  9031. * @param {string} id - the id to search for
  9032. * @return {BABYLON.Node|null} the node found or null if not found at all.
  9033. */
  9034. Scene.prototype.getLastEntryByID = function (id) {
  9035. for (var index = this.meshes.length - 1; index >= 0; index--) {
  9036. if (this.meshes[index].id === id) {
  9037. return this.meshes[index];
  9038. }
  9039. }
  9040. for (index = this.cameras.length - 1; index >= 0; index--) {
  9041. if (this.cameras[index].id === id) {
  9042. return this.cameras[index];
  9043. }
  9044. }
  9045. for (index = this.lights.length - 1; index >= 0; index--) {
  9046. if (this.lights[index].id === id) {
  9047. return this.lights[index];
  9048. }
  9049. }
  9050. return null;
  9051. };
  9052. Scene.prototype.getNodeByName = function (name) {
  9053. var mesh = this.getMeshByName(name);
  9054. if (mesh) {
  9055. return mesh;
  9056. }
  9057. var light = this.getLightByName(name);
  9058. if (light) {
  9059. return light;
  9060. }
  9061. return this.getCameraByName(name);
  9062. };
  9063. Scene.prototype.getMeshByName = function (name) {
  9064. for (var index = 0; index < this.meshes.length; index++) {
  9065. if (this.meshes[index].name === name) {
  9066. return this.meshes[index];
  9067. }
  9068. }
  9069. return null;
  9070. };
  9071. Scene.prototype.getSoundByName = function (name) {
  9072. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  9073. if (this.mainSoundTrack.soundCollection[index].name === name) {
  9074. return this.mainSoundTrack.soundCollection[index];
  9075. }
  9076. }
  9077. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  9078. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  9079. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  9080. return this.soundTracks[sdIndex].soundCollection[index];
  9081. }
  9082. }
  9083. }
  9084. return null;
  9085. };
  9086. Scene.prototype.getLastSkeletonByID = function (id) {
  9087. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  9088. if (this.skeletons[index].id === id) {
  9089. return this.skeletons[index];
  9090. }
  9091. }
  9092. return null;
  9093. };
  9094. Scene.prototype.getSkeletonById = function (id) {
  9095. for (var index = 0; index < this.skeletons.length; index++) {
  9096. if (this.skeletons[index].id === id) {
  9097. return this.skeletons[index];
  9098. }
  9099. }
  9100. return null;
  9101. };
  9102. Scene.prototype.getSkeletonByName = function (name) {
  9103. for (var index = 0; index < this.skeletons.length; index++) {
  9104. if (this.skeletons[index].name === name) {
  9105. return this.skeletons[index];
  9106. }
  9107. }
  9108. return null;
  9109. };
  9110. Scene.prototype.isActiveMesh = function (mesh) {
  9111. return (this._activeMeshes.indexOf(mesh) !== -1);
  9112. };
  9113. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  9114. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  9115. var material = subMesh.getMaterial();
  9116. if (mesh.showSubMeshesBoundingBox) {
  9117. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  9118. }
  9119. if (material) {
  9120. // Render targets
  9121. if (material.getRenderTargetTextures) {
  9122. if (this._processedMaterials.indexOf(material) === -1) {
  9123. this._processedMaterials.push(material);
  9124. this._renderTargets.concat(material.getRenderTargetTextures());
  9125. }
  9126. }
  9127. // Dispatch
  9128. this._activeIndices += subMesh.indexCount;
  9129. this._renderingManager.dispatch(subMesh);
  9130. }
  9131. }
  9132. };
  9133. Scene.prototype._evaluateActiveMeshes = function () {
  9134. this.activeCamera._activeMeshes.reset();
  9135. this._activeMeshes.reset();
  9136. this._renderingManager.reset();
  9137. this._processedMaterials.reset();
  9138. this._activeParticleSystems.reset();
  9139. this._activeSkeletons.reset();
  9140. this._boundingBoxRenderer.reset();
  9141. if (!this._frustumPlanes) {
  9142. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  9143. }
  9144. else {
  9145. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  9146. }
  9147. // Meshes
  9148. var meshes;
  9149. var len;
  9150. if (this._selectionOctree) {
  9151. var selection = this._selectionOctree.select(this._frustumPlanes);
  9152. meshes = selection.data;
  9153. len = selection.length;
  9154. }
  9155. else {
  9156. len = this.meshes.length;
  9157. meshes = this.meshes;
  9158. }
  9159. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  9160. var mesh = meshes[meshIndex];
  9161. if (mesh.isBlocked) {
  9162. continue;
  9163. }
  9164. this._totalVertices += mesh.getTotalVertices();
  9165. if (!mesh.isReady() || !mesh.isEnabled()) {
  9166. continue;
  9167. }
  9168. mesh.computeWorldMatrix();
  9169. // Intersections
  9170. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  9171. this._meshesForIntersections.pushNoDuplicate(mesh);
  9172. }
  9173. // Switch to current LOD
  9174. var meshLOD = mesh.getLOD(this.activeCamera);
  9175. if (!meshLOD) {
  9176. continue;
  9177. }
  9178. mesh._preActivate();
  9179. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  9180. this._activeMeshes.push(mesh);
  9181. this.activeCamera._activeMeshes.push(mesh);
  9182. mesh._activate(this._renderId);
  9183. this._activeMesh(meshLOD);
  9184. }
  9185. }
  9186. // Particle systems
  9187. var beforeParticlesDate = BABYLON.Tools.Now;
  9188. if (this.particlesEnabled) {
  9189. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  9190. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  9191. var particleSystem = this.particleSystems[particleIndex];
  9192. if (!particleSystem.isStarted()) {
  9193. continue;
  9194. }
  9195. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  9196. this._activeParticleSystems.push(particleSystem);
  9197. particleSystem.animate();
  9198. }
  9199. }
  9200. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  9201. }
  9202. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9203. };
  9204. Scene.prototype._activeMesh = function (mesh) {
  9205. if (mesh.skeleton && this.skeletonsEnabled) {
  9206. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  9207. }
  9208. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  9209. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  9210. }
  9211. if (mesh && mesh.subMeshes) {
  9212. // Submeshes Octrees
  9213. var len;
  9214. var subMeshes;
  9215. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  9216. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  9217. len = intersections.length;
  9218. subMeshes = intersections.data;
  9219. }
  9220. else {
  9221. subMeshes = mesh.subMeshes;
  9222. len = subMeshes.length;
  9223. }
  9224. for (var subIndex = 0; subIndex < len; subIndex++) {
  9225. var subMesh = subMeshes[subIndex];
  9226. this._evaluateSubMesh(subMesh, mesh);
  9227. }
  9228. }
  9229. };
  9230. Scene.prototype.updateTransformMatrix = function (force) {
  9231. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  9232. };
  9233. Scene.prototype._renderForCamera = function (camera) {
  9234. var engine = this._engine;
  9235. this.activeCamera = camera;
  9236. if (!this.activeCamera)
  9237. throw new Error("Active camera not set");
  9238. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9239. // Viewport
  9240. engine.setViewport(this.activeCamera.viewport);
  9241. // Camera
  9242. this._renderId++;
  9243. this.updateTransformMatrix();
  9244. if (this.beforeCameraRender) {
  9245. this.beforeCameraRender(this.activeCamera);
  9246. }
  9247. // Meshes
  9248. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  9249. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  9250. this._evaluateActiveMeshes();
  9251. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  9252. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  9253. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  9254. var skeleton = this._activeSkeletons.data[skeletonIndex];
  9255. skeleton.prepare();
  9256. }
  9257. // Render targets
  9258. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9259. if (this.renderTargetsEnabled) {
  9260. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9261. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  9262. var renderTarget = this._renderTargets.data[renderIndex];
  9263. if (renderTarget._shouldRender()) {
  9264. this._renderId++;
  9265. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  9266. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  9267. }
  9268. }
  9269. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9270. this._renderId++;
  9271. }
  9272. if (this._renderTargets.length > 0) {
  9273. engine.restoreDefaultFramebuffer();
  9274. }
  9275. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9276. // Prepare Frame
  9277. this.postProcessManager._prepareFrame();
  9278. var beforeRenderDate = BABYLON.Tools.Now;
  9279. // Backgrounds
  9280. if (this.layers.length) {
  9281. engine.setDepthBuffer(false);
  9282. var layerIndex;
  9283. var layer;
  9284. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9285. layer = this.layers[layerIndex];
  9286. if (layer.isBackground) {
  9287. layer.render();
  9288. }
  9289. }
  9290. engine.setDepthBuffer(true);
  9291. }
  9292. // Render
  9293. BABYLON.Tools.StartPerformanceCounter("Main render");
  9294. this._renderingManager.render(null, null, true, true);
  9295. BABYLON.Tools.EndPerformanceCounter("Main render");
  9296. // Bounding boxes
  9297. this._boundingBoxRenderer.render();
  9298. // Lens flares
  9299. if (this.lensFlaresEnabled) {
  9300. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9301. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  9302. this.lensFlareSystems[lensFlareSystemIndex].render();
  9303. }
  9304. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9305. }
  9306. // Foregrounds
  9307. if (this.layers.length) {
  9308. engine.setDepthBuffer(false);
  9309. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9310. layer = this.layers[layerIndex];
  9311. if (!layer.isBackground) {
  9312. layer.render();
  9313. }
  9314. }
  9315. engine.setDepthBuffer(true);
  9316. }
  9317. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  9318. // Finalize frame
  9319. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  9320. // Update camera
  9321. this.activeCamera._updateFromScene();
  9322. // Reset some special arrays
  9323. this._renderTargets.reset();
  9324. if (this.afterCameraRender) {
  9325. this.afterCameraRender(this.activeCamera);
  9326. }
  9327. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9328. };
  9329. Scene.prototype._processSubCameras = function (camera) {
  9330. if (camera.subCameras.length === 0) {
  9331. this._renderForCamera(camera);
  9332. return;
  9333. }
  9334. for (var index = 0; index < camera.subCameras.length; index++) {
  9335. this._renderForCamera(camera.subCameras[index]);
  9336. }
  9337. this.activeCamera = camera;
  9338. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  9339. // Update camera
  9340. this.activeCamera._updateFromScene();
  9341. };
  9342. Scene.prototype._checkIntersections = function () {
  9343. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  9344. var sourceMesh = this._meshesForIntersections.data[index];
  9345. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  9346. var action = sourceMesh.actionManager.actions[actionIndex];
  9347. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9348. var parameters = action.getTriggerParameter();
  9349. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  9350. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  9351. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9352. if (areIntersecting && currentIntersectionInProgress === -1) {
  9353. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  9354. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9355. sourceMesh._intersectionsInProgress.push(otherMesh);
  9356. }
  9357. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9358. sourceMesh._intersectionsInProgress.push(otherMesh);
  9359. }
  9360. }
  9361. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9362. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9363. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9364. if (indexOfOther > -1) {
  9365. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  9366. }
  9367. }
  9368. }
  9369. }
  9370. }
  9371. };
  9372. Scene.prototype.render = function () {
  9373. var startDate = BABYLON.Tools.Now;
  9374. this._particlesDuration = 0;
  9375. this._spritesDuration = 0;
  9376. this._activeParticles = 0;
  9377. this._renderDuration = 0;
  9378. this._renderTargetsDuration = 0;
  9379. this._evaluateActiveMeshesDuration = 0;
  9380. this._totalVertices = 0;
  9381. this._activeIndices = 0;
  9382. this._activeBones = 0;
  9383. this.getEngine().resetDrawCalls();
  9384. this._meshesForIntersections.reset();
  9385. this.resetCachedMaterial();
  9386. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  9387. // Actions
  9388. if (this.actionManager) {
  9389. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  9390. }
  9391. //Simplification Queue
  9392. if (!this.simplificationQueue.running) {
  9393. this.simplificationQueue.executeNext();
  9394. }
  9395. // Before render
  9396. if (this.beforeRender) {
  9397. this.beforeRender();
  9398. }
  9399. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9400. this._onBeforeRenderCallbacks[callbackIndex]();
  9401. }
  9402. // Animations
  9403. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  9404. this._animationRatio = deltaTime * (60.0 / 1000.0);
  9405. this._animate();
  9406. // Physics
  9407. if (this._physicsEngine) {
  9408. BABYLON.Tools.StartPerformanceCounter("Physics");
  9409. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  9410. BABYLON.Tools.EndPerformanceCounter("Physics");
  9411. }
  9412. // Customs render targets
  9413. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9414. var engine = this.getEngine();
  9415. var currentActiveCamera = this.activeCamera;
  9416. if (this.renderTargetsEnabled) {
  9417. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9418. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  9419. var renderTarget = this.customRenderTargets[customIndex];
  9420. if (renderTarget._shouldRender()) {
  9421. this._renderId++;
  9422. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  9423. if (!this.activeCamera)
  9424. throw new Error("Active camera not set");
  9425. // Viewport
  9426. engine.setViewport(this.activeCamera.viewport);
  9427. // Camera
  9428. this.updateTransformMatrix();
  9429. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  9430. }
  9431. }
  9432. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9433. this._renderId++;
  9434. }
  9435. if (this.customRenderTargets.length > 0) {
  9436. engine.restoreDefaultFramebuffer();
  9437. }
  9438. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9439. this.activeCamera = currentActiveCamera;
  9440. // Procedural textures
  9441. if (this.proceduralTexturesEnabled) {
  9442. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9443. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  9444. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  9445. if (proceduralTexture._shouldRender()) {
  9446. proceduralTexture.render();
  9447. }
  9448. }
  9449. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9450. }
  9451. // Clear
  9452. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  9453. // Shadows
  9454. if (this.shadowsEnabled) {
  9455. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  9456. var light = this.lights[lightIndex];
  9457. var shadowGenerator = light.getShadowGenerator();
  9458. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  9459. this._renderTargets.push(shadowGenerator.getShadowMap());
  9460. }
  9461. }
  9462. }
  9463. // Depth renderer
  9464. if (this._depthRenderer) {
  9465. this._renderTargets.push(this._depthRenderer.getDepthMap());
  9466. }
  9467. // RenderPipeline
  9468. this.postProcessRenderPipelineManager.update();
  9469. // Multi-cameras?
  9470. if (this.activeCameras.length > 0) {
  9471. var currentRenderId = this._renderId;
  9472. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  9473. this._renderId = currentRenderId;
  9474. this._processSubCameras(this.activeCameras[cameraIndex]);
  9475. }
  9476. }
  9477. else {
  9478. if (!this.activeCamera) {
  9479. throw new Error("No camera defined");
  9480. }
  9481. this._processSubCameras(this.activeCamera);
  9482. }
  9483. // Intersection checks
  9484. this._checkIntersections();
  9485. // Update the audio listener attached to the camera
  9486. this._updateAudioParameters();
  9487. // After render
  9488. if (this.afterRender) {
  9489. this.afterRender();
  9490. }
  9491. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9492. this._onAfterRenderCallbacks[callbackIndex]();
  9493. }
  9494. for (var index = 0; index < this._toBeDisposed.length; index++) {
  9495. this._toBeDisposed.data[index].dispose();
  9496. this._toBeDisposed[index] = null;
  9497. }
  9498. this._toBeDisposed.reset();
  9499. if (this.dumpNextRenderTargets) {
  9500. this.dumpNextRenderTargets = false;
  9501. }
  9502. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  9503. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  9504. };
  9505. Scene.prototype._updateAudioParameters = function () {
  9506. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  9507. return;
  9508. }
  9509. var listeningCamera;
  9510. var audioEngine = BABYLON.Engine.audioEngine;
  9511. if (this.activeCameras.length > 0) {
  9512. listeningCamera = this.activeCameras[0];
  9513. }
  9514. else {
  9515. listeningCamera = this.activeCamera;
  9516. }
  9517. if (listeningCamera && audioEngine.canUseWebAudio) {
  9518. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  9519. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  9520. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  9521. cameraDirection.normalize();
  9522. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  9523. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9524. var sound = this.mainSoundTrack.soundCollection[i];
  9525. if (sound.useCustomAttenuation) {
  9526. sound.updateDistanceFromListener();
  9527. }
  9528. }
  9529. for (i = 0; i < this.soundTracks.length; i++) {
  9530. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9531. sound = this.soundTracks[i].soundCollection[j];
  9532. if (sound.useCustomAttenuation) {
  9533. sound.updateDistanceFromListener();
  9534. }
  9535. }
  9536. }
  9537. }
  9538. };
  9539. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9540. // Audio
  9541. get: function () {
  9542. return this._audioEnabled;
  9543. },
  9544. set: function (value) {
  9545. this._audioEnabled = value;
  9546. if (this._audioEnabled) {
  9547. this._enableAudio();
  9548. }
  9549. else {
  9550. this._disableAudio();
  9551. }
  9552. },
  9553. enumerable: true,
  9554. configurable: true
  9555. });
  9556. Scene.prototype._disableAudio = function () {
  9557. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9558. this.mainSoundTrack.soundCollection[i].pause();
  9559. }
  9560. for (i = 0; i < this.soundTracks.length; i++) {
  9561. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9562. this.soundTracks[i].soundCollection[j].pause();
  9563. }
  9564. }
  9565. };
  9566. Scene.prototype._enableAudio = function () {
  9567. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9568. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9569. this.mainSoundTrack.soundCollection[i].play();
  9570. }
  9571. }
  9572. for (i = 0; i < this.soundTracks.length; i++) {
  9573. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9574. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9575. this.soundTracks[i].soundCollection[j].play();
  9576. }
  9577. }
  9578. }
  9579. };
  9580. Object.defineProperty(Scene.prototype, "headphone", {
  9581. get: function () {
  9582. return this._headphone;
  9583. },
  9584. set: function (value) {
  9585. this._headphone = value;
  9586. if (this._headphone) {
  9587. this._switchAudioModeForHeadphones();
  9588. }
  9589. else {
  9590. this._switchAudioModeForNormalSpeakers();
  9591. }
  9592. },
  9593. enumerable: true,
  9594. configurable: true
  9595. });
  9596. Scene.prototype._switchAudioModeForHeadphones = function () {
  9597. this.mainSoundTrack.switchPanningModelToHRTF();
  9598. for (var i = 0; i < this.soundTracks.length; i++) {
  9599. this.soundTracks[i].switchPanningModelToHRTF();
  9600. }
  9601. };
  9602. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  9603. this.mainSoundTrack.switchPanningModelToEqualPower();
  9604. for (var i = 0; i < this.soundTracks.length; i++) {
  9605. this.soundTracks[i].switchPanningModelToEqualPower();
  9606. }
  9607. };
  9608. Scene.prototype.enableDepthRenderer = function () {
  9609. if (this._depthRenderer) {
  9610. return this._depthRenderer;
  9611. }
  9612. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9613. return this._depthRenderer;
  9614. };
  9615. Scene.prototype.disableDepthRenderer = function () {
  9616. if (!this._depthRenderer) {
  9617. return;
  9618. }
  9619. this._depthRenderer.dispose();
  9620. this._depthRenderer = null;
  9621. };
  9622. Scene.prototype.dispose = function () {
  9623. this.beforeRender = null;
  9624. this.afterRender = null;
  9625. this.skeletons = [];
  9626. this._boundingBoxRenderer.dispose();
  9627. if (this._depthRenderer) {
  9628. this._depthRenderer.dispose();
  9629. }
  9630. // Debug layer
  9631. this.debugLayer.hide();
  9632. // Events
  9633. if (this.onDispose) {
  9634. this.onDispose();
  9635. }
  9636. this._onBeforeRenderCallbacks = [];
  9637. this._onAfterRenderCallbacks = [];
  9638. this.detachControl();
  9639. // Release sounds & sounds tracks
  9640. this.disposeSounds();
  9641. // Detach cameras
  9642. var canvas = this._engine.getRenderingCanvas();
  9643. var index;
  9644. for (index = 0; index < this.cameras.length; index++) {
  9645. this.cameras[index].detachControl(canvas);
  9646. }
  9647. while (this.lights.length) {
  9648. this.lights[0].dispose();
  9649. }
  9650. while (this.meshes.length) {
  9651. this.meshes[0].dispose(true);
  9652. }
  9653. while (this.cameras.length) {
  9654. this.cameras[0].dispose();
  9655. }
  9656. while (this.materials.length) {
  9657. this.materials[0].dispose();
  9658. }
  9659. while (this.particleSystems.length) {
  9660. this.particleSystems[0].dispose();
  9661. }
  9662. while (this.spriteManagers.length) {
  9663. this.spriteManagers[0].dispose();
  9664. }
  9665. while (this.layers.length) {
  9666. this.layers[0].dispose();
  9667. }
  9668. while (this.textures.length) {
  9669. this.textures[0].dispose();
  9670. }
  9671. // Post-processes
  9672. this.postProcessManager.dispose();
  9673. // Physics
  9674. if (this._physicsEngine) {
  9675. this.disablePhysicsEngine();
  9676. }
  9677. // Remove from engine
  9678. index = this._engine.scenes.indexOf(this);
  9679. if (index > -1) {
  9680. this._engine.scenes.splice(index, 1);
  9681. }
  9682. this._engine.wipeCaches();
  9683. };
  9684. // Release sounds & sounds tracks
  9685. Scene.prototype.disposeSounds = function () {
  9686. this.mainSoundTrack.dispose();
  9687. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9688. this.soundTracks[scIndex].dispose();
  9689. }
  9690. };
  9691. // Collisions
  9692. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9693. if (excludedMesh === void 0) { excludedMesh = null; }
  9694. position.divideToRef(collider.radius, this._scaledPosition);
  9695. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9696. collider.retry = 0;
  9697. collider.initialVelocity = this._scaledVelocity;
  9698. collider.initialPosition = this._scaledPosition;
  9699. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9700. finalPosition.multiplyInPlace(collider.radius);
  9701. };
  9702. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9703. if (excludedMesh === void 0) { excludedMesh = null; }
  9704. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9705. if (collider.retry >= maximumRetry) {
  9706. finalPosition.copyFrom(position);
  9707. return;
  9708. }
  9709. collider._initialize(position, velocity, closeDistance);
  9710. for (var index = 0; index < this.meshes.length; index++) {
  9711. var mesh = this.meshes[index];
  9712. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9713. mesh._checkCollision(collider);
  9714. }
  9715. }
  9716. if (!collider.collisionFound) {
  9717. position.addToRef(velocity, finalPosition);
  9718. return;
  9719. }
  9720. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9721. collider._getResponse(position, velocity);
  9722. }
  9723. if (velocity.length() <= closeDistance) {
  9724. finalPosition.copyFrom(position);
  9725. return;
  9726. }
  9727. collider.retry++;
  9728. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9729. };
  9730. // Octrees
  9731. Scene.prototype.getWorldExtends = function () {
  9732. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9733. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9734. for (var index = 0; index < this.meshes.length; index++) {
  9735. var mesh = this.meshes[index];
  9736. mesh.computeWorldMatrix(true);
  9737. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9738. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9739. BABYLON.Tools.CheckExtends(minBox, min, max);
  9740. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9741. }
  9742. return {
  9743. min: min,
  9744. max: max
  9745. };
  9746. };
  9747. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9748. if (maxCapacity === void 0) { maxCapacity = 64; }
  9749. if (maxDepth === void 0) { maxDepth = 2; }
  9750. if (!this._selectionOctree) {
  9751. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9752. }
  9753. var worldExtends = this.getWorldExtends();
  9754. // Update octree
  9755. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9756. return this._selectionOctree;
  9757. };
  9758. // Picking
  9759. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9760. var engine = this._engine;
  9761. if (!camera) {
  9762. if (!this.activeCamera)
  9763. throw new Error("Active camera not set");
  9764. camera = this.activeCamera;
  9765. }
  9766. var cameraViewport = camera.viewport;
  9767. var viewport = cameraViewport.toGlobal(engine);
  9768. // Moving coordinates to local viewport world
  9769. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9770. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9771. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9772. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9773. };
  9774. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9775. var pickingInfo = null;
  9776. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9777. var mesh = this.meshes[meshIndex];
  9778. if (predicate) {
  9779. if (!predicate(mesh)) {
  9780. continue;
  9781. }
  9782. }
  9783. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9784. continue;
  9785. }
  9786. var world = mesh.getWorldMatrix();
  9787. var ray = rayFunction(world);
  9788. var result = mesh.intersects(ray, fastCheck);
  9789. if (!result || !result.hit)
  9790. continue;
  9791. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9792. continue;
  9793. pickingInfo = result;
  9794. if (fastCheck) {
  9795. break;
  9796. }
  9797. }
  9798. return pickingInfo || new BABYLON.PickingInfo();
  9799. };
  9800. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9801. var _this = this;
  9802. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9803. /// <param name="x">X position on screen</param>
  9804. /// <param name="y">Y position on screen</param>
  9805. /// <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>
  9806. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9807. /// <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>
  9808. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9809. };
  9810. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9811. var _this = this;
  9812. return this._internalPick(function (world) {
  9813. if (!_this._pickWithRayInverseMatrix) {
  9814. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9815. }
  9816. world.invertToRef(_this._pickWithRayInverseMatrix);
  9817. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9818. }, predicate, fastCheck);
  9819. };
  9820. Scene.prototype.setPointerOverMesh = function (mesh) {
  9821. if (this._pointerOverMesh === mesh) {
  9822. return;
  9823. }
  9824. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9825. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9826. }
  9827. this._pointerOverMesh = mesh;
  9828. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9829. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9830. }
  9831. };
  9832. Scene.prototype.getPointerOverMesh = function () {
  9833. return this._pointerOverMesh;
  9834. };
  9835. // Physics
  9836. Scene.prototype.getPhysicsEngine = function () {
  9837. return this._physicsEngine;
  9838. };
  9839. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9840. if (this._physicsEngine) {
  9841. return true;
  9842. }
  9843. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9844. if (!this._physicsEngine.isSupported()) {
  9845. this._physicsEngine = null;
  9846. return false;
  9847. }
  9848. this._physicsEngine._initialize(gravity);
  9849. return true;
  9850. };
  9851. Scene.prototype.disablePhysicsEngine = function () {
  9852. if (!this._physicsEngine) {
  9853. return;
  9854. }
  9855. this._physicsEngine.dispose();
  9856. this._physicsEngine = undefined;
  9857. };
  9858. Scene.prototype.isPhysicsEnabled = function () {
  9859. return this._physicsEngine !== undefined;
  9860. };
  9861. Scene.prototype.setGravity = function (gravity) {
  9862. if (!this._physicsEngine) {
  9863. return;
  9864. }
  9865. this._physicsEngine._setGravity(gravity);
  9866. };
  9867. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9868. if (parts.parts) {
  9869. options = parts;
  9870. parts = parts.parts;
  9871. }
  9872. if (!this._physicsEngine) {
  9873. return null;
  9874. }
  9875. for (var index = 0; index < parts.length; index++) {
  9876. var mesh = parts[index].mesh;
  9877. mesh._physicImpostor = parts[index].impostor;
  9878. mesh._physicsMass = options.mass / parts.length;
  9879. mesh._physicsFriction = options.friction;
  9880. mesh._physicRestitution = options.restitution;
  9881. }
  9882. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9883. };
  9884. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9885. for (var index = 0; index < compound.parts.length; index++) {
  9886. var mesh = compound.parts[index].mesh;
  9887. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9888. this._physicsEngine._unregisterMesh(mesh);
  9889. }
  9890. };
  9891. // Misc.
  9892. Scene.prototype.createDefaultCameraOrLight = function () {
  9893. // Light
  9894. if (this.lights.length === 0) {
  9895. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9896. }
  9897. // Camera
  9898. if (!this.activeCamera) {
  9899. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9900. // Compute position
  9901. var worldExtends = this.getWorldExtends();
  9902. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9903. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9904. camera.setTarget(worldCenter);
  9905. this.activeCamera = camera;
  9906. }
  9907. };
  9908. // Tags
  9909. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9910. if (tagsQuery === undefined) {
  9911. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9912. return list;
  9913. }
  9914. var listByTags = [];
  9915. forEach = forEach || (function (item) {
  9916. return;
  9917. });
  9918. for (var i in list) {
  9919. var item = list[i];
  9920. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9921. listByTags.push(item);
  9922. forEach(item);
  9923. }
  9924. }
  9925. return listByTags;
  9926. };
  9927. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9928. return this._getByTags(this.meshes, tagsQuery, forEach);
  9929. };
  9930. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9931. return this._getByTags(this.cameras, tagsQuery, forEach);
  9932. };
  9933. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9934. return this._getByTags(this.lights, tagsQuery, forEach);
  9935. };
  9936. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9937. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9938. };
  9939. // Statics
  9940. Scene._FOGMODE_NONE = 0;
  9941. Scene._FOGMODE_EXP = 1;
  9942. Scene._FOGMODE_EXP2 = 2;
  9943. Scene._FOGMODE_LINEAR = 3;
  9944. Scene.MinDeltaTime = 1.0;
  9945. Scene.MaxDeltaTime = 1000.0;
  9946. return Scene;
  9947. })();
  9948. BABYLON.Scene = Scene;
  9949. })(BABYLON || (BABYLON = {}));
  9950. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9951. (function (BABYLON) {
  9952. var VertexBuffer = (function () {
  9953. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9954. if (engine instanceof BABYLON.Mesh) {
  9955. this._engine = engine.getScene().getEngine();
  9956. }
  9957. else {
  9958. this._engine = engine;
  9959. }
  9960. this._updatable = updatable;
  9961. this._data = data;
  9962. if (!postponeInternalCreation) {
  9963. this.create();
  9964. }
  9965. this._kind = kind;
  9966. if (stride) {
  9967. this._strideSize = stride;
  9968. return;
  9969. }
  9970. switch (kind) {
  9971. case VertexBuffer.PositionKind:
  9972. this._strideSize = 3;
  9973. break;
  9974. case VertexBuffer.NormalKind:
  9975. this._strideSize = 3;
  9976. break;
  9977. case VertexBuffer.UVKind:
  9978. this._strideSize = 2;
  9979. break;
  9980. case VertexBuffer.UV2Kind:
  9981. this._strideSize = 2;
  9982. break;
  9983. case VertexBuffer.ColorKind:
  9984. this._strideSize = 4;
  9985. break;
  9986. case VertexBuffer.MatricesIndicesKind:
  9987. this._strideSize = 4;
  9988. break;
  9989. case VertexBuffer.MatricesWeightsKind:
  9990. this._strideSize = 4;
  9991. break;
  9992. }
  9993. }
  9994. // Properties
  9995. VertexBuffer.prototype.isUpdatable = function () {
  9996. return this._updatable;
  9997. };
  9998. VertexBuffer.prototype.getData = function () {
  9999. return this._data;
  10000. };
  10001. VertexBuffer.prototype.getBuffer = function () {
  10002. return this._buffer;
  10003. };
  10004. VertexBuffer.prototype.getStrideSize = function () {
  10005. return this._strideSize;
  10006. };
  10007. // Methods
  10008. VertexBuffer.prototype.create = function (data) {
  10009. if (!data && this._buffer) {
  10010. return; // nothing to do
  10011. }
  10012. data = data || this._data;
  10013. if (!this._buffer) {
  10014. if (this._updatable) {
  10015. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  10016. }
  10017. else {
  10018. this._buffer = this._engine.createVertexBuffer(data);
  10019. }
  10020. }
  10021. if (this._updatable) {
  10022. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  10023. this._data = data;
  10024. }
  10025. };
  10026. VertexBuffer.prototype.update = function (data) {
  10027. this.create(data);
  10028. };
  10029. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  10030. if (!this._buffer) {
  10031. return;
  10032. }
  10033. if (this._updatable) {
  10034. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  10035. this._data = null;
  10036. }
  10037. };
  10038. VertexBuffer.prototype.dispose = function () {
  10039. if (!this._buffer) {
  10040. return;
  10041. }
  10042. if (this._engine._releaseBuffer(this._buffer)) {
  10043. this._buffer = null;
  10044. }
  10045. };
  10046. Object.defineProperty(VertexBuffer, "PositionKind", {
  10047. get: function () {
  10048. return VertexBuffer._PositionKind;
  10049. },
  10050. enumerable: true,
  10051. configurable: true
  10052. });
  10053. Object.defineProperty(VertexBuffer, "NormalKind", {
  10054. get: function () {
  10055. return VertexBuffer._NormalKind;
  10056. },
  10057. enumerable: true,
  10058. configurable: true
  10059. });
  10060. Object.defineProperty(VertexBuffer, "UVKind", {
  10061. get: function () {
  10062. return VertexBuffer._UVKind;
  10063. },
  10064. enumerable: true,
  10065. configurable: true
  10066. });
  10067. Object.defineProperty(VertexBuffer, "UV2Kind", {
  10068. get: function () {
  10069. return VertexBuffer._UV2Kind;
  10070. },
  10071. enumerable: true,
  10072. configurable: true
  10073. });
  10074. Object.defineProperty(VertexBuffer, "ColorKind", {
  10075. get: function () {
  10076. return VertexBuffer._ColorKind;
  10077. },
  10078. enumerable: true,
  10079. configurable: true
  10080. });
  10081. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  10082. get: function () {
  10083. return VertexBuffer._MatricesIndicesKind;
  10084. },
  10085. enumerable: true,
  10086. configurable: true
  10087. });
  10088. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  10089. get: function () {
  10090. return VertexBuffer._MatricesWeightsKind;
  10091. },
  10092. enumerable: true,
  10093. configurable: true
  10094. });
  10095. // Enums
  10096. VertexBuffer._PositionKind = "position";
  10097. VertexBuffer._NormalKind = "normal";
  10098. VertexBuffer._UVKind = "uv";
  10099. VertexBuffer._UV2Kind = "uv2";
  10100. VertexBuffer._ColorKind = "color";
  10101. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  10102. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  10103. return VertexBuffer;
  10104. })();
  10105. BABYLON.VertexBuffer = VertexBuffer;
  10106. })(BABYLON || (BABYLON = {}));
  10107. //# sourceMappingURL=babylon.vertexBuffer.js.map
  10108. var BABYLON;
  10109. (function (BABYLON) {
  10110. var AbstractMesh = (function (_super) {
  10111. __extends(AbstractMesh, _super);
  10112. function AbstractMesh(name, scene) {
  10113. _super.call(this, name, scene);
  10114. // Properties
  10115. this.definedFacingForward = true; // orientation for POV movement & rotation
  10116. this.position = new BABYLON.Vector3(0, 0, 0);
  10117. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10118. this.scaling = new BABYLON.Vector3(1, 1, 1);
  10119. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10120. this.visibility = 1.0;
  10121. this.alphaIndex = Number.MAX_VALUE;
  10122. this.infiniteDistance = false;
  10123. this.isVisible = true;
  10124. this.isPickable = true;
  10125. this.showBoundingBox = false;
  10126. this.showSubMeshesBoundingBox = false;
  10127. this.onDispose = null;
  10128. this.checkCollisions = false;
  10129. this.isBlocker = false;
  10130. this.renderingGroupId = 0;
  10131. this.receiveShadows = false;
  10132. this.renderOutline = false;
  10133. this.outlineColor = BABYLON.Color3.Red();
  10134. this.outlineWidth = 0.02;
  10135. this.renderOverlay = false;
  10136. this.overlayColor = BABYLON.Color3.Red();
  10137. this.overlayAlpha = 0.5;
  10138. this.hasVertexAlpha = false;
  10139. this.useVertexColors = true;
  10140. this.applyFog = true;
  10141. this.useOctreeForRenderingSelection = true;
  10142. this.useOctreeForPicking = true;
  10143. this.useOctreeForCollisions = true;
  10144. this.layerMask = 0x0FFFFFFF;
  10145. this.alwaysSelectAsActiveMesh = false;
  10146. // Physics
  10147. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  10148. // Collisions
  10149. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10150. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10151. this._collider = new BABYLON.Collider();
  10152. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10153. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10154. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10155. // Cache
  10156. this._localScaling = BABYLON.Matrix.Zero();
  10157. this._localRotation = BABYLON.Matrix.Zero();
  10158. this._localTranslation = BABYLON.Matrix.Zero();
  10159. this._localBillboard = BABYLON.Matrix.Zero();
  10160. this._localPivotScaling = BABYLON.Matrix.Zero();
  10161. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  10162. this._localWorld = BABYLON.Matrix.Zero();
  10163. this._worldMatrix = BABYLON.Matrix.Zero();
  10164. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10165. this._absolutePosition = BABYLON.Vector3.Zero();
  10166. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10167. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10168. this._isDirty = false;
  10169. this._pivotMatrix = BABYLON.Matrix.Identity();
  10170. this._isDisposed = false;
  10171. this._renderId = 0;
  10172. this._intersectionsInProgress = new Array();
  10173. this._onAfterWorldMatrixUpdate = new Array();
  10174. this._isWorldMatrixFrozen = false;
  10175. scene.addMesh(this);
  10176. }
  10177. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10178. get: function () {
  10179. return AbstractMesh._BILLBOARDMODE_NONE;
  10180. },
  10181. enumerable: true,
  10182. configurable: true
  10183. });
  10184. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10185. get: function () {
  10186. return AbstractMesh._BILLBOARDMODE_X;
  10187. },
  10188. enumerable: true,
  10189. configurable: true
  10190. });
  10191. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10192. get: function () {
  10193. return AbstractMesh._BILLBOARDMODE_Y;
  10194. },
  10195. enumerable: true,
  10196. configurable: true
  10197. });
  10198. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10199. get: function () {
  10200. return AbstractMesh._BILLBOARDMODE_Z;
  10201. },
  10202. enumerable: true,
  10203. configurable: true
  10204. });
  10205. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10206. get: function () {
  10207. return AbstractMesh._BILLBOARDMODE_ALL;
  10208. },
  10209. enumerable: true,
  10210. configurable: true
  10211. });
  10212. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10213. // Methods
  10214. get: function () {
  10215. return false;
  10216. },
  10217. enumerable: true,
  10218. configurable: true
  10219. });
  10220. AbstractMesh.prototype.getLOD = function (camera) {
  10221. return this;
  10222. };
  10223. AbstractMesh.prototype.getTotalVertices = function () {
  10224. return 0;
  10225. };
  10226. AbstractMesh.prototype.getIndices = function () {
  10227. return null;
  10228. };
  10229. AbstractMesh.prototype.getVerticesData = function (kind) {
  10230. return null;
  10231. };
  10232. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10233. return false;
  10234. };
  10235. AbstractMesh.prototype.getBoundingInfo = function () {
  10236. if (this._masterMesh) {
  10237. return this._masterMesh.getBoundingInfo();
  10238. }
  10239. if (!this._boundingInfo) {
  10240. this._updateBoundingInfo();
  10241. }
  10242. return this._boundingInfo;
  10243. };
  10244. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10245. get: function () {
  10246. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10247. },
  10248. enumerable: true,
  10249. configurable: true
  10250. });
  10251. AbstractMesh.prototype._preActivate = function () {
  10252. };
  10253. AbstractMesh.prototype._activate = function (renderId) {
  10254. this._renderId = renderId;
  10255. };
  10256. AbstractMesh.prototype.getWorldMatrix = function () {
  10257. if (this._masterMesh) {
  10258. return this._masterMesh.getWorldMatrix();
  10259. }
  10260. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10261. this.computeWorldMatrix();
  10262. }
  10263. return this._worldMatrix;
  10264. };
  10265. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10266. get: function () {
  10267. return this._worldMatrix;
  10268. },
  10269. enumerable: true,
  10270. configurable: true
  10271. });
  10272. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10273. get: function () {
  10274. return this._absolutePosition;
  10275. },
  10276. enumerable: true,
  10277. configurable: true
  10278. });
  10279. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10280. this.computeWorldMatrix(true);
  10281. this._isWorldMatrixFrozen = true;
  10282. };
  10283. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10284. this.computeWorldMatrix(true);
  10285. this._isWorldMatrixFrozen = false;
  10286. };
  10287. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10288. if (!this.rotationQuaternion) {
  10289. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10290. this.rotation = BABYLON.Vector3.Zero();
  10291. }
  10292. if (!space || space === 0 /* LOCAL */) {
  10293. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10294. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  10295. }
  10296. else {
  10297. if (this.parent) {
  10298. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10299. invertParentWorldMatrix.invert();
  10300. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10301. }
  10302. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10303. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  10304. }
  10305. };
  10306. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10307. var displacementVector = axis.scale(distance);
  10308. if (!space || space === 0 /* LOCAL */) {
  10309. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10310. this.setPositionWithLocalVector(tempV3);
  10311. }
  10312. else {
  10313. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10314. }
  10315. };
  10316. AbstractMesh.prototype.getAbsolutePosition = function () {
  10317. this.computeWorldMatrix();
  10318. return this._absolutePosition;
  10319. };
  10320. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10321. if (!absolutePosition) {
  10322. return;
  10323. }
  10324. var absolutePositionX;
  10325. var absolutePositionY;
  10326. var absolutePositionZ;
  10327. if (absolutePosition.x === undefined) {
  10328. if (arguments.length < 3) {
  10329. return;
  10330. }
  10331. absolutePositionX = arguments[0];
  10332. absolutePositionY = arguments[1];
  10333. absolutePositionZ = arguments[2];
  10334. }
  10335. else {
  10336. absolutePositionX = absolutePosition.x;
  10337. absolutePositionY = absolutePosition.y;
  10338. absolutePositionZ = absolutePosition.z;
  10339. }
  10340. if (this.parent) {
  10341. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10342. invertParentWorldMatrix.invert();
  10343. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10344. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10345. }
  10346. else {
  10347. this.position.x = absolutePositionX;
  10348. this.position.y = absolutePositionY;
  10349. this.position.z = absolutePositionZ;
  10350. }
  10351. };
  10352. // ================================== Point of View Movement =================================
  10353. /**
  10354. * Perform relative position change from the point of view of behind the front of the mesh.
  10355. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10356. * Supports definition of mesh facing forward or backward.
  10357. * @param {number} amountRight
  10358. * @param {number} amountUp
  10359. * @param {number} amountForward
  10360. */
  10361. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10362. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10363. };
  10364. /**
  10365. * Calculate relative position change from the point of view of behind the front of the mesh.
  10366. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10367. * Supports definition of mesh facing forward or backward.
  10368. * @param {number} amountRight
  10369. * @param {number} amountUp
  10370. * @param {number} amountForward
  10371. */
  10372. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10373. var rotMatrix = new BABYLON.Matrix();
  10374. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10375. rotQuaternion.toRotationMatrix(rotMatrix);
  10376. var translationDelta = BABYLON.Vector3.Zero();
  10377. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10378. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10379. return translationDelta;
  10380. };
  10381. // ================================== Point of View Rotation =================================
  10382. /**
  10383. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10384. * Supports definition of mesh facing forward or backward.
  10385. * @param {number} flipBack
  10386. * @param {number} twirlClockwise
  10387. * @param {number} tiltRight
  10388. */
  10389. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10390. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10391. };
  10392. /**
  10393. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10394. * Supports definition of mesh facing forward or backward.
  10395. * @param {number} flipBack
  10396. * @param {number} twirlClockwise
  10397. * @param {number} tiltRight
  10398. */
  10399. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10400. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10401. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10402. };
  10403. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10404. this._pivotMatrix = matrix;
  10405. this._cache.pivotMatrixUpdated = true;
  10406. };
  10407. AbstractMesh.prototype.getPivotMatrix = function () {
  10408. return this._pivotMatrix;
  10409. };
  10410. AbstractMesh.prototype._isSynchronized = function () {
  10411. if (this._isDirty) {
  10412. return false;
  10413. }
  10414. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10415. return false;
  10416. if (this._cache.pivotMatrixUpdated) {
  10417. return false;
  10418. }
  10419. if (this.infiniteDistance) {
  10420. return false;
  10421. }
  10422. if (!this._cache.position.equals(this.position))
  10423. return false;
  10424. if (this.rotationQuaternion) {
  10425. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10426. return false;
  10427. }
  10428. else {
  10429. if (!this._cache.rotation.equals(this.rotation))
  10430. return false;
  10431. }
  10432. if (!this._cache.scaling.equals(this.scaling))
  10433. return false;
  10434. return true;
  10435. };
  10436. AbstractMesh.prototype._initCache = function () {
  10437. _super.prototype._initCache.call(this);
  10438. this._cache.localMatrixUpdated = false;
  10439. this._cache.position = BABYLON.Vector3.Zero();
  10440. this._cache.scaling = BABYLON.Vector3.Zero();
  10441. this._cache.rotation = BABYLON.Vector3.Zero();
  10442. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10443. };
  10444. AbstractMesh.prototype.markAsDirty = function (property) {
  10445. if (property === "rotation") {
  10446. this.rotationQuaternion = null;
  10447. }
  10448. this._currentRenderId = Number.MAX_VALUE;
  10449. this._isDirty = true;
  10450. };
  10451. AbstractMesh.prototype._updateBoundingInfo = function () {
  10452. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10453. this._boundingInfo._update(this.worldMatrixFromCache);
  10454. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10455. };
  10456. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10457. if (!this.subMeshes) {
  10458. return;
  10459. }
  10460. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10461. var subMesh = this.subMeshes[subIndex];
  10462. subMesh.updateBoundingInfo(matrix);
  10463. }
  10464. };
  10465. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10466. if (this._isWorldMatrixFrozen) {
  10467. return this._worldMatrix;
  10468. }
  10469. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10470. return this._worldMatrix;
  10471. }
  10472. this._cache.position.copyFrom(this.position);
  10473. this._cache.scaling.copyFrom(this.scaling);
  10474. this._cache.pivotMatrixUpdated = false;
  10475. this._currentRenderId = this.getScene().getRenderId();
  10476. this._isDirty = false;
  10477. // Scaling
  10478. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  10479. // Rotation
  10480. if (this.rotationQuaternion) {
  10481. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  10482. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10483. }
  10484. else {
  10485. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  10486. this._cache.rotation.copyFrom(this.rotation);
  10487. }
  10488. // Translation
  10489. if (this.infiniteDistance && !this.parent) {
  10490. var camera = this.getScene().activeCamera;
  10491. var cameraWorldMatrix = camera.getWorldMatrix();
  10492. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10493. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  10494. }
  10495. else {
  10496. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  10497. }
  10498. // Composing transformations
  10499. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  10500. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  10501. // Billboarding
  10502. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10503. var localPosition = this.position.clone();
  10504. var zero = this.getScene().activeCamera.globalPosition.clone();
  10505. if (this.parent && this.parent.position) {
  10506. localPosition.addInPlace(this.parent.position);
  10507. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  10508. }
  10509. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  10510. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10511. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  10512. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10513. zero.y = localPosition.y + 0.001;
  10514. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10515. zero.z = localPosition.z + 0.001;
  10516. }
  10517. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  10518. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  10519. this._localBillboard.invert();
  10520. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  10521. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  10522. }
  10523. // Local world
  10524. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  10525. // Parent
  10526. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10527. this._markSyncedWithParent();
  10528. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10529. }
  10530. else {
  10531. this._worldMatrix.copyFrom(this._localWorld);
  10532. }
  10533. // Bounding info
  10534. this._updateBoundingInfo();
  10535. // Absolute position
  10536. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10537. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  10538. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  10539. }
  10540. return this._worldMatrix;
  10541. };
  10542. /**
  10543. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10544. * @param func: callback function to add
  10545. */
  10546. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10547. this._onAfterWorldMatrixUpdate.push(func);
  10548. };
  10549. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10550. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10551. if (index > -1) {
  10552. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10553. }
  10554. };
  10555. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10556. this.computeWorldMatrix();
  10557. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10558. };
  10559. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10560. this.computeWorldMatrix();
  10561. var invLocalWorldMatrix = this._localWorld.clone();
  10562. invLocalWorldMatrix.invert();
  10563. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10564. };
  10565. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10566. this.computeWorldMatrix();
  10567. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10568. };
  10569. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10570. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10571. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10572. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10573. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10574. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10575. /// <returns>Mesh oriented towards targetMesh</returns>
  10576. yawCor = yawCor || 0; // default to zero if undefined
  10577. pitchCor = pitchCor || 0;
  10578. rollCor = rollCor || 0;
  10579. var dv = targetPoint.subtract(this.position);
  10580. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10581. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10582. var pitch = Math.atan2(dv.y, len);
  10583. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10584. };
  10585. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10586. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10587. return false;
  10588. }
  10589. return true;
  10590. };
  10591. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10592. if (!camera) {
  10593. camera = this.getScene().activeCamera;
  10594. }
  10595. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10596. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10597. return false;
  10598. }
  10599. return true;
  10600. };
  10601. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10602. if (!this._boundingInfo || !mesh._boundingInfo) {
  10603. return false;
  10604. }
  10605. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10606. };
  10607. AbstractMesh.prototype.intersectsPoint = function (point) {
  10608. if (!this._boundingInfo) {
  10609. return false;
  10610. }
  10611. return this._boundingInfo.intersectsPoint(point);
  10612. };
  10613. // Physics
  10614. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10615. var physicsEngine = this.getScene().getPhysicsEngine();
  10616. if (!physicsEngine) {
  10617. return;
  10618. }
  10619. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10620. if (impostor.impostor) {
  10621. // Old API
  10622. options = impostor;
  10623. impostor = impostor.impostor;
  10624. }
  10625. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10626. physicsEngine._unregisterMesh(this);
  10627. return;
  10628. }
  10629. if (!options) {
  10630. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10631. }
  10632. else {
  10633. if (!options.mass && options.mass !== 0)
  10634. options.mass = 0;
  10635. if (!options.friction && options.friction !== 0)
  10636. options.friction = 0.2;
  10637. if (!options.restitution && options.restitution !== 0)
  10638. options.restitution = 0.2;
  10639. }
  10640. this._physicImpostor = impostor;
  10641. this._physicsMass = options.mass;
  10642. this._physicsFriction = options.friction;
  10643. this._physicRestitution = options.restitution;
  10644. return physicsEngine._registerMesh(this, impostor, options);
  10645. };
  10646. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10647. if (!this._physicImpostor) {
  10648. return BABYLON.PhysicsEngine.NoImpostor;
  10649. }
  10650. return this._physicImpostor;
  10651. };
  10652. AbstractMesh.prototype.getPhysicsMass = function () {
  10653. if (!this._physicsMass) {
  10654. return 0;
  10655. }
  10656. return this._physicsMass;
  10657. };
  10658. AbstractMesh.prototype.getPhysicsFriction = function () {
  10659. if (!this._physicsFriction) {
  10660. return 0;
  10661. }
  10662. return this._physicsFriction;
  10663. };
  10664. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10665. if (!this._physicRestitution) {
  10666. return 0;
  10667. }
  10668. return this._physicRestitution;
  10669. };
  10670. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10671. if (!camera) {
  10672. camera = this.getScene().activeCamera;
  10673. }
  10674. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10675. };
  10676. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10677. if (!camera) {
  10678. camera = this.getScene().activeCamera;
  10679. }
  10680. return this.absolutePosition.subtract(camera.position).length();
  10681. };
  10682. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10683. if (!this._physicImpostor) {
  10684. return;
  10685. }
  10686. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10687. };
  10688. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10689. if (!this._physicImpostor) {
  10690. return;
  10691. }
  10692. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10693. };
  10694. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10695. if (!this._physicImpostor) {
  10696. return;
  10697. }
  10698. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10699. };
  10700. // Collisions
  10701. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10702. var globalPosition = this.getAbsolutePosition();
  10703. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10704. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10705. this._collider.radius = this.ellipsoid;
  10706. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10707. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10708. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10709. this.position.addInPlace(this._diffPositionForCollisions);
  10710. }
  10711. };
  10712. // Submeshes octree
  10713. /**
  10714. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10715. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10716. */
  10717. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10718. if (maxCapacity === void 0) { maxCapacity = 64; }
  10719. if (maxDepth === void 0) { maxDepth = 2; }
  10720. if (!this._submeshesOctree) {
  10721. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10722. }
  10723. this.computeWorldMatrix(true);
  10724. // Update octree
  10725. var bbox = this.getBoundingInfo().boundingBox;
  10726. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10727. return this._submeshesOctree;
  10728. };
  10729. // Collisions
  10730. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10731. this._generatePointsArray();
  10732. // Transformation
  10733. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10734. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10735. subMesh._lastColliderWorldVertices = [];
  10736. subMesh._trianglePlanes = [];
  10737. var start = subMesh.verticesStart;
  10738. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10739. for (var i = start; i < end; i++) {
  10740. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10741. }
  10742. }
  10743. // Collide
  10744. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10745. };
  10746. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10747. var subMeshes;
  10748. var len;
  10749. // Octrees
  10750. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10751. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10752. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10753. len = intersections.length;
  10754. subMeshes = intersections.data;
  10755. }
  10756. else {
  10757. subMeshes = this.subMeshes;
  10758. len = subMeshes.length;
  10759. }
  10760. for (var index = 0; index < len; index++) {
  10761. var subMesh = subMeshes[index];
  10762. // Bounding test
  10763. if (len > 1 && !subMesh._checkCollision(collider))
  10764. continue;
  10765. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10766. }
  10767. };
  10768. AbstractMesh.prototype._checkCollision = function (collider) {
  10769. // Bounding box test
  10770. if (!this._boundingInfo._checkCollision(collider))
  10771. return;
  10772. // Transformation matrix
  10773. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10774. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10775. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10776. };
  10777. // Picking
  10778. AbstractMesh.prototype._generatePointsArray = function () {
  10779. return false;
  10780. };
  10781. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10782. var pickingInfo = new BABYLON.PickingInfo();
  10783. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10784. return pickingInfo;
  10785. }
  10786. if (!this._generatePointsArray()) {
  10787. return pickingInfo;
  10788. }
  10789. var intersectInfo = null;
  10790. // Octrees
  10791. var subMeshes;
  10792. var len;
  10793. if (this._submeshesOctree && this.useOctreeForPicking) {
  10794. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10795. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10796. len = intersections.length;
  10797. subMeshes = intersections.data;
  10798. }
  10799. else {
  10800. subMeshes = this.subMeshes;
  10801. len = subMeshes.length;
  10802. }
  10803. for (var index = 0; index < len; index++) {
  10804. var subMesh = subMeshes[index];
  10805. // Bounding test
  10806. if (len > 1 && !subMesh.canIntersects(ray))
  10807. continue;
  10808. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10809. if (currentIntersectInfo) {
  10810. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10811. intersectInfo = currentIntersectInfo;
  10812. intersectInfo.subMeshId = index;
  10813. if (fastCheck) {
  10814. break;
  10815. }
  10816. }
  10817. }
  10818. }
  10819. if (intersectInfo) {
  10820. // Get picked point
  10821. var world = this.getWorldMatrix();
  10822. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10823. var direction = ray.direction.clone();
  10824. direction = direction.scale(intersectInfo.distance);
  10825. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10826. var pickedPoint = worldOrigin.add(worldDirection);
  10827. // Return result
  10828. pickingInfo.hit = true;
  10829. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10830. pickingInfo.pickedPoint = pickedPoint;
  10831. pickingInfo.pickedMesh = this;
  10832. pickingInfo.bu = intersectInfo.bu;
  10833. pickingInfo.bv = intersectInfo.bv;
  10834. pickingInfo.faceId = intersectInfo.faceId;
  10835. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10836. return pickingInfo;
  10837. }
  10838. return pickingInfo;
  10839. };
  10840. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10841. return null;
  10842. };
  10843. AbstractMesh.prototype.releaseSubMeshes = function () {
  10844. if (this.subMeshes) {
  10845. while (this.subMeshes.length) {
  10846. this.subMeshes[0].dispose();
  10847. }
  10848. }
  10849. else {
  10850. this.subMeshes = new Array();
  10851. }
  10852. };
  10853. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10854. var index;
  10855. // Physics
  10856. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  10857. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10858. }
  10859. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10860. var other = this._intersectionsInProgress[index];
  10861. var pos = other._intersectionsInProgress.indexOf(this);
  10862. other._intersectionsInProgress.splice(pos, 1);
  10863. }
  10864. this._intersectionsInProgress = [];
  10865. // SubMeshes
  10866. this.releaseSubMeshes();
  10867. // Remove from scene
  10868. this.getScene().removeMesh(this);
  10869. if (!doNotRecurse) {
  10870. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10871. if (this.getScene().particleSystems[index].emitter === this) {
  10872. this.getScene().particleSystems[index].dispose();
  10873. index--;
  10874. }
  10875. }
  10876. // Children
  10877. var objects = this.getScene().meshes.slice(0);
  10878. for (index = 0; index < objects.length; index++) {
  10879. if (objects[index].parent === this) {
  10880. objects[index].dispose();
  10881. }
  10882. }
  10883. }
  10884. else {
  10885. for (index = 0; index < this.getScene().meshes.length; index++) {
  10886. var obj = this.getScene().meshes[index];
  10887. if (obj.parent === this) {
  10888. obj.parent = null;
  10889. obj.computeWorldMatrix(true);
  10890. }
  10891. }
  10892. }
  10893. this._onAfterWorldMatrixUpdate = [];
  10894. this._isDisposed = true;
  10895. // Callback
  10896. if (this.onDispose) {
  10897. this.onDispose();
  10898. }
  10899. };
  10900. // Statics
  10901. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10902. AbstractMesh._BILLBOARDMODE_X = 1;
  10903. AbstractMesh._BILLBOARDMODE_Y = 2;
  10904. AbstractMesh._BILLBOARDMODE_Z = 4;
  10905. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10906. return AbstractMesh;
  10907. })(BABYLON.Node);
  10908. BABYLON.AbstractMesh = AbstractMesh;
  10909. })(BABYLON || (BABYLON = {}));
  10910. //# sourceMappingURL=babylon.abstractMesh.js.map
  10911. var BABYLON;
  10912. (function (BABYLON) {
  10913. var _InstancesBatch = (function () {
  10914. function _InstancesBatch() {
  10915. this.mustReturn = false;
  10916. this.visibleInstances = new Array();
  10917. this.renderSelf = new Array();
  10918. }
  10919. return _InstancesBatch;
  10920. })();
  10921. BABYLON._InstancesBatch = _InstancesBatch;
  10922. var Mesh = (function (_super) {
  10923. __extends(Mesh, _super);
  10924. /**
  10925. * @constructor
  10926. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10927. * @param {Scene} scene - The scene to add this mesh to.
  10928. * @param {Node} parent - The parent of this mesh, if it has one
  10929. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10930. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10931. * When false, achieved by calling a clone(), also passing False.
  10932. * This will make creation of children, recursive.
  10933. */
  10934. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10935. if (parent === void 0) { parent = null; }
  10936. _super.call(this, name, scene);
  10937. // Members
  10938. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10939. this.instances = new Array();
  10940. this._LODLevels = new Array();
  10941. this._onBeforeRenderCallbacks = new Array();
  10942. this._onAfterRenderCallbacks = new Array();
  10943. this._visibleInstances = {};
  10944. this._renderIdForInstances = new Array();
  10945. this._batchCache = new _InstancesBatch();
  10946. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10947. this._sideOrientation = Mesh._DEFAULTSIDE;
  10948. if (source) {
  10949. // Geometry
  10950. if (source._geometry) {
  10951. source._geometry.applyToMesh(this);
  10952. }
  10953. // Deep copy
  10954. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  10955. // Material
  10956. this.material = source.material;
  10957. if (!doNotCloneChildren) {
  10958. for (var index = 0; index < scene.meshes.length; index++) {
  10959. var mesh = scene.meshes[index];
  10960. if (mesh.parent === source) {
  10961. // doNotCloneChildren is always going to be False
  10962. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10963. }
  10964. }
  10965. }
  10966. for (index = 0; index < scene.particleSystems.length; index++) {
  10967. var system = scene.particleSystems[index];
  10968. if (system.emitter === source) {
  10969. system.clone(system.name, this);
  10970. }
  10971. }
  10972. this.computeWorldMatrix(true);
  10973. }
  10974. // Parent
  10975. if (parent !== null) {
  10976. this.parent = parent;
  10977. }
  10978. }
  10979. Object.defineProperty(Mesh, "FRONTSIDE", {
  10980. get: function () {
  10981. return Mesh._FRONTSIDE;
  10982. },
  10983. enumerable: true,
  10984. configurable: true
  10985. });
  10986. Object.defineProperty(Mesh, "BACKSIDE", {
  10987. get: function () {
  10988. return Mesh._BACKSIDE;
  10989. },
  10990. enumerable: true,
  10991. configurable: true
  10992. });
  10993. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10994. get: function () {
  10995. return Mesh._DOUBLESIDE;
  10996. },
  10997. enumerable: true,
  10998. configurable: true
  10999. });
  11000. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  11001. get: function () {
  11002. return Mesh._DEFAULTSIDE;
  11003. },
  11004. enumerable: true,
  11005. configurable: true
  11006. });
  11007. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  11008. // Methods
  11009. get: function () {
  11010. return this._LODLevels.length > 0;
  11011. },
  11012. enumerable: true,
  11013. configurable: true
  11014. });
  11015. Mesh.prototype._sortLODLevels = function () {
  11016. this._LODLevels.sort(function (a, b) {
  11017. if (a.distance < b.distance) {
  11018. return 1;
  11019. }
  11020. if (a.distance > b.distance) {
  11021. return -1;
  11022. }
  11023. return 0;
  11024. });
  11025. };
  11026. /**
  11027. * Add a mesh as LOD level triggered at the given distance.
  11028. * @param {number} distance - the distance from the center of the object to show this level
  11029. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  11030. * @return {BABYLON.Mesh} this mesh (for chaining)
  11031. */
  11032. Mesh.prototype.addLODLevel = function (distance, mesh) {
  11033. if (mesh && mesh._masterMesh) {
  11034. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  11035. return this;
  11036. }
  11037. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  11038. this._LODLevels.push(level);
  11039. if (mesh) {
  11040. mesh._masterMesh = this;
  11041. }
  11042. this._sortLODLevels();
  11043. return this;
  11044. };
  11045. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  11046. for (var index = 0; index < this._LODLevels.length; index++) {
  11047. var level = this._LODLevels[index];
  11048. if (level.distance === distance) {
  11049. return level.mesh;
  11050. }
  11051. }
  11052. return null;
  11053. };
  11054. /**
  11055. * Remove a mesh from the LOD array
  11056. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  11057. * @return {BABYLON.Mesh} this mesh (for chaining)
  11058. */
  11059. Mesh.prototype.removeLODLevel = function (mesh) {
  11060. for (var index = 0; index < this._LODLevels.length; index++) {
  11061. if (this._LODLevels[index].mesh === mesh) {
  11062. this._LODLevels.splice(index, 1);
  11063. if (mesh) {
  11064. mesh._masterMesh = null;
  11065. }
  11066. }
  11067. }
  11068. this._sortLODLevels();
  11069. return this;
  11070. };
  11071. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  11072. if (!this._LODLevels || this._LODLevels.length === 0) {
  11073. return this;
  11074. }
  11075. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  11076. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  11077. if (this.onLODLevelSelection) {
  11078. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  11079. }
  11080. return this;
  11081. }
  11082. for (var index = 0; index < this._LODLevels.length; index++) {
  11083. var level = this._LODLevels[index];
  11084. if (level.distance < distanceToCamera) {
  11085. if (level.mesh) {
  11086. level.mesh._preActivate();
  11087. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11088. }
  11089. if (this.onLODLevelSelection) {
  11090. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  11091. }
  11092. return level.mesh;
  11093. }
  11094. }
  11095. if (this.onLODLevelSelection) {
  11096. this.onLODLevelSelection(distanceToCamera, this, this);
  11097. }
  11098. return this;
  11099. };
  11100. Object.defineProperty(Mesh.prototype, "geometry", {
  11101. get: function () {
  11102. return this._geometry;
  11103. },
  11104. enumerable: true,
  11105. configurable: true
  11106. });
  11107. Mesh.prototype.getTotalVertices = function () {
  11108. if (!this._geometry) {
  11109. return 0;
  11110. }
  11111. return this._geometry.getTotalVertices();
  11112. };
  11113. Mesh.prototype.getVerticesData = function (kind) {
  11114. if (!this._geometry) {
  11115. return null;
  11116. }
  11117. return this._geometry.getVerticesData(kind);
  11118. };
  11119. Mesh.prototype.getVertexBuffer = function (kind) {
  11120. if (!this._geometry) {
  11121. return undefined;
  11122. }
  11123. return this._geometry.getVertexBuffer(kind);
  11124. };
  11125. Mesh.prototype.isVerticesDataPresent = function (kind) {
  11126. if (!this._geometry) {
  11127. if (this._delayInfo) {
  11128. return this._delayInfo.indexOf(kind) !== -1;
  11129. }
  11130. return false;
  11131. }
  11132. return this._geometry.isVerticesDataPresent(kind);
  11133. };
  11134. Mesh.prototype.getVerticesDataKinds = function () {
  11135. if (!this._geometry) {
  11136. var result = [];
  11137. if (this._delayInfo) {
  11138. for (var kind in this._delayInfo) {
  11139. result.push(kind);
  11140. }
  11141. }
  11142. return result;
  11143. }
  11144. return this._geometry.getVerticesDataKinds();
  11145. };
  11146. Mesh.prototype.getTotalIndices = function () {
  11147. if (!this._geometry) {
  11148. return 0;
  11149. }
  11150. return this._geometry.getTotalIndices();
  11151. };
  11152. Mesh.prototype.getIndices = function () {
  11153. if (!this._geometry) {
  11154. return [];
  11155. }
  11156. return this._geometry.getIndices();
  11157. };
  11158. Object.defineProperty(Mesh.prototype, "isBlocked", {
  11159. get: function () {
  11160. return this._masterMesh !== null && this._masterMesh !== undefined;
  11161. },
  11162. enumerable: true,
  11163. configurable: true
  11164. });
  11165. Mesh.prototype.isReady = function () {
  11166. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11167. return false;
  11168. }
  11169. return _super.prototype.isReady.call(this);
  11170. };
  11171. Mesh.prototype.isDisposed = function () {
  11172. return this._isDisposed;
  11173. };
  11174. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  11175. get: function () {
  11176. return this._sideOrientation;
  11177. },
  11178. set: function (sideO) {
  11179. this._sideOrientation = sideO;
  11180. },
  11181. enumerable: true,
  11182. configurable: true
  11183. });
  11184. // Methods
  11185. Mesh.prototype._preActivate = function () {
  11186. var sceneRenderId = this.getScene().getRenderId();
  11187. if (this._preActivateId === sceneRenderId) {
  11188. return;
  11189. }
  11190. this._preActivateId = sceneRenderId;
  11191. this._visibleInstances = null;
  11192. };
  11193. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  11194. if (!this._visibleInstances) {
  11195. this._visibleInstances = {};
  11196. this._visibleInstances.defaultRenderId = renderId;
  11197. this._visibleInstances.selfDefaultRenderId = this._renderId;
  11198. }
  11199. if (!this._visibleInstances[renderId]) {
  11200. this._visibleInstances[renderId] = new Array();
  11201. }
  11202. this._visibleInstances[renderId].push(instance);
  11203. };
  11204. Mesh.prototype.refreshBoundingInfo = function () {
  11205. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11206. if (data) {
  11207. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  11208. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11209. }
  11210. if (this.subMeshes) {
  11211. for (var index = 0; index < this.subMeshes.length; index++) {
  11212. this.subMeshes[index].refreshBoundingInfo();
  11213. }
  11214. }
  11215. this._updateBoundingInfo();
  11216. };
  11217. Mesh.prototype._createGlobalSubMesh = function () {
  11218. var totalVertices = this.getTotalVertices();
  11219. if (!totalVertices || !this.getIndices()) {
  11220. return null;
  11221. }
  11222. this.releaseSubMeshes();
  11223. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  11224. };
  11225. Mesh.prototype.subdivide = function (count) {
  11226. if (count < 1) {
  11227. return;
  11228. }
  11229. var totalIndices = this.getTotalIndices();
  11230. var subdivisionSize = (totalIndices / count) | 0;
  11231. var offset = 0;
  11232. while (subdivisionSize % 3 !== 0) {
  11233. subdivisionSize++;
  11234. }
  11235. this.releaseSubMeshes();
  11236. for (var index = 0; index < count; index++) {
  11237. if (offset >= totalIndices) {
  11238. break;
  11239. }
  11240. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  11241. offset += subdivisionSize;
  11242. }
  11243. this.synchronizeInstances();
  11244. };
  11245. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11246. if (kind instanceof Array) {
  11247. var temp = data;
  11248. data = kind;
  11249. kind = temp;
  11250. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  11251. }
  11252. if (!this._geometry) {
  11253. var vertexData = new BABYLON.VertexData();
  11254. vertexData.set(data, kind);
  11255. var scene = this.getScene();
  11256. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  11257. }
  11258. else {
  11259. this._geometry.setVerticesData(kind, data, updatable, stride);
  11260. }
  11261. };
  11262. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11263. if (!this._geometry) {
  11264. return;
  11265. }
  11266. if (!makeItUnique) {
  11267. this._geometry.updateVerticesData(kind, data, updateExtends);
  11268. }
  11269. else {
  11270. this.makeGeometryUnique();
  11271. this.updateVerticesData(kind, data, updateExtends, false);
  11272. }
  11273. };
  11274. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  11275. if (!this._geometry) {
  11276. return;
  11277. }
  11278. if (!makeItUnique) {
  11279. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  11280. }
  11281. else {
  11282. this.makeGeometryUnique();
  11283. this.updateVerticesDataDirectly(kind, data, offset, false);
  11284. }
  11285. };
  11286. // Mesh positions update function :
  11287. // updates the mesh positions according to the positionFunction returned values.
  11288. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  11289. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  11290. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  11291. if (computeNormals === void 0) { computeNormals = true; }
  11292. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11293. positionFunction(positions);
  11294. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  11295. if (computeNormals) {
  11296. var indices = this.getIndices();
  11297. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11298. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  11299. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  11300. }
  11301. };
  11302. Mesh.prototype.makeGeometryUnique = function () {
  11303. if (!this._geometry) {
  11304. return;
  11305. }
  11306. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  11307. geometry.applyToMesh(this);
  11308. };
  11309. Mesh.prototype.setIndices = function (indices, totalVertices) {
  11310. if (!this._geometry) {
  11311. var vertexData = new BABYLON.VertexData();
  11312. vertexData.indices = indices;
  11313. var scene = this.getScene();
  11314. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  11315. }
  11316. else {
  11317. this._geometry.setIndices(indices, totalVertices);
  11318. }
  11319. };
  11320. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  11321. var engine = this.getScene().getEngine();
  11322. // Wireframe
  11323. var indexToBind;
  11324. switch (fillMode) {
  11325. case BABYLON.Material.PointFillMode:
  11326. indexToBind = null;
  11327. break;
  11328. case BABYLON.Material.WireFrameFillMode:
  11329. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  11330. break;
  11331. default:
  11332. case BABYLON.Material.TriangleFillMode:
  11333. indexToBind = this._geometry.getIndexBuffer();
  11334. break;
  11335. }
  11336. // VBOs
  11337. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  11338. };
  11339. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  11340. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11341. return;
  11342. }
  11343. var engine = this.getScene().getEngine();
  11344. switch (fillMode) {
  11345. case BABYLON.Material.PointFillMode:
  11346. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  11347. break;
  11348. case BABYLON.Material.WireFrameFillMode:
  11349. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  11350. break;
  11351. default:
  11352. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  11353. }
  11354. };
  11355. Mesh.prototype.registerBeforeRender = function (func) {
  11356. this._onBeforeRenderCallbacks.push(func);
  11357. };
  11358. Mesh.prototype.unregisterBeforeRender = function (func) {
  11359. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11360. if (index > -1) {
  11361. this._onBeforeRenderCallbacks.splice(index, 1);
  11362. }
  11363. };
  11364. Mesh.prototype.registerAfterRender = function (func) {
  11365. this._onAfterRenderCallbacks.push(func);
  11366. };
  11367. Mesh.prototype.unregisterAfterRender = function (func) {
  11368. var index = this._onAfterRenderCallbacks.indexOf(func);
  11369. if (index > -1) {
  11370. this._onAfterRenderCallbacks.splice(index, 1);
  11371. }
  11372. };
  11373. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  11374. var scene = this.getScene();
  11375. this._batchCache.mustReturn = false;
  11376. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  11377. this._batchCache.visibleInstances[subMeshId] = null;
  11378. if (this._visibleInstances) {
  11379. var currentRenderId = scene.getRenderId();
  11380. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  11381. var selfRenderId = this._renderId;
  11382. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  11383. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  11384. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  11385. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  11386. }
  11387. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  11388. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  11389. this._batchCache.mustReturn = true;
  11390. return this._batchCache;
  11391. }
  11392. if (currentRenderId !== selfRenderId) {
  11393. this._batchCache.renderSelf[subMeshId] = false;
  11394. }
  11395. }
  11396. this._renderIdForInstances[subMeshId] = currentRenderId;
  11397. }
  11398. return this._batchCache;
  11399. };
  11400. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  11401. var visibleInstances = batch.visibleInstances[subMesh._id];
  11402. var matricesCount = visibleInstances.length + 1;
  11403. var bufferSize = matricesCount * 16 * 4;
  11404. while (this._instancesBufferSize < bufferSize) {
  11405. this._instancesBufferSize *= 2;
  11406. }
  11407. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  11408. if (this._worldMatricesInstancesBuffer) {
  11409. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11410. }
  11411. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  11412. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  11413. }
  11414. var offset = 0;
  11415. var instancesCount = 0;
  11416. var world = this.getWorldMatrix();
  11417. if (batch.renderSelf[subMesh._id]) {
  11418. world.copyToArray(this._worldMatricesInstancesArray, offset);
  11419. offset += 16;
  11420. instancesCount++;
  11421. }
  11422. if (visibleInstances) {
  11423. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  11424. var instance = visibleInstances[instanceIndex];
  11425. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  11426. offset += 16;
  11427. instancesCount++;
  11428. }
  11429. }
  11430. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  11431. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  11432. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  11433. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  11434. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  11435. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  11436. this._draw(subMesh, fillMode, instancesCount);
  11437. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  11438. };
  11439. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  11440. var scene = this.getScene();
  11441. var engine = scene.getEngine();
  11442. if (hardwareInstancedRendering) {
  11443. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  11444. }
  11445. else {
  11446. if (batch.renderSelf[subMesh._id]) {
  11447. // Draw
  11448. if (onBeforeDraw) {
  11449. onBeforeDraw(false, this.getWorldMatrix());
  11450. }
  11451. this._draw(subMesh, fillMode);
  11452. }
  11453. if (batch.visibleInstances[subMesh._id]) {
  11454. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  11455. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  11456. // World
  11457. var world = instance.getWorldMatrix();
  11458. if (onBeforeDraw) {
  11459. onBeforeDraw(true, world);
  11460. }
  11461. // Draw
  11462. this._draw(subMesh, fillMode);
  11463. }
  11464. }
  11465. }
  11466. };
  11467. Mesh.prototype.render = function (subMesh) {
  11468. var scene = this.getScene();
  11469. // Managing instances
  11470. var batch = this._getInstancesRenderList(subMesh._id);
  11471. if (batch.mustReturn) {
  11472. return;
  11473. }
  11474. // Checking geometry state
  11475. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11476. return;
  11477. }
  11478. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  11479. this._onBeforeRenderCallbacks[callbackIndex](this);
  11480. }
  11481. var engine = scene.getEngine();
  11482. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11483. // Material
  11484. var effectiveMaterial = subMesh.getMaterial();
  11485. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  11486. return;
  11487. }
  11488. // Outline - step 1
  11489. var savedDepthWrite = engine.getDepthWrite();
  11490. if (this.renderOutline) {
  11491. engine.setDepthWrite(false);
  11492. scene.getOutlineRenderer().render(subMesh, batch);
  11493. engine.setDepthWrite(savedDepthWrite);
  11494. }
  11495. effectiveMaterial._preBind();
  11496. var effect = effectiveMaterial.getEffect();
  11497. // Bind
  11498. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  11499. this._bind(subMesh, effect, fillMode);
  11500. var world = this.getWorldMatrix();
  11501. effectiveMaterial.bind(world, this);
  11502. // Draw
  11503. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  11504. if (isInstance) {
  11505. effectiveMaterial.bindOnlyWorldMatrix(world);
  11506. }
  11507. });
  11508. // Unbind
  11509. effectiveMaterial.unbind();
  11510. // Outline - step 2
  11511. if (this.renderOutline && savedDepthWrite) {
  11512. engine.setDepthWrite(true);
  11513. engine.setColorWrite(false);
  11514. scene.getOutlineRenderer().render(subMesh, batch);
  11515. engine.setColorWrite(true);
  11516. }
  11517. // Overlay
  11518. if (this.renderOverlay) {
  11519. var currentMode = engine.getAlphaMode();
  11520. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11521. scene.getOutlineRenderer().render(subMesh, batch, true);
  11522. engine.setAlphaMode(currentMode);
  11523. }
  11524. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  11525. this._onAfterRenderCallbacks[callbackIndex](this);
  11526. }
  11527. };
  11528. Mesh.prototype.getEmittedParticleSystems = function () {
  11529. var results = new Array();
  11530. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11531. var particleSystem = this.getScene().particleSystems[index];
  11532. if (particleSystem.emitter === this) {
  11533. results.push(particleSystem);
  11534. }
  11535. }
  11536. return results;
  11537. };
  11538. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  11539. var results = new Array();
  11540. var descendants = this.getDescendants();
  11541. descendants.push(this);
  11542. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11543. var particleSystem = this.getScene().particleSystems[index];
  11544. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  11545. results.push(particleSystem);
  11546. }
  11547. }
  11548. return results;
  11549. };
  11550. Mesh.prototype.getChildren = function () {
  11551. var results = [];
  11552. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11553. var mesh = this.getScene().meshes[index];
  11554. if (mesh.parent === this) {
  11555. results.push(mesh);
  11556. }
  11557. }
  11558. return results;
  11559. };
  11560. Mesh.prototype._checkDelayState = function () {
  11561. var _this = this;
  11562. var that = this;
  11563. var scene = this.getScene();
  11564. if (this._geometry) {
  11565. this._geometry.load(scene);
  11566. }
  11567. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11568. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  11569. scene._addPendingData(that);
  11570. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  11571. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  11572. if (data instanceof ArrayBuffer) {
  11573. _this._delayLoadingFunction(data, _this);
  11574. }
  11575. else {
  11576. _this._delayLoadingFunction(JSON.parse(data), _this);
  11577. }
  11578. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11579. scene._removePendingData(_this);
  11580. }, function () {
  11581. }, scene.database, getBinaryData);
  11582. }
  11583. };
  11584. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11585. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11586. return false;
  11587. }
  11588. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11589. return false;
  11590. }
  11591. this._checkDelayState();
  11592. return true;
  11593. };
  11594. Mesh.prototype.setMaterialByID = function (id) {
  11595. var materials = this.getScene().materials;
  11596. for (var index = 0; index < materials.length; index++) {
  11597. if (materials[index].id === id) {
  11598. this.material = materials[index];
  11599. return;
  11600. }
  11601. }
  11602. // Multi
  11603. var multiMaterials = this.getScene().multiMaterials;
  11604. for (index = 0; index < multiMaterials.length; index++) {
  11605. if (multiMaterials[index].id === id) {
  11606. this.material = multiMaterials[index];
  11607. return;
  11608. }
  11609. }
  11610. };
  11611. Mesh.prototype.getAnimatables = function () {
  11612. var results = [];
  11613. if (this.material) {
  11614. results.push(this.material);
  11615. }
  11616. if (this.skeleton) {
  11617. results.push(this.skeleton);
  11618. }
  11619. return results;
  11620. };
  11621. // Geometry
  11622. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11623. // Position
  11624. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11625. return;
  11626. }
  11627. this._resetPointsArrayCache();
  11628. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11629. var temp = [];
  11630. for (var index = 0; index < data.length; index += 3) {
  11631. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11632. }
  11633. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11634. // Normals
  11635. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11636. return;
  11637. }
  11638. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11639. temp = [];
  11640. for (index = 0; index < data.length; index += 3) {
  11641. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11642. }
  11643. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11644. };
  11645. // Cache
  11646. Mesh.prototype._resetPointsArrayCache = function () {
  11647. this._positions = null;
  11648. };
  11649. Mesh.prototype._generatePointsArray = function () {
  11650. if (this._positions)
  11651. return true;
  11652. this._positions = [];
  11653. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11654. if (!data) {
  11655. return false;
  11656. }
  11657. for (var index = 0; index < data.length; index += 3) {
  11658. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11659. }
  11660. return true;
  11661. };
  11662. // Clone
  11663. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11664. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11665. };
  11666. // Dispose
  11667. Mesh.prototype.dispose = function (doNotRecurse) {
  11668. if (this._geometry) {
  11669. this._geometry.releaseForMesh(this, true);
  11670. }
  11671. // Instances
  11672. if (this._worldMatricesInstancesBuffer) {
  11673. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11674. this._worldMatricesInstancesBuffer = null;
  11675. }
  11676. while (this.instances.length) {
  11677. this.instances[0].dispose();
  11678. }
  11679. _super.prototype.dispose.call(this, doNotRecurse);
  11680. };
  11681. // Geometric tools
  11682. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11683. var _this = this;
  11684. var scene = this.getScene();
  11685. var onload = function (img) {
  11686. // Getting height map data
  11687. var canvas = document.createElement("canvas");
  11688. var context = canvas.getContext("2d");
  11689. var heightMapWidth = img.width;
  11690. var heightMapHeight = img.height;
  11691. canvas.width = heightMapWidth;
  11692. canvas.height = heightMapHeight;
  11693. context.drawImage(img, 0, 0);
  11694. // Create VertexData from map data
  11695. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11696. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11697. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11698. //execute success callback, if set
  11699. if (onSuccess) {
  11700. onSuccess(_this);
  11701. }
  11702. };
  11703. BABYLON.Tools.LoadImage(url, onload, function () {
  11704. }, scene.database);
  11705. };
  11706. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11707. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11708. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11709. return;
  11710. }
  11711. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11712. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11713. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11714. var position = BABYLON.Vector3.Zero();
  11715. var normal = BABYLON.Vector3.Zero();
  11716. var uv = BABYLON.Vector2.Zero();
  11717. for (var index = 0; index < positions.length; index += 3) {
  11718. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11719. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11720. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11721. // Compute height
  11722. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11723. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11724. var pos = (u + v * heightMapWidth) * 4;
  11725. var r = buffer[pos] / 255.0;
  11726. var g = buffer[pos + 1] / 255.0;
  11727. var b = buffer[pos + 2] / 255.0;
  11728. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11729. normal.normalize();
  11730. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11731. position = position.add(normal);
  11732. position.toArray(positions, index);
  11733. }
  11734. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11735. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11736. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11737. };
  11738. Mesh.prototype.convertToFlatShadedMesh = function () {
  11739. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11740. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11741. var kinds = this.getVerticesDataKinds();
  11742. var vbs = [];
  11743. var data = [];
  11744. var newdata = [];
  11745. var updatableNormals = false;
  11746. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11747. var kind = kinds[kindIndex];
  11748. var vertexBuffer = this.getVertexBuffer(kind);
  11749. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11750. updatableNormals = vertexBuffer.isUpdatable();
  11751. kinds.splice(kindIndex, 1);
  11752. kindIndex--;
  11753. continue;
  11754. }
  11755. vbs[kind] = vertexBuffer;
  11756. data[kind] = vbs[kind].getData();
  11757. newdata[kind] = [];
  11758. }
  11759. // Save previous submeshes
  11760. var previousSubmeshes = this.subMeshes.slice(0);
  11761. var indices = this.getIndices();
  11762. var totalIndices = this.getTotalIndices();
  11763. for (var index = 0; index < totalIndices; index++) {
  11764. var vertexIndex = indices[index];
  11765. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11766. kind = kinds[kindIndex];
  11767. var stride = vbs[kind].getStrideSize();
  11768. for (var offset = 0; offset < stride; offset++) {
  11769. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11770. }
  11771. }
  11772. }
  11773. // Updating faces & normal
  11774. var normals = [];
  11775. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11776. for (index = 0; index < totalIndices; index += 3) {
  11777. indices[index] = index;
  11778. indices[index + 1] = index + 1;
  11779. indices[index + 2] = index + 2;
  11780. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11781. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11782. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11783. var p1p2 = p1.subtract(p2);
  11784. var p3p2 = p3.subtract(p2);
  11785. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11786. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11787. normals.push(normal.x);
  11788. normals.push(normal.y);
  11789. normals.push(normal.z);
  11790. }
  11791. }
  11792. this.setIndices(indices);
  11793. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11794. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11795. kind = kinds[kindIndex];
  11796. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11797. }
  11798. // Updating submeshes
  11799. this.releaseSubMeshes();
  11800. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11801. var previousOne = previousSubmeshes[submeshIndex];
  11802. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11803. }
  11804. this.synchronizeInstances();
  11805. };
  11806. // Instances
  11807. Mesh.prototype.createInstance = function (name) {
  11808. return new BABYLON.InstancedMesh(name, this);
  11809. };
  11810. Mesh.prototype.synchronizeInstances = function () {
  11811. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11812. var instance = this.instances[instanceIndex];
  11813. instance._syncSubMeshes();
  11814. }
  11815. };
  11816. /**
  11817. * Simplify the mesh according to the given array of settings.
  11818. * Function will return immediately and will simplify async.
  11819. * @param settings a collection of simplification settings.
  11820. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11821. * @param type the type of simplification to run.
  11822. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  11823. */
  11824. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11825. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11826. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11827. this.getScene().simplificationQueue.addTask({
  11828. settings: settings,
  11829. parallelProcessing: parallelProcessing,
  11830. mesh: this,
  11831. simplificationType: simplificationType,
  11832. successCallback: successCallback
  11833. });
  11834. };
  11835. /**
  11836. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  11837. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  11838. * This should be used together with the simplification to avoid disappearing triangles.
  11839. * @param successCallback an optional success callback to be called after the optimization finished.
  11840. */
  11841. Mesh.prototype.optimizeIndices = function (successCallback) {
  11842. var _this = this;
  11843. var indices = this.getIndices();
  11844. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11845. var vectorPositions = [];
  11846. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  11847. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  11848. }
  11849. var dupes = [];
  11850. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  11851. var realPos = vectorPositions.length - 1 - iteration;
  11852. var testedPosition = vectorPositions[realPos];
  11853. for (var j = 0; j < realPos; ++j) {
  11854. var againstPosition = vectorPositions[j];
  11855. if (testedPosition.equals(againstPosition)) {
  11856. dupes[realPos] = j;
  11857. break;
  11858. }
  11859. }
  11860. }, function () {
  11861. for (var i = 0; i < indices.length; ++i) {
  11862. indices[i] = dupes[indices[i]] || indices[i];
  11863. }
  11864. //indices are now reordered
  11865. var originalSubMeshes = _this.subMeshes.slice(0);
  11866. _this.setIndices(indices);
  11867. _this.subMeshes = originalSubMeshes;
  11868. if (successCallback) {
  11869. successCallback(_this);
  11870. }
  11871. });
  11872. };
  11873. // Statics
  11874. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  11875. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11876. if (ribbonInstance === void 0) { ribbonInstance = null; }
  11877. if (ribbonInstance) {
  11878. // positionFunction : ribbon case
  11879. // only pathArray and sideOrientation parameters are taken into account for positions update
  11880. var positionsOfRibbon = function (pathArray, sideOrientation) {
  11881. var positionFunction = function (positions) {
  11882. var minlg = pathArray[0].length;
  11883. var i = 0;
  11884. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  11885. for (var si = 1; si <= ns; si++) {
  11886. for (var p = 0; p < pathArray.length; p++) {
  11887. var path = pathArray[p];
  11888. var l = path.length;
  11889. minlg = (minlg < l) ? minlg : l;
  11890. var j = 0;
  11891. while (j < minlg) {
  11892. positions[i] = path[j].x;
  11893. positions[i + 1] = path[j].y;
  11894. positions[i + 2] = path[j].z;
  11895. j++;
  11896. i += 3;
  11897. }
  11898. }
  11899. }
  11900. };
  11901. return positionFunction;
  11902. };
  11903. var sideOrientation = ribbonInstance.sideOrientation;
  11904. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  11905. ribbonInstance.updateMeshPositions(positionFunction, true);
  11906. return ribbonInstance;
  11907. }
  11908. else {
  11909. var ribbon = new Mesh(name, scene);
  11910. ribbon.sideOrientation = sideOrientation;
  11911. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11912. vertexData.applyToMesh(ribbon, updatable);
  11913. return ribbon;
  11914. }
  11915. };
  11916. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  11917. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11918. var disc = new Mesh(name, scene);
  11919. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  11920. vertexData.applyToMesh(disc, updatable);
  11921. return disc;
  11922. };
  11923. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11924. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11925. var box = new Mesh(name, scene);
  11926. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11927. vertexData.applyToMesh(box, updatable);
  11928. return box;
  11929. };
  11930. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11931. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11932. var sphere = new Mesh(name, scene);
  11933. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11934. vertexData.applyToMesh(sphere, updatable);
  11935. return sphere;
  11936. };
  11937. // Cylinder and cone (Code inspired by SharpDX.org)
  11938. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11939. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11940. // subdivisions is a new parameter, we need to support old signature
  11941. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11942. if (scene !== undefined) {
  11943. updatable = scene;
  11944. }
  11945. scene = subdivisions;
  11946. subdivisions = 1;
  11947. }
  11948. var cylinder = new Mesh(name, scene);
  11949. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11950. vertexData.applyToMesh(cylinder, updatable);
  11951. return cylinder;
  11952. };
  11953. // Torus (Code from SharpDX.org)
  11954. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11955. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11956. var torus = new Mesh(name, scene);
  11957. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11958. vertexData.applyToMesh(torus, updatable);
  11959. return torus;
  11960. };
  11961. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11962. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11963. var torusKnot = new Mesh(name, scene);
  11964. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11965. vertexData.applyToMesh(torusKnot, updatable);
  11966. return torusKnot;
  11967. };
  11968. // Lines
  11969. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  11970. if (linesInstance === void 0) { linesInstance = null; }
  11971. if (linesInstance) {
  11972. var positionsOfLines = function (points) {
  11973. var positionFunction = function (positions) {
  11974. var i = 0;
  11975. for (var p = 0; p < points.length; p++) {
  11976. positions[i] = points[p].x;
  11977. positions[i + 1] = points[p].y;
  11978. positions[i + 2] = points[p].z;
  11979. i += 3;
  11980. }
  11981. };
  11982. return positionFunction;
  11983. };
  11984. var positionFunction = positionsOfLines(points);
  11985. linesInstance.updateMeshPositions(positionFunction, false);
  11986. return linesInstance;
  11987. }
  11988. // lines creation
  11989. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11990. var vertexData = BABYLON.VertexData.CreateLines(points);
  11991. vertexData.applyToMesh(lines, updatable);
  11992. return lines;
  11993. };
  11994. // Extrusion
  11995. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation, extrudedInstance) {
  11996. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11997. if (extrudedInstance === void 0) { extrudedInstance = null; }
  11998. scale = scale || 1;
  11999. rotation = rotation || 0;
  12000. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation, extrudedInstance);
  12001. return extruded;
  12002. };
  12003. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation, extrudedInstance) {
  12004. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  12005. if (extrudedInstance === void 0) { extrudedInstance = null; }
  12006. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation, extrudedInstance);
  12007. return extrudedCustom;
  12008. };
  12009. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, custom, scene, updtbl, side, instance) {
  12010. // extrusion geometry
  12011. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, custom) {
  12012. var tangents = path3D.getTangents();
  12013. var normals = path3D.getNormals();
  12014. var binormals = path3D.getBinormals();
  12015. var distances = path3D.getDistances();
  12016. var angle = 0;
  12017. var returnScale = function (i, distance) {
  12018. return scale;
  12019. };
  12020. var returnRotation = function (i, distance) {
  12021. return rotation;
  12022. };
  12023. var rotate = custom ? rotateFunction : returnRotation;
  12024. var scl = custom ? scaleFunction : returnScale;
  12025. var index = 0;
  12026. for (var i = 0; i < curve.length; i++) {
  12027. var shapePath = new Array();
  12028. var angleStep = rotate(i, distances[i]);
  12029. var scaleRatio = scl(i, distances[i]);
  12030. for (var p = 0; p < shape.length; p++) {
  12031. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  12032. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  12033. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  12034. shapePath.push(rotated);
  12035. }
  12036. shapePaths[index] = shapePath;
  12037. angle += angleStep;
  12038. index++;
  12039. }
  12040. return shapePaths;
  12041. };
  12042. if (instance) {
  12043. var path3D = (instance.path3D).update(curve);
  12044. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, custom);
  12045. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  12046. return instance;
  12047. }
  12048. // extruded shape creation
  12049. var path3D = new BABYLON.Path3D(curve);
  12050. var newShapePaths = new Array();
  12051. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, custom);
  12052. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  12053. extrudedGeneric.pathArray = pathArray;
  12054. extrudedGeneric.path3D = path3D;
  12055. return extrudedGeneric;
  12056. };
  12057. // Plane & ground
  12058. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  12059. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  12060. var plane = new Mesh(name, scene);
  12061. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  12062. vertexData.applyToMesh(plane, updatable);
  12063. return plane;
  12064. };
  12065. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  12066. var ground = new BABYLON.GroundMesh(name, scene);
  12067. ground._setReady(false);
  12068. ground._subdivisions = subdivisions;
  12069. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  12070. vertexData.applyToMesh(ground, updatable);
  12071. ground._setReady(true);
  12072. return ground;
  12073. };
  12074. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  12075. var tiledGround = new Mesh(name, scene);
  12076. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  12077. vertexData.applyToMesh(tiledGround, updatable);
  12078. return tiledGround;
  12079. };
  12080. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  12081. var ground = new BABYLON.GroundMesh(name, scene);
  12082. ground._subdivisions = subdivisions;
  12083. ground._setReady(false);
  12084. var onload = function (img) {
  12085. // Getting height map data
  12086. var canvas = document.createElement("canvas");
  12087. var context = canvas.getContext("2d");
  12088. var heightMapWidth = img.width;
  12089. var heightMapHeight = img.height;
  12090. canvas.width = heightMapWidth;
  12091. canvas.height = heightMapHeight;
  12092. context.drawImage(img, 0, 0);
  12093. // Create VertexData from map data
  12094. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  12095. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  12096. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  12097. vertexData.applyToMesh(ground, updatable);
  12098. ground._setReady(true);
  12099. //execute ready callback, if set
  12100. if (onReady) {
  12101. onReady(ground);
  12102. }
  12103. };
  12104. BABYLON.Tools.LoadImage(url, onload, function () {
  12105. }, scene.database);
  12106. return ground;
  12107. };
  12108. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, scene, updatable, sideOrientation, tubeInstance) {
  12109. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  12110. if (tubeInstance === void 0) { tubeInstance = null; }
  12111. // tube geometry
  12112. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction) {
  12113. var tangents = path3D.getTangents();
  12114. var normals = path3D.getNormals();
  12115. var distances = path3D.getDistances();
  12116. var pi2 = Math.PI * 2;
  12117. var step = pi2 / tessellation;
  12118. var returnRadius = function (i, distance) { return radius; };
  12119. var radiusFunctionFinal = radiusFunction || returnRadius;
  12120. var circlePath;
  12121. var rad;
  12122. var normal;
  12123. var rotated;
  12124. var rotationMatrix;
  12125. var index = 0;
  12126. for (var i = 0; i < path.length; i++) {
  12127. rad = radiusFunctionFinal(i, distances[i]); // current radius
  12128. circlePath = Array(); // current circle array
  12129. normal = normals[i]; // current normal
  12130. for (var ang = 0; ang < pi2; ang += step) {
  12131. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  12132. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  12133. circlePath.push(rotated);
  12134. }
  12135. circlePaths[index] = circlePath;
  12136. index++;
  12137. }
  12138. return circlePaths;
  12139. };
  12140. if (tubeInstance) {
  12141. var path3D = (tubeInstance.path3D).update(path);
  12142. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction);
  12143. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  12144. return tubeInstance;
  12145. }
  12146. // tube creation
  12147. var path3D = new BABYLON.Path3D(path);
  12148. var newPathArray = new Array();
  12149. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction);
  12150. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  12151. tube.pathArray = pathArray;
  12152. tube.path3D = path3D;
  12153. tube.tessellation = tessellation;
  12154. return tube;
  12155. };
  12156. // Decals
  12157. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  12158. if (angle === void 0) { angle = 0; }
  12159. var indices = sourceMesh.getIndices();
  12160. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12161. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12162. // Getting correct rotation
  12163. if (!normal) {
  12164. var target = new BABYLON.Vector3(0, 0, 1);
  12165. var camera = sourceMesh.getScene().activeCamera;
  12166. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  12167. normal = camera.globalPosition.subtract(cameraWorldTarget);
  12168. }
  12169. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  12170. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  12171. var pitch = Math.atan2(normal.y, len);
  12172. // Matrix
  12173. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  12174. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  12175. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  12176. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  12177. var vertexData = new BABYLON.VertexData();
  12178. vertexData.indices = [];
  12179. vertexData.positions = [];
  12180. vertexData.normals = [];
  12181. vertexData.uvs = [];
  12182. var currentVertexDataIndex = 0;
  12183. var extractDecalVector3 = function (indexId) {
  12184. var vertexId = indices[indexId];
  12185. var result = new BABYLON.PositionNormalVertex();
  12186. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  12187. // Send vector to decal local world
  12188. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  12189. // Get normal
  12190. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  12191. return result;
  12192. };
  12193. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  12194. var clip = function (vertices, axis) {
  12195. if (vertices.length === 0) {
  12196. return vertices;
  12197. }
  12198. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  12199. var clipVertices = function (v0, v1) {
  12200. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  12201. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  12202. };
  12203. var result = new Array();
  12204. for (var index = 0; index < vertices.length; index += 3) {
  12205. var v1Out;
  12206. var v2Out;
  12207. var v3Out;
  12208. var total = 0;
  12209. var nV1, nV2, nV3, nV4;
  12210. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  12211. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  12212. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  12213. v1Out = d1 > 0;
  12214. v2Out = d2 > 0;
  12215. v3Out = d3 > 0;
  12216. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  12217. switch (total) {
  12218. case 0:
  12219. result.push(vertices[index]);
  12220. result.push(vertices[index + 1]);
  12221. result.push(vertices[index + 2]);
  12222. break;
  12223. case 1:
  12224. if (v1Out) {
  12225. nV1 = vertices[index + 1];
  12226. nV2 = vertices[index + 2];
  12227. nV3 = clipVertices(vertices[index], nV1);
  12228. nV4 = clipVertices(vertices[index], nV2);
  12229. }
  12230. if (v2Out) {
  12231. nV1 = vertices[index];
  12232. nV2 = vertices[index + 2];
  12233. nV3 = clipVertices(vertices[index + 1], nV1);
  12234. nV4 = clipVertices(vertices[index + 1], nV2);
  12235. result.push(nV3);
  12236. result.push(nV2.clone());
  12237. result.push(nV1.clone());
  12238. result.push(nV2.clone());
  12239. result.push(nV3.clone());
  12240. result.push(nV4);
  12241. break;
  12242. }
  12243. if (v3Out) {
  12244. nV1 = vertices[index];
  12245. nV2 = vertices[index + 1];
  12246. nV3 = clipVertices(vertices[index + 2], nV1);
  12247. nV4 = clipVertices(vertices[index + 2], nV2);
  12248. }
  12249. result.push(nV1.clone());
  12250. result.push(nV2.clone());
  12251. result.push(nV3);
  12252. result.push(nV4);
  12253. result.push(nV3.clone());
  12254. result.push(nV2.clone());
  12255. break;
  12256. case 2:
  12257. if (!v1Out) {
  12258. nV1 = vertices[index].clone();
  12259. nV2 = clipVertices(nV1, vertices[index + 1]);
  12260. nV3 = clipVertices(nV1, vertices[index + 2]);
  12261. result.push(nV1);
  12262. result.push(nV2);
  12263. result.push(nV3);
  12264. }
  12265. if (!v2Out) {
  12266. nV1 = vertices[index + 1].clone();
  12267. nV2 = clipVertices(nV1, vertices[index + 2]);
  12268. nV3 = clipVertices(nV1, vertices[index]);
  12269. result.push(nV1);
  12270. result.push(nV2);
  12271. result.push(nV3);
  12272. }
  12273. if (!v3Out) {
  12274. nV1 = vertices[index + 2].clone();
  12275. nV2 = clipVertices(nV1, vertices[index]);
  12276. nV3 = clipVertices(nV1, vertices[index + 1]);
  12277. result.push(nV1);
  12278. result.push(nV2);
  12279. result.push(nV3);
  12280. }
  12281. break;
  12282. case 3:
  12283. break;
  12284. }
  12285. }
  12286. return result;
  12287. };
  12288. for (var index = 0; index < indices.length; index += 3) {
  12289. var faceVertices = new Array();
  12290. faceVertices.push(extractDecalVector3(index));
  12291. faceVertices.push(extractDecalVector3(index + 1));
  12292. faceVertices.push(extractDecalVector3(index + 2));
  12293. // Clip
  12294. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  12295. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  12296. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  12297. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  12298. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  12299. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  12300. if (faceVertices.length === 0) {
  12301. continue;
  12302. }
  12303. // Add UVs and get back to world
  12304. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  12305. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  12306. var vertex = faceVertices[vIndex];
  12307. vertexData.indices.push(currentVertexDataIndex);
  12308. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  12309. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  12310. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  12311. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  12312. currentVertexDataIndex++;
  12313. }
  12314. }
  12315. // Return mesh
  12316. var decal = new Mesh(name, sourceMesh.getScene());
  12317. vertexData.applyToMesh(decal);
  12318. decal.position = position.clone();
  12319. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  12320. return decal;
  12321. };
  12322. // Tools
  12323. Mesh.MinMax = function (meshes) {
  12324. var minVector = null;
  12325. var maxVector = null;
  12326. for (var i in meshes) {
  12327. var mesh = meshes[i];
  12328. var boundingBox = mesh.getBoundingInfo().boundingBox;
  12329. if (!minVector) {
  12330. minVector = boundingBox.minimumWorld;
  12331. maxVector = boundingBox.maximumWorld;
  12332. continue;
  12333. }
  12334. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  12335. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  12336. }
  12337. return {
  12338. min: minVector,
  12339. max: maxVector
  12340. };
  12341. };
  12342. Mesh.Center = function (meshesOrMinMaxVector) {
  12343. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  12344. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  12345. };
  12346. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  12347. if (disposeSource === void 0) { disposeSource = true; }
  12348. var source = meshes[0];
  12349. var material = source.material;
  12350. var scene = source.getScene();
  12351. if (!allow32BitsIndices) {
  12352. var totalVertices = 0;
  12353. for (var index = 0; index < meshes.length; index++) {
  12354. totalVertices += meshes[index].getTotalVertices();
  12355. if (totalVertices > 65536) {
  12356. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  12357. return null;
  12358. }
  12359. }
  12360. }
  12361. // Merge
  12362. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  12363. vertexData.transform(source.getWorldMatrix());
  12364. for (index = 1; index < meshes.length; index++) {
  12365. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  12366. otherVertexData.transform(meshes[index].getWorldMatrix());
  12367. vertexData.merge(otherVertexData);
  12368. }
  12369. var newMesh = new Mesh(source.name + "_merged", scene);
  12370. vertexData.applyToMesh(newMesh);
  12371. // Setting properties
  12372. newMesh.material = material;
  12373. newMesh.checkCollisions = source.checkCollisions;
  12374. // Cleaning
  12375. if (disposeSource) {
  12376. for (index = 0; index < meshes.length; index++) {
  12377. meshes[index].dispose();
  12378. }
  12379. }
  12380. return newMesh;
  12381. };
  12382. // Consts
  12383. Mesh._FRONTSIDE = 0;
  12384. Mesh._BACKSIDE = 1;
  12385. Mesh._DOUBLESIDE = 2;
  12386. Mesh._DEFAULTSIDE = 0;
  12387. return Mesh;
  12388. })(BABYLON.AbstractMesh);
  12389. BABYLON.Mesh = Mesh;
  12390. })(BABYLON || (BABYLON = {}));
  12391. //# sourceMappingURL=babylon.mesh.js.map
  12392. var BABYLON;
  12393. (function (BABYLON) {
  12394. var GroundMesh = (function (_super) {
  12395. __extends(GroundMesh, _super);
  12396. function GroundMesh(name, scene) {
  12397. _super.call(this, name, scene);
  12398. this.generateOctree = false;
  12399. this._worldInverse = new BABYLON.Matrix();
  12400. }
  12401. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  12402. get: function () {
  12403. return this._subdivisions;
  12404. },
  12405. enumerable: true,
  12406. configurable: true
  12407. });
  12408. GroundMesh.prototype.optimize = function (chunksCount) {
  12409. this.subdivide(this._subdivisions);
  12410. this.createOrUpdateSubmeshesOctree(32);
  12411. };
  12412. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  12413. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  12414. this.getWorldMatrix().invertToRef(this._worldInverse);
  12415. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  12416. var pickInfo = this.intersects(ray);
  12417. if (pickInfo.hit) {
  12418. return pickInfo.pickedPoint.y;
  12419. }
  12420. return 0;
  12421. };
  12422. return GroundMesh;
  12423. })(BABYLON.Mesh);
  12424. BABYLON.GroundMesh = GroundMesh;
  12425. })(BABYLON || (BABYLON = {}));
  12426. //# sourceMappingURL=babylon.groundMesh.js.map
  12427. var BABYLON;
  12428. (function (BABYLON) {
  12429. /**
  12430. * Creates an instance based on a source mesh.
  12431. */
  12432. var InstancedMesh = (function (_super) {
  12433. __extends(InstancedMesh, _super);
  12434. function InstancedMesh(name, source) {
  12435. _super.call(this, name, source.getScene());
  12436. source.instances.push(this);
  12437. this._sourceMesh = source;
  12438. this.position.copyFrom(source.position);
  12439. this.rotation.copyFrom(source.rotation);
  12440. this.scaling.copyFrom(source.scaling);
  12441. if (source.rotationQuaternion) {
  12442. this.rotationQuaternion = source.rotationQuaternion.clone();
  12443. }
  12444. this.infiniteDistance = source.infiniteDistance;
  12445. this.setPivotMatrix(source.getPivotMatrix());
  12446. this.refreshBoundingInfo();
  12447. this._syncSubMeshes();
  12448. }
  12449. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  12450. // Methods
  12451. get: function () {
  12452. return this._sourceMesh.receiveShadows;
  12453. },
  12454. enumerable: true,
  12455. configurable: true
  12456. });
  12457. Object.defineProperty(InstancedMesh.prototype, "material", {
  12458. get: function () {
  12459. return this._sourceMesh.material;
  12460. },
  12461. enumerable: true,
  12462. configurable: true
  12463. });
  12464. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  12465. get: function () {
  12466. return this._sourceMesh.visibility;
  12467. },
  12468. enumerable: true,
  12469. configurable: true
  12470. });
  12471. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  12472. get: function () {
  12473. return this._sourceMesh.skeleton;
  12474. },
  12475. enumerable: true,
  12476. configurable: true
  12477. });
  12478. InstancedMesh.prototype.getTotalVertices = function () {
  12479. return this._sourceMesh.getTotalVertices();
  12480. };
  12481. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  12482. get: function () {
  12483. return this._sourceMesh;
  12484. },
  12485. enumerable: true,
  12486. configurable: true
  12487. });
  12488. InstancedMesh.prototype.getVerticesData = function (kind) {
  12489. return this._sourceMesh.getVerticesData(kind);
  12490. };
  12491. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  12492. return this._sourceMesh.isVerticesDataPresent(kind);
  12493. };
  12494. InstancedMesh.prototype.getIndices = function () {
  12495. return this._sourceMesh.getIndices();
  12496. };
  12497. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  12498. get: function () {
  12499. return this._sourceMesh._positions;
  12500. },
  12501. enumerable: true,
  12502. configurable: true
  12503. });
  12504. InstancedMesh.prototype.refreshBoundingInfo = function () {
  12505. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12506. if (data) {
  12507. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  12508. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12509. }
  12510. this._updateBoundingInfo();
  12511. };
  12512. InstancedMesh.prototype._preActivate = function () {
  12513. if (this._currentLOD) {
  12514. this._currentLOD._preActivate();
  12515. }
  12516. };
  12517. InstancedMesh.prototype._activate = function (renderId) {
  12518. if (this._currentLOD) {
  12519. this._currentLOD._registerInstanceForRenderId(this, renderId);
  12520. }
  12521. };
  12522. InstancedMesh.prototype.getLOD = function (camera) {
  12523. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  12524. if (this._currentLOD === this.sourceMesh) {
  12525. return this;
  12526. }
  12527. return this._currentLOD;
  12528. };
  12529. InstancedMesh.prototype._syncSubMeshes = function () {
  12530. this.releaseSubMeshes();
  12531. if (this._sourceMesh.subMeshes) {
  12532. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  12533. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  12534. }
  12535. }
  12536. };
  12537. InstancedMesh.prototype._generatePointsArray = function () {
  12538. return this._sourceMesh._generatePointsArray();
  12539. };
  12540. // Clone
  12541. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12542. var result = this._sourceMesh.createInstance(name);
  12543. // Deep copy
  12544. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  12545. // Bounding info
  12546. this.refreshBoundingInfo();
  12547. // Parent
  12548. if (newParent) {
  12549. result.parent = newParent;
  12550. }
  12551. if (!doNotCloneChildren) {
  12552. for (var index = 0; index < this.getScene().meshes.length; index++) {
  12553. var mesh = this.getScene().meshes[index];
  12554. if (mesh.parent === this) {
  12555. mesh.clone(mesh.name, result);
  12556. }
  12557. }
  12558. }
  12559. result.computeWorldMatrix(true);
  12560. return result;
  12561. };
  12562. // Dispoe
  12563. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  12564. // Remove from mesh
  12565. var index = this._sourceMesh.instances.indexOf(this);
  12566. this._sourceMesh.instances.splice(index, 1);
  12567. _super.prototype.dispose.call(this, doNotRecurse);
  12568. };
  12569. return InstancedMesh;
  12570. })(BABYLON.AbstractMesh);
  12571. BABYLON.InstancedMesh = InstancedMesh;
  12572. })(BABYLON || (BABYLON = {}));
  12573. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  12574. (function (BABYLON) {
  12575. var SubMesh = (function () {
  12576. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  12577. if (createBoundingBox === void 0) { createBoundingBox = true; }
  12578. this.materialIndex = materialIndex;
  12579. this.verticesStart = verticesStart;
  12580. this.verticesCount = verticesCount;
  12581. this.indexStart = indexStart;
  12582. this.indexCount = indexCount;
  12583. this._renderId = 0;
  12584. this._mesh = mesh;
  12585. this._renderingMesh = renderingMesh || mesh;
  12586. mesh.subMeshes.push(this);
  12587. this._id = mesh.subMeshes.length - 1;
  12588. if (createBoundingBox) {
  12589. this.refreshBoundingInfo();
  12590. mesh.computeWorldMatrix(true);
  12591. }
  12592. }
  12593. SubMesh.prototype.getBoundingInfo = function () {
  12594. return this._boundingInfo;
  12595. };
  12596. SubMesh.prototype.getMesh = function () {
  12597. return this._mesh;
  12598. };
  12599. SubMesh.prototype.getRenderingMesh = function () {
  12600. return this._renderingMesh;
  12601. };
  12602. SubMesh.prototype.getMaterial = function () {
  12603. var rootMaterial = this._renderingMesh.material;
  12604. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  12605. var multiMaterial = rootMaterial;
  12606. return multiMaterial.getSubMaterial(this.materialIndex);
  12607. }
  12608. if (!rootMaterial) {
  12609. return this._mesh.getScene().defaultMaterial;
  12610. }
  12611. return rootMaterial;
  12612. };
  12613. // Methods
  12614. SubMesh.prototype.refreshBoundingInfo = function () {
  12615. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12616. if (!data) {
  12617. this._boundingInfo = this._mesh._boundingInfo;
  12618. return;
  12619. }
  12620. var indices = this._renderingMesh.getIndices();
  12621. var extend;
  12622. if (this.indexStart === 0 && this.indexCount === indices.length) {
  12623. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  12624. }
  12625. else {
  12626. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  12627. }
  12628. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12629. };
  12630. SubMesh.prototype._checkCollision = function (collider) {
  12631. return this._boundingInfo._checkCollision(collider);
  12632. };
  12633. SubMesh.prototype.updateBoundingInfo = function (world) {
  12634. if (!this._boundingInfo) {
  12635. this.refreshBoundingInfo();
  12636. }
  12637. this._boundingInfo._update(world);
  12638. };
  12639. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  12640. return this._boundingInfo.isInFrustum(frustumPlanes);
  12641. };
  12642. SubMesh.prototype.render = function () {
  12643. this._renderingMesh.render(this);
  12644. };
  12645. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  12646. if (!this._linesIndexBuffer) {
  12647. var linesIndices = [];
  12648. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12649. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  12650. }
  12651. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  12652. this.linesIndexCount = linesIndices.length;
  12653. }
  12654. return this._linesIndexBuffer;
  12655. };
  12656. SubMesh.prototype.canIntersects = function (ray) {
  12657. return ray.intersectsBox(this._boundingInfo.boundingBox);
  12658. };
  12659. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  12660. var intersectInfo = null;
  12661. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12662. var p0 = positions[indices[index]];
  12663. var p1 = positions[indices[index + 1]];
  12664. var p2 = positions[indices[index + 2]];
  12665. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  12666. if (currentIntersectInfo) {
  12667. if (currentIntersectInfo.distance < 0) {
  12668. continue;
  12669. }
  12670. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12671. intersectInfo = currentIntersectInfo;
  12672. intersectInfo.faceId = index / 3;
  12673. if (fastCheck) {
  12674. break;
  12675. }
  12676. }
  12677. }
  12678. }
  12679. return intersectInfo;
  12680. };
  12681. // Clone
  12682. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  12683. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  12684. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  12685. return result;
  12686. };
  12687. // Dispose
  12688. SubMesh.prototype.dispose = function () {
  12689. if (this._linesIndexBuffer) {
  12690. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  12691. this._linesIndexBuffer = null;
  12692. }
  12693. // Remove from mesh
  12694. var index = this._mesh.subMeshes.indexOf(this);
  12695. this._mesh.subMeshes.splice(index, 1);
  12696. };
  12697. // Statics
  12698. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  12699. var minVertexIndex = Number.MAX_VALUE;
  12700. var maxVertexIndex = -Number.MAX_VALUE;
  12701. renderingMesh = renderingMesh || mesh;
  12702. var indices = renderingMesh.getIndices();
  12703. for (var index = startIndex; index < startIndex + indexCount; index++) {
  12704. var vertexIndex = indices[index];
  12705. if (vertexIndex < minVertexIndex)
  12706. minVertexIndex = vertexIndex;
  12707. if (vertexIndex > maxVertexIndex)
  12708. maxVertexIndex = vertexIndex;
  12709. }
  12710. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  12711. };
  12712. return SubMesh;
  12713. })();
  12714. BABYLON.SubMesh = SubMesh;
  12715. })(BABYLON || (BABYLON = {}));
  12716. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  12717. (function (BABYLON) {
  12718. var BaseTexture = (function () {
  12719. function BaseTexture(scene) {
  12720. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  12721. this.hasAlpha = false;
  12722. this.getAlphaFromRGB = false;
  12723. this.level = 1;
  12724. this.isCube = false;
  12725. this.isRenderTarget = false;
  12726. this.animations = new Array();
  12727. this.coordinatesIndex = 0;
  12728. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  12729. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12730. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12731. this.anisotropicFilteringLevel = 4;
  12732. this._scene = scene;
  12733. this._scene.textures.push(this);
  12734. }
  12735. BaseTexture.prototype.getScene = function () {
  12736. return this._scene;
  12737. };
  12738. BaseTexture.prototype.getTextureMatrix = function () {
  12739. return null;
  12740. };
  12741. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  12742. return null;
  12743. };
  12744. BaseTexture.prototype.getInternalTexture = function () {
  12745. return this._texture;
  12746. };
  12747. BaseTexture.prototype.isReady = function () {
  12748. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12749. return true;
  12750. }
  12751. if (this._texture) {
  12752. return this._texture.isReady;
  12753. }
  12754. return false;
  12755. };
  12756. BaseTexture.prototype.getSize = function () {
  12757. if (this._texture._width) {
  12758. return { width: this._texture._width, height: this._texture._height };
  12759. }
  12760. if (this._texture._size) {
  12761. return { width: this._texture._size, height: this._texture._size };
  12762. }
  12763. return { width: 0, height: 0 };
  12764. };
  12765. BaseTexture.prototype.getBaseSize = function () {
  12766. if (!this.isReady())
  12767. return { width: 0, height: 0 };
  12768. if (this._texture._size) {
  12769. return { width: this._texture._size, height: this._texture._size };
  12770. }
  12771. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  12772. };
  12773. BaseTexture.prototype.scale = function (ratio) {
  12774. };
  12775. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  12776. get: function () {
  12777. return false;
  12778. },
  12779. enumerable: true,
  12780. configurable: true
  12781. });
  12782. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  12783. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12784. for (var index = 0; index < texturesCache.length; index++) {
  12785. var texturesCacheEntry = texturesCache[index];
  12786. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12787. texturesCache.splice(index, 1);
  12788. return;
  12789. }
  12790. }
  12791. };
  12792. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  12793. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12794. for (var index = 0; index < texturesCache.length; index++) {
  12795. var texturesCacheEntry = texturesCache[index];
  12796. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12797. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  12798. texturesCacheEntry.references++;
  12799. return texturesCacheEntry;
  12800. }
  12801. }
  12802. }
  12803. return null;
  12804. };
  12805. BaseTexture.prototype.delayLoad = function () {
  12806. };
  12807. BaseTexture.prototype.releaseInternalTexture = function () {
  12808. if (!this._texture) {
  12809. return;
  12810. }
  12811. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12812. this._texture.references--;
  12813. // Final reference ?
  12814. if (this._texture.references === 0) {
  12815. var index = texturesCache.indexOf(this._texture);
  12816. texturesCache.splice(index, 1);
  12817. this._scene.getEngine()._releaseTexture(this._texture);
  12818. delete this._texture;
  12819. }
  12820. };
  12821. BaseTexture.prototype.clone = function () {
  12822. return null;
  12823. };
  12824. BaseTexture.prototype.dispose = function () {
  12825. // Remove from scene
  12826. var index = this._scene.textures.indexOf(this);
  12827. if (index >= 0) {
  12828. this._scene.textures.splice(index, 1);
  12829. }
  12830. if (this._texture === undefined) {
  12831. return;
  12832. }
  12833. this.releaseInternalTexture();
  12834. // Callback
  12835. if (this.onDispose) {
  12836. this.onDispose();
  12837. }
  12838. };
  12839. return BaseTexture;
  12840. })();
  12841. BABYLON.BaseTexture = BaseTexture;
  12842. })(BABYLON || (BABYLON = {}));
  12843. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  12844. (function (BABYLON) {
  12845. var RenderingGroup = (function () {
  12846. function RenderingGroup(index, scene) {
  12847. this.index = index;
  12848. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12849. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12850. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12851. this._scene = scene;
  12852. }
  12853. RenderingGroup.prototype.render = function (customRenderFunction) {
  12854. if (customRenderFunction) {
  12855. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12856. return true;
  12857. }
  12858. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12859. return false;
  12860. }
  12861. var engine = this._scene.getEngine();
  12862. // Opaque
  12863. var subIndex;
  12864. var submesh;
  12865. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12866. submesh = this._opaqueSubMeshes.data[subIndex];
  12867. submesh.render();
  12868. }
  12869. // Alpha test
  12870. engine.setAlphaTesting(true);
  12871. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12872. submesh = this._alphaTestSubMeshes.data[subIndex];
  12873. submesh.render();
  12874. }
  12875. engine.setAlphaTesting(false);
  12876. // Transparent
  12877. if (this._transparentSubMeshes.length) {
  12878. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12879. submesh = this._transparentSubMeshes.data[subIndex];
  12880. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12881. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  12882. }
  12883. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12884. sortedArray.sort(function (a, b) {
  12885. // Alpha index first
  12886. if (a._alphaIndex > b._alphaIndex) {
  12887. return 1;
  12888. }
  12889. if (a._alphaIndex < b._alphaIndex) {
  12890. return -1;
  12891. }
  12892. // Then distance to camera
  12893. if (a._distanceToCamera < b._distanceToCamera) {
  12894. return 1;
  12895. }
  12896. if (a._distanceToCamera > b._distanceToCamera) {
  12897. return -1;
  12898. }
  12899. return 0;
  12900. });
  12901. // Rendering
  12902. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12903. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12904. submesh = sortedArray[subIndex];
  12905. submesh.render();
  12906. }
  12907. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12908. }
  12909. return true;
  12910. };
  12911. RenderingGroup.prototype.prepare = function () {
  12912. this._opaqueSubMeshes.reset();
  12913. this._transparentSubMeshes.reset();
  12914. this._alphaTestSubMeshes.reset();
  12915. };
  12916. RenderingGroup.prototype.dispatch = function (subMesh) {
  12917. var material = subMesh.getMaterial();
  12918. var mesh = subMesh.getMesh();
  12919. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12920. this._transparentSubMeshes.push(subMesh);
  12921. }
  12922. else if (material.needAlphaTesting()) {
  12923. this._alphaTestSubMeshes.push(subMesh);
  12924. }
  12925. else {
  12926. this._opaqueSubMeshes.push(subMesh); // Opaque
  12927. }
  12928. };
  12929. return RenderingGroup;
  12930. })();
  12931. BABYLON.RenderingGroup = RenderingGroup;
  12932. })(BABYLON || (BABYLON = {}));
  12933. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12934. (function (BABYLON) {
  12935. var RenderingManager = (function () {
  12936. function RenderingManager(scene) {
  12937. this._renderingGroups = new Array();
  12938. this._scene = scene;
  12939. }
  12940. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12941. if (this._scene._activeParticleSystems.length === 0) {
  12942. return;
  12943. }
  12944. // Particles
  12945. var beforeParticlesDate = BABYLON.Tools.Now;
  12946. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12947. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12948. if (particleSystem.renderingGroupId !== index) {
  12949. continue;
  12950. }
  12951. this._clearDepthBuffer();
  12952. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12953. this._scene._activeParticles += particleSystem.render();
  12954. }
  12955. }
  12956. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12957. };
  12958. RenderingManager.prototype._renderSprites = function (index) {
  12959. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12960. return;
  12961. }
  12962. // Sprites
  12963. var beforeSpritessDate = BABYLON.Tools.Now;
  12964. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12965. var spriteManager = this._scene.spriteManagers[id];
  12966. if (spriteManager.renderingGroupId === index) {
  12967. this._clearDepthBuffer();
  12968. spriteManager.render();
  12969. }
  12970. }
  12971. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12972. };
  12973. RenderingManager.prototype._clearDepthBuffer = function () {
  12974. if (this._depthBufferAlreadyCleaned) {
  12975. return;
  12976. }
  12977. this._scene.getEngine().clear(0, false, true);
  12978. this._depthBufferAlreadyCleaned = true;
  12979. };
  12980. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12981. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12982. this._depthBufferAlreadyCleaned = false;
  12983. var renderingGroup = this._renderingGroups[index];
  12984. var needToStepBack = false;
  12985. if (renderingGroup) {
  12986. this._clearDepthBuffer();
  12987. if (!renderingGroup.render(customRenderFunction)) {
  12988. this._renderingGroups.splice(index, 1);
  12989. needToStepBack = true;
  12990. }
  12991. }
  12992. if (renderSprites) {
  12993. this._renderSprites(index);
  12994. }
  12995. if (renderParticles) {
  12996. this._renderParticles(index, activeMeshes);
  12997. }
  12998. if (needToStepBack) {
  12999. index--;
  13000. }
  13001. }
  13002. };
  13003. RenderingManager.prototype.reset = function () {
  13004. for (var index in this._renderingGroups) {
  13005. var renderingGroup = this._renderingGroups[index];
  13006. renderingGroup.prepare();
  13007. }
  13008. };
  13009. RenderingManager.prototype.dispatch = function (subMesh) {
  13010. var mesh = subMesh.getMesh();
  13011. var renderingGroupId = mesh.renderingGroupId || 0;
  13012. if (!this._renderingGroups[renderingGroupId]) {
  13013. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  13014. }
  13015. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13016. };
  13017. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13018. return RenderingManager;
  13019. })();
  13020. BABYLON.RenderingManager = RenderingManager;
  13021. })(BABYLON || (BABYLON = {}));
  13022. //# sourceMappingURL=babylon.renderingManager.js.map
  13023. var BABYLON;
  13024. (function (BABYLON) {
  13025. var Texture = (function (_super) {
  13026. __extends(Texture, _super);
  13027. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  13028. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  13029. if (onLoad === void 0) { onLoad = null; }
  13030. if (onError === void 0) { onError = null; }
  13031. if (buffer === void 0) { buffer = null; }
  13032. if (deleteBuffer === void 0) { deleteBuffer = false; }
  13033. _super.call(this, scene);
  13034. this.uOffset = 0;
  13035. this.vOffset = 0;
  13036. this.uScale = 1.0;
  13037. this.vScale = 1.0;
  13038. this.uAng = 0;
  13039. this.vAng = 0;
  13040. this.wAng = 0;
  13041. this.name = url;
  13042. this.url = url;
  13043. this._noMipmap = noMipmap;
  13044. this._invertY = invertY;
  13045. this._samplingMode = samplingMode;
  13046. this._buffer = buffer;
  13047. this._deleteBuffer = deleteBuffer;
  13048. if (!url) {
  13049. return;
  13050. }
  13051. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  13052. if (!this._texture) {
  13053. if (!scene.useDelayedTextureLoading) {
  13054. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  13055. if (deleteBuffer) {
  13056. delete this._buffer;
  13057. }
  13058. }
  13059. else {
  13060. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  13061. }
  13062. }
  13063. }
  13064. Texture.prototype.delayLoad = function () {
  13065. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13066. return;
  13067. }
  13068. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13069. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  13070. if (!this._texture) {
  13071. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  13072. if (this._deleteBuffer) {
  13073. delete this._buffer;
  13074. }
  13075. }
  13076. };
  13077. Texture.prototype.updateSamplingMode = function (samplingMode) {
  13078. if (!this._texture) {
  13079. return;
  13080. }
  13081. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  13082. };
  13083. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  13084. x -= this.uOffset + 0.5;
  13085. y -= this.vOffset + 0.5;
  13086. z -= 0.5;
  13087. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  13088. t.x *= this.uScale;
  13089. t.y *= this.vScale;
  13090. t.x += 0.5;
  13091. t.y += 0.5;
  13092. t.z += 0.5;
  13093. };
  13094. Texture.prototype.getTextureMatrix = function () {
  13095. 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) {
  13096. return this._cachedTextureMatrix;
  13097. }
  13098. this._cachedUOffset = this.uOffset;
  13099. this._cachedVOffset = this.vOffset;
  13100. this._cachedUScale = this.uScale;
  13101. this._cachedVScale = this.vScale;
  13102. this._cachedUAng = this.uAng;
  13103. this._cachedVAng = this.vAng;
  13104. this._cachedWAng = this.wAng;
  13105. if (!this._cachedTextureMatrix) {
  13106. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  13107. this._rowGenerationMatrix = new BABYLON.Matrix();
  13108. this._t0 = BABYLON.Vector3.Zero();
  13109. this._t1 = BABYLON.Vector3.Zero();
  13110. this._t2 = BABYLON.Vector3.Zero();
  13111. }
  13112. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  13113. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  13114. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  13115. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  13116. this._t1.subtractInPlace(this._t0);
  13117. this._t2.subtractInPlace(this._t0);
  13118. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13119. this._cachedTextureMatrix.m[0] = this._t1.x;
  13120. this._cachedTextureMatrix.m[1] = this._t1.y;
  13121. this._cachedTextureMatrix.m[2] = this._t1.z;
  13122. this._cachedTextureMatrix.m[4] = this._t2.x;
  13123. this._cachedTextureMatrix.m[5] = this._t2.y;
  13124. this._cachedTextureMatrix.m[6] = this._t2.z;
  13125. this._cachedTextureMatrix.m[8] = this._t0.x;
  13126. this._cachedTextureMatrix.m[9] = this._t0.y;
  13127. this._cachedTextureMatrix.m[10] = this._t0.z;
  13128. return this._cachedTextureMatrix;
  13129. };
  13130. Texture.prototype.getReflectionTextureMatrix = function () {
  13131. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  13132. return this._cachedTextureMatrix;
  13133. }
  13134. if (!this._cachedTextureMatrix) {
  13135. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  13136. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  13137. }
  13138. this._cachedCoordinatesMode = this.coordinatesMode;
  13139. switch (this.coordinatesMode) {
  13140. case Texture.SPHERICAL_MODE:
  13141. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13142. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  13143. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  13144. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  13145. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  13146. break;
  13147. case Texture.PLANAR_MODE:
  13148. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13149. this._cachedTextureMatrix[0] = this.uScale;
  13150. this._cachedTextureMatrix[5] = this.vScale;
  13151. this._cachedTextureMatrix[12] = this.uOffset;
  13152. this._cachedTextureMatrix[13] = this.vOffset;
  13153. break;
  13154. case Texture.PROJECTION_MODE:
  13155. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  13156. this._projectionModeMatrix.m[0] = 0.5;
  13157. this._projectionModeMatrix.m[5] = -0.5;
  13158. this._projectionModeMatrix.m[10] = 0.0;
  13159. this._projectionModeMatrix.m[12] = 0.5;
  13160. this._projectionModeMatrix.m[13] = 0.5;
  13161. this._projectionModeMatrix.m[14] = 1.0;
  13162. this._projectionModeMatrix.m[15] = 1.0;
  13163. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  13164. break;
  13165. default:
  13166. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13167. break;
  13168. }
  13169. return this._cachedTextureMatrix;
  13170. };
  13171. Texture.prototype.clone = function () {
  13172. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  13173. // Base texture
  13174. newTexture.hasAlpha = this.hasAlpha;
  13175. newTexture.level = this.level;
  13176. newTexture.wrapU = this.wrapU;
  13177. newTexture.wrapV = this.wrapV;
  13178. newTexture.coordinatesIndex = this.coordinatesIndex;
  13179. newTexture.coordinatesMode = this.coordinatesMode;
  13180. // Texture
  13181. newTexture.uOffset = this.uOffset;
  13182. newTexture.vOffset = this.vOffset;
  13183. newTexture.uScale = this.uScale;
  13184. newTexture.vScale = this.vScale;
  13185. newTexture.uAng = this.uAng;
  13186. newTexture.vAng = this.vAng;
  13187. newTexture.wAng = this.wAng;
  13188. return newTexture;
  13189. };
  13190. // Statics
  13191. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  13192. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  13193. if (onLoad === void 0) { onLoad = null; }
  13194. if (onError === void 0) { onError = null; }
  13195. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  13196. };
  13197. // Constants
  13198. Texture.NEAREST_SAMPLINGMODE = 1;
  13199. Texture.BILINEAR_SAMPLINGMODE = 2;
  13200. Texture.TRILINEAR_SAMPLINGMODE = 3;
  13201. Texture.EXPLICIT_MODE = 0;
  13202. Texture.SPHERICAL_MODE = 1;
  13203. Texture.PLANAR_MODE = 2;
  13204. Texture.CUBIC_MODE = 3;
  13205. Texture.PROJECTION_MODE = 4;
  13206. Texture.SKYBOX_MODE = 5;
  13207. Texture.CLAMP_ADDRESSMODE = 0;
  13208. Texture.WRAP_ADDRESSMODE = 1;
  13209. Texture.MIRROR_ADDRESSMODE = 2;
  13210. return Texture;
  13211. })(BABYLON.BaseTexture);
  13212. BABYLON.Texture = Texture;
  13213. })(BABYLON || (BABYLON = {}));
  13214. //# sourceMappingURL=babylon.texture.js.map
  13215. var BABYLON;
  13216. (function (BABYLON) {
  13217. var CubeTexture = (function (_super) {
  13218. __extends(CubeTexture, _super);
  13219. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  13220. _super.call(this, scene);
  13221. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  13222. this.name = rootUrl;
  13223. this.url = rootUrl;
  13224. this._noMipmap = noMipmap;
  13225. this.hasAlpha = false;
  13226. this._texture = this._getFromCache(rootUrl, noMipmap);
  13227. if (!extensions) {
  13228. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  13229. }
  13230. this._extensions = extensions;
  13231. if (!this._texture) {
  13232. if (!scene.useDelayedTextureLoading) {
  13233. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  13234. }
  13235. else {
  13236. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  13237. }
  13238. }
  13239. this.isCube = true;
  13240. this._textureMatrix = BABYLON.Matrix.Identity();
  13241. }
  13242. CubeTexture.prototype.clone = function () {
  13243. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  13244. // Base texture
  13245. newTexture.level = this.level;
  13246. newTexture.wrapU = this.wrapU;
  13247. newTexture.wrapV = this.wrapV;
  13248. newTexture.coordinatesIndex = this.coordinatesIndex;
  13249. newTexture.coordinatesMode = this.coordinatesMode;
  13250. return newTexture;
  13251. };
  13252. // Methods
  13253. CubeTexture.prototype.delayLoad = function () {
  13254. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13255. return;
  13256. }
  13257. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13258. this._texture = this._getFromCache(this.url, this._noMipmap);
  13259. if (!this._texture) {
  13260. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  13261. }
  13262. };
  13263. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  13264. return this._textureMatrix;
  13265. };
  13266. return CubeTexture;
  13267. })(BABYLON.BaseTexture);
  13268. BABYLON.CubeTexture = CubeTexture;
  13269. })(BABYLON || (BABYLON = {}));
  13270. //# sourceMappingURL=babylon.cubeTexture.js.map
  13271. var BABYLON;
  13272. (function (BABYLON) {
  13273. var RenderTargetTexture = (function (_super) {
  13274. __extends(RenderTargetTexture, _super);
  13275. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  13276. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  13277. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  13278. _super.call(this, null, scene, !generateMipMaps);
  13279. this.renderList = new Array();
  13280. this.renderParticles = true;
  13281. this.renderSprites = false;
  13282. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  13283. this._currentRefreshId = -1;
  13284. this._refreshRate = 1;
  13285. this.name = name;
  13286. this.isRenderTarget = true;
  13287. this._size = size;
  13288. this._generateMipMaps = generateMipMaps;
  13289. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  13290. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  13291. // Rendering groups
  13292. this._renderingManager = new BABYLON.RenderingManager(scene);
  13293. }
  13294. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  13295. this._currentRefreshId = -1;
  13296. };
  13297. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  13298. get: function () {
  13299. return this._refreshRate;
  13300. },
  13301. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13302. set: function (value) {
  13303. this._refreshRate = value;
  13304. this.resetRefreshCounter();
  13305. },
  13306. enumerable: true,
  13307. configurable: true
  13308. });
  13309. RenderTargetTexture.prototype._shouldRender = function () {
  13310. if (this._currentRefreshId === -1) {
  13311. this._currentRefreshId = 1;
  13312. return true;
  13313. }
  13314. if (this.refreshRate === this._currentRefreshId) {
  13315. this._currentRefreshId = 1;
  13316. return true;
  13317. }
  13318. this._currentRefreshId++;
  13319. return false;
  13320. };
  13321. RenderTargetTexture.prototype.isReady = function () {
  13322. if (!this.getScene().renderTargetsEnabled) {
  13323. return false;
  13324. }
  13325. return _super.prototype.isReady.call(this);
  13326. };
  13327. RenderTargetTexture.prototype.getRenderSize = function () {
  13328. return this._size;
  13329. };
  13330. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  13331. get: function () {
  13332. return true;
  13333. },
  13334. enumerable: true,
  13335. configurable: true
  13336. });
  13337. RenderTargetTexture.prototype.scale = function (ratio) {
  13338. var newSize = this._size * ratio;
  13339. this.resize(newSize, this._generateMipMaps);
  13340. };
  13341. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  13342. this.releaseInternalTexture();
  13343. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13344. };
  13345. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  13346. var scene = this.getScene();
  13347. var engine = scene.getEngine();
  13348. if (this._waitingRenderList) {
  13349. this.renderList = [];
  13350. for (var index = 0; index < this._waitingRenderList.length; index++) {
  13351. var id = this._waitingRenderList[index];
  13352. this.renderList.push(scene.getMeshByID(id));
  13353. }
  13354. delete this._waitingRenderList;
  13355. }
  13356. if (this.renderList && this.renderList.length === 0) {
  13357. return;
  13358. }
  13359. // Bind
  13360. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  13361. engine.bindFramebuffer(this._texture);
  13362. }
  13363. this._renderingManager.reset();
  13364. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  13365. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  13366. var mesh = currentRenderList[meshIndex];
  13367. if (mesh) {
  13368. if (!mesh.isReady()) {
  13369. // Reset _currentRefreshId
  13370. this.resetRefreshCounter();
  13371. continue;
  13372. }
  13373. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  13374. mesh._activate(scene.getRenderId());
  13375. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13376. var subMesh = mesh.subMeshes[subIndex];
  13377. scene._activeIndices += subMesh.indexCount;
  13378. this._renderingManager.dispatch(subMesh);
  13379. }
  13380. }
  13381. }
  13382. }
  13383. if (this.onBeforeRender) {
  13384. this.onBeforeRender();
  13385. }
  13386. // Clear
  13387. if (this.onClear) {
  13388. this.onClear(engine);
  13389. }
  13390. else {
  13391. engine.clear(scene.clearColor, true, true);
  13392. }
  13393. if (!this._doNotChangeAspectRatio) {
  13394. scene.updateTransformMatrix(true);
  13395. }
  13396. // Render
  13397. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  13398. if (useCameraPostProcess) {
  13399. scene.postProcessManager._finalizeFrame(false, this._texture);
  13400. }
  13401. if (!this._doNotChangeAspectRatio) {
  13402. scene.updateTransformMatrix(true);
  13403. }
  13404. if (this.onAfterRender) {
  13405. this.onAfterRender();
  13406. }
  13407. // Dump ?
  13408. if (dumpForDebug) {
  13409. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  13410. }
  13411. // Unbind
  13412. engine.unBindFramebuffer(this._texture);
  13413. if (this.onAfterUnbind) {
  13414. this.onAfterUnbind();
  13415. }
  13416. };
  13417. RenderTargetTexture.prototype.clone = function () {
  13418. var textureSize = this.getSize();
  13419. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13420. // Base texture
  13421. newTexture.hasAlpha = this.hasAlpha;
  13422. newTexture.level = this.level;
  13423. // RenderTarget Texture
  13424. newTexture.coordinatesMode = this.coordinatesMode;
  13425. newTexture.renderList = this.renderList.slice(0);
  13426. return newTexture;
  13427. };
  13428. return RenderTargetTexture;
  13429. })(BABYLON.Texture);
  13430. BABYLON.RenderTargetTexture = RenderTargetTexture;
  13431. })(BABYLON || (BABYLON = {}));
  13432. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  13433. var BABYLON;
  13434. (function (BABYLON) {
  13435. var ProceduralTexture = (function (_super) {
  13436. __extends(ProceduralTexture, _super);
  13437. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  13438. if (generateMipMaps === void 0) { generateMipMaps = true; }
  13439. _super.call(this, null, scene, !generateMipMaps);
  13440. this._currentRefreshId = -1;
  13441. this._refreshRate = 1;
  13442. this._vertexDeclaration = [2];
  13443. this._vertexStrideSize = 2 * 4;
  13444. this._uniforms = new Array();
  13445. this._samplers = new Array();
  13446. this._textures = new Array();
  13447. this._floats = new Array();
  13448. this._floatsArrays = {};
  13449. this._colors3 = new Array();
  13450. this._colors4 = new Array();
  13451. this._vectors2 = new Array();
  13452. this._vectors3 = new Array();
  13453. this._matrices = new Array();
  13454. this._fallbackTextureUsed = false;
  13455. scene._proceduralTextures.push(this);
  13456. this.name = name;
  13457. this.isRenderTarget = true;
  13458. this._size = size;
  13459. this._generateMipMaps = generateMipMaps;
  13460. this.setFragment(fragment);
  13461. this._fallbackTexture = fallbackTexture;
  13462. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  13463. // VBO
  13464. var vertices = [];
  13465. vertices.push(1, 1);
  13466. vertices.push(-1, 1);
  13467. vertices.push(-1, -1);
  13468. vertices.push(1, -1);
  13469. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13470. // Indices
  13471. var indices = [];
  13472. indices.push(0);
  13473. indices.push(1);
  13474. indices.push(2);
  13475. indices.push(0);
  13476. indices.push(2);
  13477. indices.push(3);
  13478. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13479. }
  13480. ProceduralTexture.prototype.reset = function () {
  13481. if (this._effect === undefined) {
  13482. return;
  13483. }
  13484. var engine = this.getScene().getEngine();
  13485. engine._releaseEffect(this._effect);
  13486. };
  13487. ProceduralTexture.prototype.isReady = function () {
  13488. var _this = this;
  13489. var engine = this.getScene().getEngine();
  13490. var shaders;
  13491. if (!this._fragment) {
  13492. return false;
  13493. }
  13494. if (this._fallbackTextureUsed) {
  13495. return true;
  13496. }
  13497. if (this._fragment.fragmentElement !== undefined) {
  13498. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  13499. }
  13500. else {
  13501. shaders = { vertex: "procedural", fragment: this._fragment };
  13502. }
  13503. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  13504. _this.releaseInternalTexture();
  13505. if (_this._fallbackTexture) {
  13506. _this._texture = _this._fallbackTexture._texture;
  13507. _this._texture.references++;
  13508. }
  13509. _this._fallbackTextureUsed = true;
  13510. });
  13511. return this._effect.isReady();
  13512. };
  13513. ProceduralTexture.prototype.resetRefreshCounter = function () {
  13514. this._currentRefreshId = -1;
  13515. };
  13516. ProceduralTexture.prototype.setFragment = function (fragment) {
  13517. this._fragment = fragment;
  13518. };
  13519. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  13520. get: function () {
  13521. return this._refreshRate;
  13522. },
  13523. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13524. set: function (value) {
  13525. this._refreshRate = value;
  13526. this.resetRefreshCounter();
  13527. },
  13528. enumerable: true,
  13529. configurable: true
  13530. });
  13531. ProceduralTexture.prototype._shouldRender = function () {
  13532. if (!this.isReady() || !this._texture) {
  13533. return false;
  13534. }
  13535. if (this._fallbackTextureUsed) {
  13536. return false;
  13537. }
  13538. if (this._currentRefreshId === -1) {
  13539. this._currentRefreshId = 1;
  13540. return true;
  13541. }
  13542. if (this.refreshRate === this._currentRefreshId) {
  13543. this._currentRefreshId = 1;
  13544. return true;
  13545. }
  13546. this._currentRefreshId++;
  13547. return false;
  13548. };
  13549. ProceduralTexture.prototype.getRenderSize = function () {
  13550. return this._size;
  13551. };
  13552. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  13553. if (this._fallbackTextureUsed) {
  13554. return;
  13555. }
  13556. this.releaseInternalTexture();
  13557. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13558. };
  13559. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  13560. if (this._uniforms.indexOf(uniformName) === -1) {
  13561. this._uniforms.push(uniformName);
  13562. }
  13563. };
  13564. ProceduralTexture.prototype.setTexture = function (name, texture) {
  13565. if (this._samplers.indexOf(name) === -1) {
  13566. this._samplers.push(name);
  13567. }
  13568. this._textures[name] = texture;
  13569. return this;
  13570. };
  13571. ProceduralTexture.prototype.setFloat = function (name, value) {
  13572. this._checkUniform(name);
  13573. this._floats[name] = value;
  13574. return this;
  13575. };
  13576. ProceduralTexture.prototype.setFloats = function (name, value) {
  13577. this._checkUniform(name);
  13578. this._floatsArrays[name] = value;
  13579. return this;
  13580. };
  13581. ProceduralTexture.prototype.setColor3 = function (name, value) {
  13582. this._checkUniform(name);
  13583. this._colors3[name] = value;
  13584. return this;
  13585. };
  13586. ProceduralTexture.prototype.setColor4 = function (name, value) {
  13587. this._checkUniform(name);
  13588. this._colors4[name] = value;
  13589. return this;
  13590. };
  13591. ProceduralTexture.prototype.setVector2 = function (name, value) {
  13592. this._checkUniform(name);
  13593. this._vectors2[name] = value;
  13594. return this;
  13595. };
  13596. ProceduralTexture.prototype.setVector3 = function (name, value) {
  13597. this._checkUniform(name);
  13598. this._vectors3[name] = value;
  13599. return this;
  13600. };
  13601. ProceduralTexture.prototype.setMatrix = function (name, value) {
  13602. this._checkUniform(name);
  13603. this._matrices[name] = value;
  13604. return this;
  13605. };
  13606. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13607. var scene = this.getScene();
  13608. var engine = scene.getEngine();
  13609. engine.bindFramebuffer(this._texture);
  13610. // Clear
  13611. engine.clear(scene.clearColor, true, true);
  13612. // Render
  13613. engine.enableEffect(this._effect);
  13614. engine.setState(false);
  13615. for (var name in this._textures) {
  13616. this._effect.setTexture(name, this._textures[name]);
  13617. }
  13618. for (name in this._floats) {
  13619. this._effect.setFloat(name, this._floats[name]);
  13620. }
  13621. for (name in this._floatsArrays) {
  13622. this._effect.setArray(name, this._floatsArrays[name]);
  13623. }
  13624. for (name in this._colors3) {
  13625. this._effect.setColor3(name, this._colors3[name]);
  13626. }
  13627. for (name in this._colors4) {
  13628. var color = this._colors4[name];
  13629. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  13630. }
  13631. for (name in this._vectors2) {
  13632. this._effect.setVector2(name, this._vectors2[name]);
  13633. }
  13634. for (name in this._vectors3) {
  13635. this._effect.setVector3(name, this._vectors3[name]);
  13636. }
  13637. for (name in this._matrices) {
  13638. this._effect.setMatrix(name, this._matrices[name]);
  13639. }
  13640. // VBOs
  13641. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13642. // Draw order
  13643. engine.draw(true, 0, 6);
  13644. // Unbind
  13645. engine.unBindFramebuffer(this._texture);
  13646. };
  13647. ProceduralTexture.prototype.clone = function () {
  13648. var textureSize = this.getSize();
  13649. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  13650. // Base texture
  13651. newTexture.hasAlpha = this.hasAlpha;
  13652. newTexture.level = this.level;
  13653. // RenderTarget Texture
  13654. newTexture.coordinatesMode = this.coordinatesMode;
  13655. return newTexture;
  13656. };
  13657. ProceduralTexture.prototype.dispose = function () {
  13658. var index = this.getScene()._proceduralTextures.indexOf(this);
  13659. if (index >= 0) {
  13660. this.getScene()._proceduralTextures.splice(index, 1);
  13661. }
  13662. _super.prototype.dispose.call(this);
  13663. };
  13664. return ProceduralTexture;
  13665. })(BABYLON.Texture);
  13666. BABYLON.ProceduralTexture = ProceduralTexture;
  13667. })(BABYLON || (BABYLON = {}));
  13668. //# sourceMappingURL=babylon.proceduralTexture.js.map
  13669. var BABYLON;
  13670. (function (BABYLON) {
  13671. var WoodProceduralTexture = (function (_super) {
  13672. __extends(WoodProceduralTexture, _super);
  13673. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13674. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  13675. this._ampScale = 100.0;
  13676. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  13677. this.updateShaderUniforms();
  13678. this.refreshRate = 0;
  13679. }
  13680. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  13681. this.setFloat("ampScale", this._ampScale);
  13682. this.setColor3("woodColor", this._woodColor);
  13683. };
  13684. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  13685. get: function () {
  13686. return this._ampScale;
  13687. },
  13688. set: function (value) {
  13689. this._ampScale = value;
  13690. this.updateShaderUniforms();
  13691. },
  13692. enumerable: true,
  13693. configurable: true
  13694. });
  13695. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  13696. get: function () {
  13697. return this._woodColor;
  13698. },
  13699. set: function (value) {
  13700. this._woodColor = value;
  13701. this.updateShaderUniforms();
  13702. },
  13703. enumerable: true,
  13704. configurable: true
  13705. });
  13706. return WoodProceduralTexture;
  13707. })(BABYLON.ProceduralTexture);
  13708. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  13709. var FireProceduralTexture = (function (_super) {
  13710. __extends(FireProceduralTexture, _super);
  13711. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13712. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  13713. this._time = 0.0;
  13714. this._speed = new BABYLON.Vector2(0.5, 0.3);
  13715. this._autoGenerateTime = true;
  13716. this._alphaThreshold = 0.5;
  13717. this._fireColors = FireProceduralTexture.RedFireColors;
  13718. this.updateShaderUniforms();
  13719. this.refreshRate = 1;
  13720. }
  13721. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  13722. this.setFloat("time", this._time);
  13723. this.setVector2("speed", this._speed);
  13724. this.setColor3("c1", this._fireColors[0]);
  13725. this.setColor3("c2", this._fireColors[1]);
  13726. this.setColor3("c3", this._fireColors[2]);
  13727. this.setColor3("c4", this._fireColors[3]);
  13728. this.setColor3("c5", this._fireColors[4]);
  13729. this.setColor3("c6", this._fireColors[5]);
  13730. this.setFloat("alphaThreshold", this._alphaThreshold);
  13731. };
  13732. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13733. if (this._autoGenerateTime) {
  13734. this._time += this.getScene().getAnimationRatio() * 0.03;
  13735. this.updateShaderUniforms();
  13736. }
  13737. _super.prototype.render.call(this, useCameraPostProcess);
  13738. };
  13739. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  13740. get: function () {
  13741. return [
  13742. new BABYLON.Color3(0.5, 0.0, 1.0),
  13743. new BABYLON.Color3(0.9, 0.0, 1.0),
  13744. new BABYLON.Color3(0.2, 0.0, 1.0),
  13745. new BABYLON.Color3(1.0, 0.9, 1.0),
  13746. new BABYLON.Color3(0.1, 0.1, 1.0),
  13747. new BABYLON.Color3(0.9, 0.9, 1.0)
  13748. ];
  13749. },
  13750. enumerable: true,
  13751. configurable: true
  13752. });
  13753. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  13754. get: function () {
  13755. return [
  13756. new BABYLON.Color3(0.5, 1.0, 0.0),
  13757. new BABYLON.Color3(0.5, 1.0, 0.0),
  13758. new BABYLON.Color3(0.3, 0.4, 0.0),
  13759. new BABYLON.Color3(0.5, 1.0, 0.0),
  13760. new BABYLON.Color3(0.2, 0.0, 0.0),
  13761. new BABYLON.Color3(0.5, 1.0, 0.0)
  13762. ];
  13763. },
  13764. enumerable: true,
  13765. configurable: true
  13766. });
  13767. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  13768. get: function () {
  13769. return [
  13770. new BABYLON.Color3(0.5, 0.0, 0.1),
  13771. new BABYLON.Color3(0.9, 0.0, 0.0),
  13772. new BABYLON.Color3(0.2, 0.0, 0.0),
  13773. new BABYLON.Color3(1.0, 0.9, 0.0),
  13774. new BABYLON.Color3(0.1, 0.1, 0.1),
  13775. new BABYLON.Color3(0.9, 0.9, 0.9)
  13776. ];
  13777. },
  13778. enumerable: true,
  13779. configurable: true
  13780. });
  13781. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  13782. get: function () {
  13783. return [
  13784. new BABYLON.Color3(0.1, 0.0, 0.5),
  13785. new BABYLON.Color3(0.0, 0.0, 0.5),
  13786. new BABYLON.Color3(0.1, 0.0, 0.2),
  13787. new BABYLON.Color3(0.0, 0.0, 1.0),
  13788. new BABYLON.Color3(0.1, 0.2, 0.3),
  13789. new BABYLON.Color3(0.0, 0.2, 0.9)
  13790. ];
  13791. },
  13792. enumerable: true,
  13793. configurable: true
  13794. });
  13795. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  13796. get: function () {
  13797. return this._fireColors;
  13798. },
  13799. set: function (value) {
  13800. this._fireColors = value;
  13801. this.updateShaderUniforms();
  13802. },
  13803. enumerable: true,
  13804. configurable: true
  13805. });
  13806. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  13807. get: function () {
  13808. return this._time;
  13809. },
  13810. set: function (value) {
  13811. this._time = value;
  13812. this.updateShaderUniforms();
  13813. },
  13814. enumerable: true,
  13815. configurable: true
  13816. });
  13817. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  13818. get: function () {
  13819. return this._speed;
  13820. },
  13821. set: function (value) {
  13822. this._speed = value;
  13823. this.updateShaderUniforms();
  13824. },
  13825. enumerable: true,
  13826. configurable: true
  13827. });
  13828. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  13829. get: function () {
  13830. return this._alphaThreshold;
  13831. },
  13832. set: function (value) {
  13833. this._alphaThreshold = value;
  13834. this.updateShaderUniforms();
  13835. },
  13836. enumerable: true,
  13837. configurable: true
  13838. });
  13839. return FireProceduralTexture;
  13840. })(BABYLON.ProceduralTexture);
  13841. BABYLON.FireProceduralTexture = FireProceduralTexture;
  13842. var CloudProceduralTexture = (function (_super) {
  13843. __extends(CloudProceduralTexture, _super);
  13844. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13845. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  13846. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  13847. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  13848. this.updateShaderUniforms();
  13849. this.refreshRate = 0;
  13850. }
  13851. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  13852. this.setColor3("skyColor", this._skyColor);
  13853. this.setColor3("cloudColor", this._cloudColor);
  13854. };
  13855. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  13856. get: function () {
  13857. return this._skyColor;
  13858. },
  13859. set: function (value) {
  13860. this._skyColor = value;
  13861. this.updateShaderUniforms();
  13862. },
  13863. enumerable: true,
  13864. configurable: true
  13865. });
  13866. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  13867. get: function () {
  13868. return this._cloudColor;
  13869. },
  13870. set: function (value) {
  13871. this._cloudColor = value;
  13872. this.updateShaderUniforms();
  13873. },
  13874. enumerable: true,
  13875. configurable: true
  13876. });
  13877. return CloudProceduralTexture;
  13878. })(BABYLON.ProceduralTexture);
  13879. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  13880. var GrassProceduralTexture = (function (_super) {
  13881. __extends(GrassProceduralTexture, _super);
  13882. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13883. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  13884. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  13885. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  13886. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  13887. this._groundColor = new BABYLON.Color3(1, 1, 1);
  13888. this._grassColors = [
  13889. new BABYLON.Color3(0.29, 0.38, 0.02),
  13890. new BABYLON.Color3(0.36, 0.49, 0.09),
  13891. new BABYLON.Color3(0.51, 0.6, 0.28)
  13892. ];
  13893. this.updateShaderUniforms();
  13894. this.refreshRate = 0;
  13895. }
  13896. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13897. this.setColor3("herb1Color", this._grassColors[0]);
  13898. this.setColor3("herb2Color", this._grassColors[1]);
  13899. this.setColor3("herb3Color", this._grassColors[2]);
  13900. this.setColor3("groundColor", this._groundColor);
  13901. };
  13902. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13903. get: function () {
  13904. return this._grassColors;
  13905. },
  13906. set: function (value) {
  13907. this._grassColors = value;
  13908. this.updateShaderUniforms();
  13909. },
  13910. enumerable: true,
  13911. configurable: true
  13912. });
  13913. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13914. get: function () {
  13915. return this._groundColor;
  13916. },
  13917. set: function (value) {
  13918. this.groundColor = value;
  13919. this.updateShaderUniforms();
  13920. },
  13921. enumerable: true,
  13922. configurable: true
  13923. });
  13924. return GrassProceduralTexture;
  13925. })(BABYLON.ProceduralTexture);
  13926. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13927. var RoadProceduralTexture = (function (_super) {
  13928. __extends(RoadProceduralTexture, _super);
  13929. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13930. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13931. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13932. this.updateShaderUniforms();
  13933. this.refreshRate = 0;
  13934. }
  13935. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13936. this.setColor3("roadColor", this._roadColor);
  13937. };
  13938. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13939. get: function () {
  13940. return this._roadColor;
  13941. },
  13942. set: function (value) {
  13943. this._roadColor = value;
  13944. this.updateShaderUniforms();
  13945. },
  13946. enumerable: true,
  13947. configurable: true
  13948. });
  13949. return RoadProceduralTexture;
  13950. })(BABYLON.ProceduralTexture);
  13951. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13952. var BrickProceduralTexture = (function (_super) {
  13953. __extends(BrickProceduralTexture, _super);
  13954. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13955. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13956. this._numberOfBricksHeight = 15;
  13957. this._numberOfBricksWidth = 5;
  13958. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13959. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13960. this.updateShaderUniforms();
  13961. this.refreshRate = 0;
  13962. }
  13963. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13964. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13965. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13966. this.setColor3("brickColor", this._brickColor);
  13967. this.setColor3("jointColor", this._jointColor);
  13968. };
  13969. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13970. get: function () {
  13971. return this._numberOfBricksHeight;
  13972. },
  13973. set: function (value) {
  13974. this._numberOfBricksHeight = value;
  13975. this.updateShaderUniforms();
  13976. },
  13977. enumerable: true,
  13978. configurable: true
  13979. });
  13980. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13981. get: function () {
  13982. return this._numberOfBricksWidth;
  13983. },
  13984. set: function (value) {
  13985. this._numberOfBricksHeight = value;
  13986. this.updateShaderUniforms();
  13987. },
  13988. enumerable: true,
  13989. configurable: true
  13990. });
  13991. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13992. get: function () {
  13993. return this._jointColor;
  13994. },
  13995. set: function (value) {
  13996. this._jointColor = value;
  13997. this.updateShaderUniforms();
  13998. },
  13999. enumerable: true,
  14000. configurable: true
  14001. });
  14002. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  14003. get: function () {
  14004. return this._brickColor;
  14005. },
  14006. set: function (value) {
  14007. this._brickColor = value;
  14008. this.updateShaderUniforms();
  14009. },
  14010. enumerable: true,
  14011. configurable: true
  14012. });
  14013. return BrickProceduralTexture;
  14014. })(BABYLON.ProceduralTexture);
  14015. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  14016. var MarbleProceduralTexture = (function (_super) {
  14017. __extends(MarbleProceduralTexture, _super);
  14018. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  14019. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  14020. this._numberOfTilesHeight = 3;
  14021. this._numberOfTilesWidth = 3;
  14022. this._amplitude = 9.0;
  14023. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  14024. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  14025. this.updateShaderUniforms();
  14026. this.refreshRate = 0;
  14027. }
  14028. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  14029. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  14030. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  14031. this.setFloat("amplitude", this._amplitude);
  14032. this.setColor3("marbleColor", this._marbleColor);
  14033. this.setColor3("jointColor", this._jointColor);
  14034. };
  14035. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  14036. get: function () {
  14037. return this._numberOfTilesHeight;
  14038. },
  14039. set: function (value) {
  14040. this._numberOfTilesHeight = value;
  14041. this.updateShaderUniforms();
  14042. },
  14043. enumerable: true,
  14044. configurable: true
  14045. });
  14046. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  14047. get: function () {
  14048. return this._numberOfTilesWidth;
  14049. },
  14050. set: function (value) {
  14051. this._numberOfTilesWidth = value;
  14052. this.updateShaderUniforms();
  14053. },
  14054. enumerable: true,
  14055. configurable: true
  14056. });
  14057. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  14058. get: function () {
  14059. return this._jointColor;
  14060. },
  14061. set: function (value) {
  14062. this._jointColor = value;
  14063. this.updateShaderUniforms();
  14064. },
  14065. enumerable: true,
  14066. configurable: true
  14067. });
  14068. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  14069. get: function () {
  14070. return this._marbleColor;
  14071. },
  14072. set: function (value) {
  14073. this._marbleColor = value;
  14074. this.updateShaderUniforms();
  14075. },
  14076. enumerable: true,
  14077. configurable: true
  14078. });
  14079. return MarbleProceduralTexture;
  14080. })(BABYLON.ProceduralTexture);
  14081. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  14082. })(BABYLON || (BABYLON = {}));
  14083. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  14084. var BABYLON;
  14085. (function (BABYLON) {
  14086. var CustomProceduralTexture = (function (_super) {
  14087. __extends(CustomProceduralTexture, _super);
  14088. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  14089. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  14090. this._animate = true;
  14091. this._time = 0;
  14092. this._texturePath = texturePath;
  14093. //Try to load json
  14094. this.loadJson(texturePath);
  14095. this.refreshRate = 1;
  14096. }
  14097. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  14098. var _this = this;
  14099. var that = this;
  14100. function noConfigFile() {
  14101. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  14102. try {
  14103. that.setFragment(that._texturePath);
  14104. }
  14105. catch (ex) {
  14106. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  14107. }
  14108. }
  14109. var configFileUrl = jsonUrl + "/config.json";
  14110. var xhr = new XMLHttpRequest();
  14111. xhr.open("GET", configFileUrl, true);
  14112. xhr.addEventListener("load", function () {
  14113. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14114. try {
  14115. _this._config = JSON.parse(xhr.response);
  14116. _this.updateShaderUniforms();
  14117. _this.updateTextures();
  14118. _this.setFragment(_this._texturePath + "/custom");
  14119. _this._animate = _this._config.animate;
  14120. _this.refreshRate = _this._config.refreshrate;
  14121. }
  14122. catch (ex) {
  14123. noConfigFile();
  14124. }
  14125. }
  14126. else {
  14127. noConfigFile();
  14128. }
  14129. }, false);
  14130. xhr.addEventListener("error", function () {
  14131. noConfigFile();
  14132. }, false);
  14133. try {
  14134. xhr.send();
  14135. }
  14136. catch (ex) {
  14137. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  14138. }
  14139. };
  14140. CustomProceduralTexture.prototype.isReady = function () {
  14141. if (!_super.prototype.isReady.call(this)) {
  14142. return false;
  14143. }
  14144. for (var name in this._textures) {
  14145. var texture = this._textures[name];
  14146. if (!texture.isReady()) {
  14147. return false;
  14148. }
  14149. }
  14150. return true;
  14151. };
  14152. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  14153. if (this._animate) {
  14154. this._time += this.getScene().getAnimationRatio() * 0.03;
  14155. this.updateShaderUniforms();
  14156. }
  14157. _super.prototype.render.call(this, useCameraPostProcess);
  14158. };
  14159. CustomProceduralTexture.prototype.updateTextures = function () {
  14160. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  14161. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  14162. }
  14163. };
  14164. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  14165. if (this._config) {
  14166. for (var j = 0; j < this._config.uniforms.length; j++) {
  14167. var uniform = this._config.uniforms[j];
  14168. switch (uniform.type) {
  14169. case "float":
  14170. this.setFloat(uniform.name, uniform.value);
  14171. break;
  14172. case "color3":
  14173. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  14174. break;
  14175. case "color4":
  14176. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  14177. break;
  14178. case "vector2":
  14179. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  14180. break;
  14181. case "vector3":
  14182. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  14183. break;
  14184. }
  14185. }
  14186. }
  14187. this.setFloat("time", this._time);
  14188. };
  14189. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  14190. get: function () {
  14191. return this._animate;
  14192. },
  14193. set: function (value) {
  14194. this._animate = value;
  14195. },
  14196. enumerable: true,
  14197. configurable: true
  14198. });
  14199. return CustomProceduralTexture;
  14200. })(BABYLON.ProceduralTexture);
  14201. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  14202. })(BABYLON || (BABYLON = {}));
  14203. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  14204. var BABYLON;
  14205. (function (BABYLON) {
  14206. var MirrorTexture = (function (_super) {
  14207. __extends(MirrorTexture, _super);
  14208. function MirrorTexture(name, size, scene, generateMipMaps) {
  14209. var _this = this;
  14210. _super.call(this, name, size, scene, generateMipMaps, true);
  14211. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  14212. this._transformMatrix = BABYLON.Matrix.Zero();
  14213. this._mirrorMatrix = BABYLON.Matrix.Zero();
  14214. this.onBeforeRender = function () {
  14215. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  14216. _this._savedViewMatrix = scene.getViewMatrix();
  14217. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  14218. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  14219. scene.clipPlane = _this.mirrorPlane;
  14220. scene.getEngine().cullBackFaces = false;
  14221. };
  14222. this.onAfterRender = function () {
  14223. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  14224. scene.getEngine().cullBackFaces = true;
  14225. delete scene.clipPlane;
  14226. };
  14227. }
  14228. MirrorTexture.prototype.clone = function () {
  14229. var textureSize = this.getSize();
  14230. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  14231. // Base texture
  14232. newTexture.hasAlpha = this.hasAlpha;
  14233. newTexture.level = this.level;
  14234. // Mirror Texture
  14235. newTexture.mirrorPlane = this.mirrorPlane.clone();
  14236. newTexture.renderList = this.renderList.slice(0);
  14237. return newTexture;
  14238. };
  14239. return MirrorTexture;
  14240. })(BABYLON.RenderTargetTexture);
  14241. BABYLON.MirrorTexture = MirrorTexture;
  14242. })(BABYLON || (BABYLON = {}));
  14243. //# sourceMappingURL=babylon.mirrorTexture.js.map
  14244. var BABYLON;
  14245. (function (BABYLON) {
  14246. var DynamicTexture = (function (_super) {
  14247. __extends(DynamicTexture, _super);
  14248. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  14249. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14250. _super.call(this, null, scene, !generateMipMaps);
  14251. this.name = name;
  14252. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14253. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14254. this._generateMipMaps = generateMipMaps;
  14255. if (options.getContext) {
  14256. this._canvas = options;
  14257. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14258. }
  14259. else {
  14260. this._canvas = document.createElement("canvas");
  14261. if (options.width) {
  14262. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14263. }
  14264. else {
  14265. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  14266. }
  14267. }
  14268. var textureSize = this.getSize();
  14269. this._canvas.width = textureSize.width;
  14270. this._canvas.height = textureSize.height;
  14271. this._context = this._canvas.getContext("2d");
  14272. }
  14273. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  14274. get: function () {
  14275. return true;
  14276. },
  14277. enumerable: true,
  14278. configurable: true
  14279. });
  14280. DynamicTexture.prototype.scale = function (ratio) {
  14281. var textureSize = this.getSize();
  14282. textureSize.width *= ratio;
  14283. textureSize.height *= ratio;
  14284. this._canvas.width = textureSize.width;
  14285. this._canvas.height = textureSize.height;
  14286. this.releaseInternalTexture();
  14287. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  14288. };
  14289. DynamicTexture.prototype.getContext = function () {
  14290. return this._context;
  14291. };
  14292. DynamicTexture.prototype.clear = function () {
  14293. var size = this.getSize();
  14294. this._context.fillRect(0, 0, size.width, size.height);
  14295. };
  14296. DynamicTexture.prototype.update = function (invertY) {
  14297. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  14298. };
  14299. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  14300. if (update === void 0) { update = true; }
  14301. var size = this.getSize();
  14302. if (clearColor) {
  14303. this._context.fillStyle = clearColor;
  14304. this._context.fillRect(0, 0, size.width, size.height);
  14305. }
  14306. this._context.font = font;
  14307. if (x === null) {
  14308. var textSize = this._context.measureText(text);
  14309. x = (size.width - textSize.width) / 2;
  14310. }
  14311. this._context.fillStyle = color;
  14312. this._context.fillText(text, x, y);
  14313. if (update) {
  14314. this.update(invertY);
  14315. }
  14316. };
  14317. DynamicTexture.prototype.clone = function () {
  14318. var textureSize = this.getSize();
  14319. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  14320. // Base texture
  14321. newTexture.hasAlpha = this.hasAlpha;
  14322. newTexture.level = this.level;
  14323. // Dynamic Texture
  14324. newTexture.wrapU = this.wrapU;
  14325. newTexture.wrapV = this.wrapV;
  14326. return newTexture;
  14327. };
  14328. return DynamicTexture;
  14329. })(BABYLON.Texture);
  14330. BABYLON.DynamicTexture = DynamicTexture;
  14331. })(BABYLON || (BABYLON = {}));
  14332. //# sourceMappingURL=babylon.dynamicTexture.js.map
  14333. var BABYLON;
  14334. (function (BABYLON) {
  14335. var VideoTexture = (function (_super) {
  14336. __extends(VideoTexture, _super);
  14337. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  14338. var _this = this;
  14339. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14340. _super.call(this, null, scene, !generateMipMaps, invertY);
  14341. this._autoLaunch = true;
  14342. this.name = name;
  14343. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  14344. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  14345. var requiredWidth = size.width || size;
  14346. var requiredHeight = size.height || size;
  14347. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  14348. var textureSize = this.getSize();
  14349. this.video = document.createElement("video");
  14350. this.video.width = textureSize.width;
  14351. this.video.height = textureSize.height;
  14352. this.video.autoplay = false;
  14353. this.video.loop = true;
  14354. this.video.addEventListener("canplaythrough", function () {
  14355. if (_this._texture) {
  14356. _this._texture.isReady = true;
  14357. }
  14358. });
  14359. urls.forEach(function (url) {
  14360. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  14361. var source = document.createElement("source");
  14362. source.src = url;
  14363. _this.video.appendChild(source);
  14364. });
  14365. this._lastUpdate = BABYLON.Tools.Now;
  14366. }
  14367. VideoTexture.prototype.update = function () {
  14368. if (this._autoLaunch) {
  14369. this._autoLaunch = false;
  14370. this.video.play();
  14371. }
  14372. var now = BABYLON.Tools.Now;
  14373. if (now - this._lastUpdate < 15) {
  14374. return false;
  14375. }
  14376. this._lastUpdate = now;
  14377. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  14378. return true;
  14379. };
  14380. return VideoTexture;
  14381. })(BABYLON.Texture);
  14382. BABYLON.VideoTexture = VideoTexture;
  14383. })(BABYLON || (BABYLON = {}));
  14384. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  14385. (function (BABYLON) {
  14386. var EffectFallbacks = (function () {
  14387. function EffectFallbacks() {
  14388. this._defines = {};
  14389. this._currentRank = 32;
  14390. this._maxRank = -1;
  14391. }
  14392. EffectFallbacks.prototype.addFallback = function (rank, define) {
  14393. if (!this._defines[rank]) {
  14394. if (rank < this._currentRank) {
  14395. this._currentRank = rank;
  14396. }
  14397. if (rank > this._maxRank) {
  14398. this._maxRank = rank;
  14399. }
  14400. this._defines[rank] = new Array();
  14401. }
  14402. this._defines[rank].push(define);
  14403. };
  14404. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  14405. get: function () {
  14406. return this._currentRank <= this._maxRank;
  14407. },
  14408. enumerable: true,
  14409. configurable: true
  14410. });
  14411. EffectFallbacks.prototype.reduce = function (currentDefines) {
  14412. var currentFallbacks = this._defines[this._currentRank];
  14413. for (var index = 0; index < currentFallbacks.length; index++) {
  14414. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  14415. }
  14416. this._currentRank++;
  14417. return currentDefines;
  14418. };
  14419. return EffectFallbacks;
  14420. })();
  14421. BABYLON.EffectFallbacks = EffectFallbacks;
  14422. var Effect = (function () {
  14423. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  14424. var _this = this;
  14425. this._isReady = false;
  14426. this._compilationError = "";
  14427. this._valueCache = [];
  14428. this._engine = engine;
  14429. this.name = baseName;
  14430. this.defines = defines;
  14431. this._uniformsNames = uniformsNames.concat(samplers);
  14432. this._samplers = samplers;
  14433. this._attributesNames = attributesNames;
  14434. this.onError = onError;
  14435. this.onCompiled = onCompiled;
  14436. var vertexSource;
  14437. var fragmentSource;
  14438. if (baseName.vertexElement) {
  14439. vertexSource = document.getElementById(baseName.vertexElement);
  14440. if (!vertexSource) {
  14441. vertexSource = baseName.vertexElement;
  14442. }
  14443. }
  14444. else {
  14445. vertexSource = baseName.vertex || baseName;
  14446. }
  14447. if (baseName.fragmentElement) {
  14448. fragmentSource = document.getElementById(baseName.fragmentElement);
  14449. if (!fragmentSource) {
  14450. fragmentSource = baseName.fragmentElement;
  14451. }
  14452. }
  14453. else {
  14454. fragmentSource = baseName.fragment || baseName;
  14455. }
  14456. this._loadVertexShader(vertexSource, function (vertexCode) {
  14457. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  14458. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  14459. });
  14460. });
  14461. }
  14462. // Properties
  14463. Effect.prototype.isReady = function () {
  14464. return this._isReady;
  14465. };
  14466. Effect.prototype.getProgram = function () {
  14467. return this._program;
  14468. };
  14469. Effect.prototype.getAttributesNames = function () {
  14470. return this._attributesNames;
  14471. };
  14472. Effect.prototype.getAttributeLocation = function (index) {
  14473. return this._attributes[index];
  14474. };
  14475. Effect.prototype.getAttributeLocationByName = function (name) {
  14476. var index = this._attributesNames.indexOf(name);
  14477. return this._attributes[index];
  14478. };
  14479. Effect.prototype.getAttributesCount = function () {
  14480. return this._attributes.length;
  14481. };
  14482. Effect.prototype.getUniformIndex = function (uniformName) {
  14483. return this._uniformsNames.indexOf(uniformName);
  14484. };
  14485. Effect.prototype.getUniform = function (uniformName) {
  14486. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  14487. };
  14488. Effect.prototype.getSamplers = function () {
  14489. return this._samplers;
  14490. };
  14491. Effect.prototype.getCompilationError = function () {
  14492. return this._compilationError;
  14493. };
  14494. // Methods
  14495. Effect.prototype._loadVertexShader = function (vertex, callback) {
  14496. // DOM element ?
  14497. if (vertex instanceof HTMLElement) {
  14498. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  14499. callback(vertexCode);
  14500. return;
  14501. }
  14502. // Is in local store ?
  14503. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  14504. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  14505. return;
  14506. }
  14507. var vertexShaderUrl;
  14508. if (vertex[0] === ".") {
  14509. vertexShaderUrl = vertex;
  14510. }
  14511. else {
  14512. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  14513. }
  14514. // Vertex shader
  14515. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  14516. };
  14517. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  14518. // DOM element ?
  14519. if (fragment instanceof HTMLElement) {
  14520. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  14521. callback(fragmentCode);
  14522. return;
  14523. }
  14524. // Is in local store ?
  14525. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  14526. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  14527. return;
  14528. }
  14529. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  14530. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  14531. return;
  14532. }
  14533. var fragmentShaderUrl;
  14534. if (fragment[0] === ".") {
  14535. fragmentShaderUrl = fragment;
  14536. }
  14537. else {
  14538. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  14539. }
  14540. // Fragment shader
  14541. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  14542. };
  14543. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  14544. try {
  14545. var engine = this._engine;
  14546. if (!engine.getCaps().highPrecisionShaderSupported) {
  14547. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14548. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14549. }
  14550. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  14551. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  14552. this._attributes = engine.getAttributes(this._program, attributesNames);
  14553. for (var index = 0; index < this._samplers.length; index++) {
  14554. var sampler = this.getUniform(this._samplers[index]);
  14555. if (sampler == null) {
  14556. this._samplers.splice(index, 1);
  14557. index--;
  14558. }
  14559. }
  14560. engine.bindSamplers(this);
  14561. this._isReady = true;
  14562. if (this.onCompiled) {
  14563. this.onCompiled(this);
  14564. }
  14565. }
  14566. catch (e) {
  14567. // Is it a problem with precision?
  14568. if (e.message.indexOf("highp") !== -1) {
  14569. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14570. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14571. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14572. return;
  14573. }
  14574. // Let's go through fallbacks then
  14575. if (fallbacks && fallbacks.isMoreFallbacks) {
  14576. defines = fallbacks.reduce(defines);
  14577. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14578. }
  14579. else {
  14580. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  14581. BABYLON.Tools.Error("Defines: " + defines);
  14582. BABYLON.Tools.Error("Error: " + e.message);
  14583. this._compilationError = e.message;
  14584. if (this.onError) {
  14585. this.onError(this, this._compilationError);
  14586. }
  14587. }
  14588. }
  14589. };
  14590. Effect.prototype._bindTexture = function (channel, texture) {
  14591. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  14592. };
  14593. Effect.prototype.setTexture = function (channel, texture) {
  14594. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  14595. };
  14596. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14597. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  14598. };
  14599. //public _cacheMatrix(uniformName, matrix) {
  14600. // if (!this._valueCache[uniformName]) {
  14601. // this._valueCache[uniformName] = new BABYLON.Matrix();
  14602. // }
  14603. // for (var index = 0; index < 16; index++) {
  14604. // this._valueCache[uniformName].m[index] = matrix.m[index];
  14605. // }
  14606. //};
  14607. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  14608. if (!this._valueCache[uniformName]) {
  14609. this._valueCache[uniformName] = [x, y];
  14610. return;
  14611. }
  14612. this._valueCache[uniformName][0] = x;
  14613. this._valueCache[uniformName][1] = y;
  14614. };
  14615. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  14616. if (!this._valueCache[uniformName]) {
  14617. this._valueCache[uniformName] = [x, y, z];
  14618. return;
  14619. }
  14620. this._valueCache[uniformName][0] = x;
  14621. this._valueCache[uniformName][1] = y;
  14622. this._valueCache[uniformName][2] = z;
  14623. };
  14624. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  14625. if (!this._valueCache[uniformName]) {
  14626. this._valueCache[uniformName] = [x, y, z, w];
  14627. return;
  14628. }
  14629. this._valueCache[uniformName][0] = x;
  14630. this._valueCache[uniformName][1] = y;
  14631. this._valueCache[uniformName][2] = z;
  14632. this._valueCache[uniformName][3] = w;
  14633. };
  14634. Effect.prototype.setArray = function (uniformName, array) {
  14635. this._engine.setArray(this.getUniform(uniformName), array);
  14636. return this;
  14637. };
  14638. Effect.prototype.setArray2 = function (uniformName, array) {
  14639. this._engine.setArray2(this.getUniform(uniformName), array);
  14640. return this;
  14641. };
  14642. Effect.prototype.setArray3 = function (uniformName, array) {
  14643. this._engine.setArray3(this.getUniform(uniformName), array);
  14644. return this;
  14645. };
  14646. Effect.prototype.setArray4 = function (uniformName, array) {
  14647. this._engine.setArray4(this.getUniform(uniformName), array);
  14648. return this;
  14649. };
  14650. Effect.prototype.setMatrices = function (uniformName, matrices) {
  14651. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  14652. return this;
  14653. };
  14654. Effect.prototype.setMatrix = function (uniformName, matrix) {
  14655. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  14656. // return;
  14657. //this._cacheMatrix(uniformName, matrix);
  14658. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  14659. return this;
  14660. };
  14661. Effect.prototype.setFloat = function (uniformName, value) {
  14662. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  14663. return this;
  14664. this._valueCache[uniformName] = value;
  14665. this._engine.setFloat(this.getUniform(uniformName), value);
  14666. return this;
  14667. };
  14668. Effect.prototype.setBool = function (uniformName, bool) {
  14669. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  14670. return this;
  14671. this._valueCache[uniformName] = bool;
  14672. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  14673. return this;
  14674. };
  14675. Effect.prototype.setVector2 = function (uniformName, vector2) {
  14676. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  14677. return this;
  14678. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  14679. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  14680. return this;
  14681. };
  14682. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  14683. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  14684. return this;
  14685. this._cacheFloat2(uniformName, x, y);
  14686. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  14687. return this;
  14688. };
  14689. Effect.prototype.setVector3 = function (uniformName, vector3) {
  14690. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  14691. return this;
  14692. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  14693. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  14694. return this;
  14695. };
  14696. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  14697. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  14698. return this;
  14699. this._cacheFloat3(uniformName, x, y, z);
  14700. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  14701. return this;
  14702. };
  14703. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  14704. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  14705. return this;
  14706. this._cacheFloat4(uniformName, x, y, z, w);
  14707. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  14708. return this;
  14709. };
  14710. Effect.prototype.setColor3 = function (uniformName, color3) {
  14711. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  14712. return this;
  14713. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  14714. this._engine.setColor3(this.getUniform(uniformName), color3);
  14715. return this;
  14716. };
  14717. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  14718. 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)
  14719. return this;
  14720. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  14721. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  14722. return this;
  14723. };
  14724. // Statics
  14725. Effect.ShadersStore={anaglyphPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n\nvoid main(void)\n{\nvec4 leftFrag = texture2D(leftSampler, vUV);\nleftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\n\nvec4 rightFrag = texture2D(textureSampler, vUV);\nrightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\n\ngl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\n}",
  14726. blackAndWhitePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void)\n{\nfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\ngl_FragColor = vec4(luminance, luminance, luminance, 1.0);\n}",
  14727. blurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nvoid main(void)\n{\nfloat weights[7];\nweights[0] = 0.05;\nweights[1] = 0.1;\nweights[2] = 0.2;\nweights[3] = 0.3;\nweights[4] = 0.2;\nweights[5] = 0.1;\nweights[6] = 0.05;\n\nvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\nvec2 texelStep = texelSize * direction * blurWidth;\nvec2 start = vUV - 3.0 * texelStep;\n\nvec4 baseColor = vec4(0., 0., 0., 0.);\nvec2 texelOffset = vec2(0., 0.);\n\nfor (int i = 0; i < 7; i++)\n{\nbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\ntexelOffset += texelStep;\n}\n\ngl_FragColor = baseColor;\n}",
  14728. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nfloat round(float number){\nreturn sign(number)*floor(abs(number) + 0.5);\n}\n\nvoid main(void)\n{\nfloat brickW = 1.0 / numberOfBricksWidth;\nfloat brickH = 1.0 / numberOfBricksHeight;\nfloat jointWPercentage = 0.01;\nfloat jointHPercentage = 0.05;\nvec3 color = brickColor;\nfloat yi = vUV.y / brickH;\nfloat nyi = round(yi);\nfloat xi = vUV.x / brickW;\n\nif (mod(floor(yi), 2.0) == 0.0){\nxi = xi - 0.5;\n}\n\nfloat nxi = round(xi);\nvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\nif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\ncolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n}\nelse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\ncolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n}\nelse {\nfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\n\nif (brickColorSwitch == 0.0)\ncolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\nelse if (brickColorSwitch == 2.0)\ncolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\n}\n\ngl_FragColor = vec4(color, 1.0);\n}",
  14729. chromaticAberrationPixelShader:"\n#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler; // original color\n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvoid main(void)\n{\nvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\nfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\n+ centered_screen_pos.y*centered_screen_pos.y;\nfloat radius = sqrt(radius2);\n\nvec4 original = texture2D(textureSampler, vUV);\n\nif (chromatic_aberration > 0.0) {\nvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\nfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\nfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\n\nvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\n\noriginal.r = texture2D(textureSampler, ref_coords_r).r;\noriginal.g = texture2D(textureSampler, ref_coords_g).g;\noriginal.b = texture2D(textureSampler, ref_coords_b).b;\n}\n\ngl_FragColor = original;\n}",
  14730. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main() {\n\nvec2 p = vUV * 12.0;\nvec3 c = mix(skyColor, cloudColor, fbm(p));\ngl_FragColor = vec4(c, 1);\n\n}",
  14731. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\ngl_FragColor = color;\n}",
  14732. colorVertexShader:"precision highp float;\n\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\ngl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  14733. colorCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler; // screen render\nuniform sampler2D colorTable; // color table with modified colors\n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT = 16.0; // how many slices in the color cube; 1 slice = 1 pixel\n\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\nfloat sliceSize = 1.0 / width; // space of 1 slice\nfloat slicePixelSize = sliceSize / width; // space of 1 pixel\nfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\nfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\nfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\nfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\nfloat s0 = xOffset + (zSlice0 * sliceSize);\nfloat s1 = xOffset + (zSlice1 * sliceSize);\nvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\nvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\nfloat zOffset = mod(uv.z * width, 1.0);\nvec4 result = mix(slice0Color, slice1Color, zOffset);\nreturn result;\n}\n\nvoid main(void)\n{\nvec4 screen_color = texture2D(textureSampler, vUV);\ngl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\n\n}",
  14734. convolutionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform float kernel[9];\n\nvoid main(void)\n{\nvec2 onePixel = vec2(1.0, 1.0) / screenSize;\nvec4 colorSum =\ntexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\ntexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\ntexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\ntexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\ntexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\ntexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\ntexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\ntexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\ntexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\n\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\n\nif (kernelWeight <= 0.0) {\nkernelWeight = 1.0;\n}\n\ngl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\n}",
  14735. 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\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform vec3 shadowsInfo0;\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 vec3 shadowsInfo1;\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 vec3 shadowsInfo2;\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 vec3 shadowsInfo3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\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#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\nfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\nreturn 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#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{\nif (mode == MAP_SPHERICAL)\n{\nvec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1.0));\n}\nelse if (mode == MAP_PLANAR)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = normalize(reflect(viewDir, worldNormal));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1));\n}\nelse if (mode == MAP_CUBIC)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = reflect(viewDir, worldNormal);\n\nreturn vec3(reflectionMatrix * vec4(coords, 0));\n}\nelse if (mode == MAP_PROJECTION)\n{\nreturn vec3(reflectionMatrix * (view * worldPos));\n}\nelse if (mode == MAP_SKYBOX)\n{\nreturn vPositionUVW;\n}\n\nreturn vec3(0, 0, 0);\n}\n#endif\n\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\nreturn dot(color, bit_shift);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\ndepth = 0.5 * depth + vec3(0.5);\nvec2 uv = depth.xy;\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\n\nif (depth.z > shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\ndepth = 0.5 * depth + vec3(0.5);\nvec2 uv = depth.xy;\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nfloat visibility = 1.;\n\nvec2 poissonDisk[4];\npoissonDisk[0] = vec2(-0.94201624, -0.39906216);\npoissonDisk[1] = vec2(0.94558609, -0.76890725);\npoissonDisk[2] = vec2(-0.094184101, -0.92938870);\npoissonDisk[3] = vec2(0.34495938, 0.29387760);\n\nfloat biasedDepth = depth.z - bias;\n\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\n\nreturn visibility;\n}\n\nfloat linstep(float low, float high, float v) {\nreturn clamp((v - low) / (high - low), 0.0, 1.0);\n}\n\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\n{\nfloat p = smoothstep(compare - bias, compare, moments.x);\nfloat variance = max(moments.y - moments.x * moments.x, 0.02);\nfloat d = compare - moments.x;\nfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\n\nreturn clamp(max(p, p_max), 0.0, 1.0);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\ndepth = 0.5 * depth + vec3(0.5);\nvec2 uv = depth.xy;\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\n{\nreturn 1.0;\n}\n\nvec4 texel = texture2D(shadowSampler, uv);\n\nvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\nreturn 1.0 - ChebychevInequality(moments, depth.z, bias);\n}\n#endif\n\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\nvec3 dp1 = dFdx(p);\nvec3 dp2 = dFdy(p);\nvec2 duv1 = dFdx(uv);\nvec2 duv2 = dFdy(uv);\n\nvec3 dp2perp = cross(dp2, normal);\nvec3 dp1perp = cross(normal, dp1);\nvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\nvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\nfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\nreturn mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\nvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\nmap = map * 255. / 127. - 128. / 127.;\nmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\nreturn normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\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{\nfloat fogCoeff = 1.0;\nfloat fogStart = vFogInfos.y;\nfloat fogEnd = vFogInfos.z;\nfloat fogDensity = vFogInfos.w;\n\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n}\n\nreturn clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\nstruct lightingInfo\n{\nvec3 diffuse;\nvec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\nlightingInfo result;\n\nvec3 lightVectorW;\nfloat attenuation = 1.0;\nif (lightData.w == 0.)\n{\nvec3 direction = lightData.xyz - vPositionW;\n\nattenuation = max(0., 1.0 - length(direction) / range);\nlightVectorW = normalize(direction);\n}\nelse\n{\nlightVectorW = normalize(-lightData.xyz);\n}\n\nfloat ndl = max(0., dot(vNormal, lightVectorW));\n\nvec3 angleW = normalize(viewDirectionW + lightVectorW);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, max(1., vSpecularColor.a));\n\nresult.diffuse = ndl * diffuseColor * attenuation;\nresult.specular = specComp * specularColor * attenuation;\n\nreturn result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\nlightingInfo result;\n\nvec3 direction = lightData.xyz - vPositionW;\nvec3 lightVectorW = normalize(direction);\nfloat attenuation = max(0., 1.0 - length(direction) / range);\n\nfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\nfloat spotAtten = 0.0;\n\nif (cosAngle >= lightDirection.w)\n{\ncosAngle = max(0., pow(cosAngle, lightData.w));\nspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\n\nfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\nvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\nresult.specular = specComp * specularColor * spotAtten * attenuation;\n\nreturn result;\n}\n\nresult.diffuse = vec3(0.);\nresult.specular = vec3(0.);\n\nreturn result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\nlightingInfo result;\n\nfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\nvec3 angleW = normalize(viewDirectionW + lightData.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult.diffuse = mix(groundColor, diffuseColor, ndl);\nresult.specular = specComp * specularColor;\n\nreturn result;\n}\n\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance > 0.0)\ndiscard;\n#endif\n\nvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\nvec4 baseColor = vec4(1., 1., 1., 1.);\nvec3 diffuseColor = vDiffuseColor.rgb;\n\nfloat alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\nbaseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\nbaseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\nif (baseColor.a < 0.4)\ndiscard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\nalpha *= baseColor.a;\n#endif\n\nbaseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n#ifdef NORMAL\nvec3 normalW = normalize(vNormalW);\n#else\nvec3 normalW = vec3(1.0, 1.0, 1.0);\n#endif\n\n\n#ifdef BUMP\nnormalW = perturbNormal(viewDirectionW);\n#endif\n\n\nvec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\nbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase = vec3(0., 0., 0.);\nvec3 specularBase = vec3(0., 0., 0.);\nfloat shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\nlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\nlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\nlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\nshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z);\n#else\n#ifdef SHADOWPCF0\nshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\n#else\nshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\ninfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\nshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z);\n#else\n#ifdef SHADOWPCF1\nshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\n#else\nshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\ninfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\nshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z);\n#else\n#ifdef SHADOWPCF2\nshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\n#else\nshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\ninfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\nshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z);\n#else\n#ifdef SHADOWPCF3\nshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\n#else\nshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\nvec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\nvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\nif (vReflectionInfos.z != 0.0)\n{\nreflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n}\nelse\n{\nvec2 coords = vReflectionUVW.xy;\n\nif (vReflectionInfos.x == MAP_PROJECTION)\n{\ncoords /= vReflectionUVW.z;\n}\n\ncoords.y = 1.0 - coords.y;\n\nreflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n}\n\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\nreflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\nopacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\nalpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\nalpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\nalpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\nalpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\nvec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\nemissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\nvec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\ndiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\nvec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\nalpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\nvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\nfloat fog = CalcFogFactor();\ncolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\ngl_FragColor = color;\n}",
  14736. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\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\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\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\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) {\nmat4 finalWorld;\n\n#ifdef REFLECTION\nvPositionUVW = position;\n#endif\n\n#ifdef INSTANCES\nfinalWorld = mat4(world0, world1, world2, world3);\n#else\nfinalWorld = world;\n#endif\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#else\nfinalWorld = finalWorld * (m0 + m1 + m2);\n#endif\n\n#endif\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\nvec4 worldPos = finalWorld * vec4(position, 1.0);\nvPositionW = vec3(worldPos);\n\n#ifdef NORMAL\nvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\nvec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef SPECULAR\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef CLIPPLANE\nfClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n#ifdef FOG\nfFogDistance = (view * worldPos).z;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nvPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\nvPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\nvPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\nvPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n#ifdef VERTEXCOLOR\nvColor = color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize = pointSize;\n#endif\n}",
  14737. 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\nif (texture2D(diffuseSampler, vUV).a < 0.4)\ndiscard;\n#endif\n\nfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\ngl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\n}",
  14738. depthVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\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#if defined(ALPHATEST) || defined(NEED_UV)\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\nmat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\nmat4 finalWorld = world;\n#endif\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\nvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14739. depthBoxBlurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\n\nvoid main(void)\n{\nvec4 colorDepth = vec4(0.0);\n\nfor (int x = -OFFSET; x <= OFFSET; x++)\nfor (int y = -OFFSET; y <= OFFSET; y++)\ncolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\n\ngl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\n}",
  14740. depthOfFieldPixelShader:"\n#ifdef GL_ES\nprecision highp float;\n#endif\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform float maxZ;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform float focus_depth;\nuniform float aperture;\nuniform float edge_blur;\nuniform bool highlights;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n\nvec2 centered_screen_pos;\nfloat radius2;\nfloat radius;\n\n\nvec2 getDistortedCoords(vec2 coords) {\n\nif (distortion == 0.0) { return coords; }\n\nvec2 direction = 1.0 * normalize(centered_screen_pos);\nvec2 dist_coords = vec2(0.5, 0.5);\ndist_coords.x = 0.5 + direction.x * radius2 * 1.0;\ndist_coords.y = 0.5 + direction.y * radius2 * 1.0;\nfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\n\ndist_coords = mix(coords, dist_coords, dist_amount);\n\nreturn dist_coords;\n}\n\nvec4 getBlurColor(vec2 coords, float size) {\n\nvec4 col = texture2D(textureSampler, coords);\nif (size == 0.0) { return col; }\n\nfloat blur_level = min(3.0, ceil(size / 1.0));\n\nfloat w = (size / screen_width);\nfloat h = (size / screen_height);\nfloat total_weight = 1.0;\n\ncol += texture2D(textureSampler, coords + vec2(-0.53*w, 0.15*h))*0.93;\ncol += texture2D(textureSampler, coords + vec2(0.42*w, -0.69*h))*0.90;\ncol += texture2D(textureSampler, coords + vec2(0.20*w, 1.00*h))*0.87;\ncol += texture2D(textureSampler, coords + vec2(-0.97*w, -0.72*h))*0.85;\ncol += texture2D(textureSampler, coords + vec2(1.37*w, -0.14*h))*0.83;\ncol += texture2D(textureSampler, coords + vec2(-1.02*w, 1.16*h))*0.80;\ncol += texture2D(textureSampler, coords + vec2(-0.03*w, -1.69*h))*0.78;\ncol += texture2D(textureSampler, coords + vec2(1.27*w, 1.34*h))*0.76;\ncol += texture2D(textureSampler, coords + vec2(-1.98*w, -0.14*h))*0.74;\ncol += texture2D(textureSampler, coords + vec2(1.66*w, -1.32*h))*0.72;\ntotal_weight += 8.18;\n\nif (blur_level > 1.0) {\ncol += texture2D(textureSampler, coords + vec2(-0.35*w, 2.22*h))*0.70;\ncol += texture2D(textureSampler, coords + vec2(-1.31*w, -1.98*h))*0.67;\ncol += texture2D(textureSampler, coords + vec2(2.42*w, 0.61*h))*0.65;\ncol += texture2D(textureSampler, coords + vec2(-2.31*w, 1.25*h))*0.63;\ncol += texture2D(textureSampler, coords + vec2(0.90*w, -2.59*h))*0.61;\ncol += texture2D(textureSampler, coords + vec2(1.14*w, 2.62*h))*0.59;\ncol += texture2D(textureSampler, coords + vec2(-2.72*w, -1.21*h))*0.56;\ncol += texture2D(textureSampler, coords + vec2(2.93*w, -0.98*h))*0.54;\ncol += texture2D(textureSampler, coords + vec2(-1.56*w, 2.80*h))*0.52;\ncol += texture2D(textureSampler, coords + vec2(-0.77*w, -3.22*h))*0.49;\ntotal_weight += 5.96;\n}\n\nif (blur_level > 2.0) {\ncol += texture2D(textureSampler, coords + vec2(2.83*w, 1.92*h))*0.46;\ncol += texture2D(textureSampler, coords + vec2(-3.49*w, 0.51*h))*0.44;\ncol += texture2D(textureSampler, coords + vec2(2.30*w, -2.82*h))*0.41;\ncol += texture2D(textureSampler, coords + vec2(0.22*w, 3.74*h))*0.38;\ncol += texture2D(textureSampler, coords + vec2(-2.76*w, -2.68*h))*0.34;\ncol += texture2D(textureSampler, coords + vec2(3.95*w, 0.11*h))*0.31;\ncol += texture2D(textureSampler, coords + vec2(-3.07*w, 2.65*h))*0.26;\ncol += texture2D(textureSampler, coords + vec2(0.48*w, -4.13*h))*0.22;\ncol += texture2D(textureSampler, coords + vec2(2.49*w, 3.46*h))*0.15;\ntotal_weight += 2.97;\n}\n\ncol /= total_weight; // scales color according to weights\ncol.a = 1.0;\n\n\nreturn col;\n}\n\nvec2 rand(vec2 co)\n{\nfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\nfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\nreturn clamp(vec2(noise1, noise2), 0.0, 1.0);\n}\n\nvoid main(void)\n{\n\ncentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\nradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\nradius = sqrt(radius2);\n\nvec4 final_color;\nvec2 distorted_coords = getDistortedCoords(vUV);\nvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height); // varies from 0 to SCREEN_WIDTH or _HEIGHT\n\nfloat dof_blur_amount = 0.0;\nfloat depth_bias = 0.0; // positive if the pixel is further than focus depth; negative if closer\nif (focus_depth != -1.0) {\nvec4 depth_sample = texture2D(depthSampler, distorted_coords);\nfloat depth = depth_sample.r;\ndepth_bias = depth - focus_depth;\n\nif (depth_bias > 0.0) { dof_blur_amount = depth_bias * aperture * 2.2; }\nelse { dof_blur_amount = depth_bias * depth_bias * aperture * 30.0; }\n\nif (dof_blur_amount < 0.05) { dof_blur_amount = 0.0; } // no blur at all\n}\n\nfloat edge_blur_amount = 0.0;\nif (edge_blur > 0.0) {\nedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\n}\n\nfloat blur_amount = max(edge_blur_amount, dof_blur_amount);\n\nif (blur_amount == 0.0) {\ngl_FragColor = texture2D(textureSampler, distorted_coords);\n}\nelse {\n\ngl_FragColor = getBlurColor(distorted_coords, blur_amount * 1.7);\n\nif (depth_bias > 0.0 && highlights) {\ngl_FragColor += clamp(dof_blur_amount, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords);\n}\n\nif (blur_noise) {\nvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\nvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\ngl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\n}\n}\n\nif (grain_amount > 0.0) {\nvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\ngl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.20;\n}\n}",
  14741. displayPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\n\nvoid main(void)\n{\ngl_FragColor = texture2D(passSampler, vUV);\n}",
  14742. filterPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform mat4 kernelMatrix;\n\nvoid main(void)\n{\nvec3 baseColor = texture2D(textureSampler, vUV).rgb;\nvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\n\ngl_FragColor = vec4(updatedColor, 1.0);\n}",
  14743. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main() {\nvec2 p = vUV * 8.0;\nfloat q = fbm(p - time * 0.1);\nvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\nvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\nvec3 color = c * cos(shift * vUV.y);\nfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\n\ngl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\n}",
  14744. 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(){\nvec2 localTexelSize = texelSize;\nvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\nvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\nvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\nvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\nvec4 rgbM = texture2D(textureSampler, vUV);\nvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\nfloat lumaNW = dot(rgbNW, luma);\nfloat lumaNE = dot(rgbNE, luma);\nfloat lumaSW = dot(rgbSW, luma);\nfloat lumaSE = dot(rgbSE, luma);\nfloat lumaM = dot(rgbM, luma);\nfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\nfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\nvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\n\nfloat dirReduce = max(\n(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\n\nfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\ndir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\ndir * rcpDirMin)) * localTexelSize;\n\nvec4 rgbA = 0.5 * (\ntexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\ntexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\n\nvec4 rgbB = rgbA * 0.5 + 0.25 * (\ntexture2D(textureSampler, vUV + dir * -0.5) +\ntexture2D(textureSampler, vUV + dir * 0.5));\nfloat lumaB = dot(rgbB, luma);\nif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\ngl_FragColor = rgbA;\n}\nelse {\ngl_FragColor = rgbB;\n}\n}",
  14745. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main(void) {\nvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\ncolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\ncolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\ncolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\ngl_FragColor = vec4(color, 1.0);\n}",
  14746. layerPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\n\nvoid main(void) {\nvec4 baseColor = texture2D(textureSampler, vUV);\n\ngl_FragColor = baseColor * color;\n}",
  14747. layerVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\n\nvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\ngl_Position = vec4(position, 0.0, 1.0);\n}",
  14748. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\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#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#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\nfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\nreturn 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#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\nconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\nreturn dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\nvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nfloat shadow = unpack(texture2D(shadowSampler, uv));\n\nif (depth.z > shadow)\n{\nreturn 0.;\n}\nreturn 1.;\n}\n\nfloat ChebychevInequality(vec2 moments, float t)\n{\nif (t <= moments.x)\n{\nreturn 1.0;\n}\n\nfloat variance = moments.y - (moments.x * moments.x);\nvariance = max(variance, 0.);\n\nfloat d = t - moments.x;\nreturn variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\nvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nvec4 texel = texture2D(shadowSampler, uv);\n\nvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\nreturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\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{\nfloat fogCoeff = 1.0;\nfloat fogStart = vFogInfos.y;\nfloat fogEnd = vFogInfos.z;\nfloat fogDensity = vFogInfos.w;\n\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n}\n\nreturn clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\nmat3 result;\n\nvec3 lightVectorW;\nif (lightData.w == 0.)\n{\nlightVectorW = normalize(lightData.xyz - vPositionW);\n}\nelse\n{\nlightVectorW = normalize(-lightData.xyz);\n}\n\nfloat ndl = max(0., dot(vNormal, lightVectorW));\n\nvec3 angleW = normalize(viewDirectionW + lightVectorW);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\nresult[0] = ndl * diffuseColor.rgb;\nresult[1] = specComp * specularColor;\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\nmat3 result;\n\nvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\nfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\nfloat spotAtten = 0.0;\n\nif (cosAngle >= lightDirection.w)\n{\ncosAngle = max(0., pow(cosAngle, lightData.w));\nspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\nfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\nvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult[0] = ndl * spotAtten * diffuseColor.rgb;\nresult[1] = specComp * specularColor * spotAtten;\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nresult[0] = vec3(0.);\nresult[1] = vec3(0.);\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\nmat3 result;\n\nfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\nvec3 angleW = normalize(viewDirectionW + lightData.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\nresult[1] = specComp * specularColor;\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance > 0.0)\ndiscard;\n#endif\n\nvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\nvec4 baseColor = vec4(1., 1., 1., 1.);\nvec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\nbaseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\nbaseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\nif (baseColor.a < 0.4)\ndiscard;\n#endif\n\nbaseColor.rgb *= vDiffuseInfos.y;\n#endif\n\nvec3 normalW = normalize(vNormalW);\n\nvec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\nbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase = vec3(0., 0., 0.);\nvec3 specularBase = vec3(0., 0., 0.);\nfloat shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\nmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\nmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\nmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\nshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\nshadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\ninfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\nshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\nshadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\ninfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\nshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\nshadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\ninfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\nshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\nshadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\nvec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\nif (vReflectionInfos.z != 0.0)\n{\nreflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n}\nelse\n{\nvec2 coords = vReflectionUVW.xy;\n\nif (vReflectionInfos.x == MAP_PROJECTION)\n{\ncoords /= vReflectionUVW.z;\n}\n\ncoords.y = 1.0 - coords.y;\n\nreflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n}\n\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\nreflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\nvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\nalpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\nalpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef VERTEXALPHA\nalpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\nalpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\nvec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\nemissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\nvec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\ndiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\nvec3 finalSpecular = specularBase * specularColor;\n\nvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\nfloat fog = CalcFogFactor();\ncolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\ngl_FragColor = color;\n}",
  14749. 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\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\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\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{\nif (mode == MAP_SPHERICAL)\n{\nvec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1.0));\n}\nelse if (mode == MAP_PLANAR)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = normalize(reflect(viewDir, worldNormal));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1));\n}\nelse if (mode == MAP_CUBIC)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = reflect(viewDir, worldNormal);\n\nreturn vec3(reflectionMatrix * vec4(coords, 0));\n}\nelse if (mode == MAP_PROJECTION)\n{\nreturn vec3(reflectionMatrix * (view * worldPos));\n}\nelse if (mode == MAP_SKYBOX)\n{\nreturn position;\n}\n\nreturn vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\nmat4 finalWorld;\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = world * (m0 + m1 + m2 + m3);\n#else\nfinalWorld = world * (m0 + m1 + m2);\n#endif\n\n#else\nfinalWorld = world;\n#endif\n\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\nvec4 worldPos = finalWorld * vec4(position, 1.0);\nvPositionW = vec3(worldPos);\nvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n#ifndef UV1\nvec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\nvec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef REFLECTION\nvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef SPECULAR\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef CLIPPLANE\nfClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n#ifdef FOG\nfFogDistance = (view * worldPos).z;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nvPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\nvPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\nvPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\nvPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n#ifdef VERTEXCOLOR\nvColor = color;\n#endif\n}",
  14750. lensFlarePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\n\nvoid main(void) {\nvec4 baseColor = texture2D(textureSampler, vUV);\n\ngl_FragColor = baseColor * color;\n}",
  14751. lensFlareVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\n\nvUV = position * madd + madd;\ngl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\n}",
  14752. lensHighlightsPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler; // original color\n\nuniform float gain;\nuniform float threshold;\nuniform bool pentagon;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight = color;\nfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\nfloat lum_threshold;\nif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\nelse { lum_threshold = 0.5 + 0.44 * threshold; }\n\nluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\n\nhighlight *= luminance * gain;\nhighlight.a = 1.0;\n\nreturn highlight;\n}\n\nvoid main(void)\n{\nvec4 original = texture2D(textureSampler, vUV);\n\nif (gain == -1.0) {\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\nreturn;\n}\n\nfloat w = 2.0 / screen_width;\nfloat h = 2.0 / screen_height;\n\nfloat weight = 1.0;\n\nvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\n\nif (pentagon) {\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\n}\nelse {\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\n}\n\nblurred /= 39.0;\n\ngl_FragColor = blurred;\n\n}",
  14753. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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{\nfloat val = 0.0;\nfloat freq = 1.0;\nfor (int i = 0; i < 4; i++)\n{\nval += abs(noise(P*freq) / freq);\nfreq *= 2.07;\n}\nreturn val;\n}\n\nfloat round(float number){\nreturn sign(number)*floor(abs(number) + 0.5);\n}\n\nvec3 marble_color(float x)\n{\nvec3 col;\nx = 0.5*(x + 1.);\nx = sqrt(x);\nx = sqrt(x);\nx = sqrt(x);\ncol = vec3(.2 + .75*x);\ncol.b *= 0.95;\nreturn col;\n}\n\nvoid main()\n{\nfloat brickW = 1.0 / numberOfTilesWidth;\nfloat brickH = 1.0 / numberOfTilesHeight;\nfloat jointWPercentage = 0.01;\nfloat jointHPercentage = 0.01;\nvec3 color = brickColor;\nfloat yi = vUV.y / brickH;\nfloat nyi = round(yi);\nfloat xi = vUV.x / brickW;\n\nif (mod(floor(yi), 2.0) == 0.0){\nxi = xi - 0.5;\n}\n\nfloat nxi = round(xi);\nvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\nif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\ncolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n}\nelse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\ncolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n}\nelse {\nfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\nt += amplitude * turbulence(brickvUV.xy);\nt = sin(t);\ncolor = marble_color(t);\n}\n\ngl_FragColor = vec4(color, 0.0);\n}",
  14754. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\nvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\nfloat rSq = theta.x * theta.x + theta.y * theta.y;\nvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\nreturn LensCenter + Scale * rvector;\n}\n\nvoid main(void)\n{\nvec2 tc = HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\nelse{\ngl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n}\n}",
  14755. 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\nif (texture2D(diffuseSampler, vUV).a < 0.4)\ndiscard;\n#endif\n\ngl_FragColor = color;\n}",
  14756. outlineVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\nattribute vec3 normal;\n\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\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\nmat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\nmat4 finalWorld = world;\n#endif\n\nvec3 offsetPosition = position + normal * offset;\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\ngl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#else\ngl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\nvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\nvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14757. particlesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\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\nif (fClipDistance > 0.0)\ndiscard;\n#endif\nvec4 baseColor = texture2D(diffuseSampler, vUV);\n\ngl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\n}",
  14758. particlesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\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) {\nvec3 viewPos = (view * vec4(position, 1.0)).xyz;\nvec3 cornerPos;\nfloat size = options.y;\nfloat angle = options.x;\nvec2 offset = options.zw;\n\ncornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\nvec3 rotatedCorner;\nrotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\nrotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\nrotatedCorner.z = 0.;\n\nviewPos += rotatedCorner;\ngl_Position = projection * vec4(viewPos, 1.0);\n\nvColor = color;\nvUV = offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos = invView * vec4(viewPos, 1.0);\nfClipDistance = dot(worldPos, vClipPlane);\n#endif\n}",
  14759. passPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void)\n{\ngl_FragColor = texture2D(textureSampler, vUV);\n}",
  14760. postprocessVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\n\nvUV = position * madd + madd;\ngl_Position = vec4(position, 0.0, 1.0);\n}",
  14761. proceduralVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\nvPosition = position;\nvUV = position * madd + madd;\ngl_Position = vec4(position, 0.0, 1.0);\n}",
  14762. refractionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\n\nvoid main() {\nfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\n\nvec2 uv = vUV - vec2(0.5);\nvec2 offset = uv * depth * ref;\nvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\n\ngl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\n}",
  14763. roadPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform vec3 roadColor;\n\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main(void) {\nfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\nvec3 color = roadColor * ratioy;\ngl_FragColor = vec4(color, 1.0);\n}",
  14764. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\nconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\nconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n\nvec4 res = fract(depth * bit_shift);\nres -= res.xxyz * bit_mask;\n\nreturn res;\n}\n\nvec2 packHalf(float depth)\n{\nconst vec2 bitOffset = vec2(1.0 / 255., 0.);\nvec2 color = vec2(depth, fract(depth * 255.));\n\nreturn color - (color.yy * bitOffset);\n}\n\nvarying vec4 vPosition;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler, vUV).a < 0.4)\ndiscard;\n#endif\nfloat depth = vPosition.z / vPosition.w;\ndepth = depth * 0.5 + 0.5;\n\n#ifdef VSM\nfloat moment1 = depth;\nfloat moment2 = moment1 * moment1;\n\ngl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\ngl_FragColor = pack(depth);\n#endif\n}",
  14765. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\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\nvarying vec4 vPosition;\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\nmat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\nmat4 finalWorld = world;\n#endif\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#endif\n\nvPosition = viewProjection * finalWorld * vec4(position, 1.0);\ngl_Position = vPosition;\n\n#ifdef ALPHATEST\n#ifdef UV1\nvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\nvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14766. spritesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform bool alphaTest;\n\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\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{\nfloat fogCoeff = 1.0;\nfloat fogStart = vFogInfos.y;\nfloat fogEnd = vFogInfos.z;\nfloat fogDensity = vFogInfos.w;\n\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n}\n\nreturn min(1., max(0., fogCoeff));\n}\n#endif\n\n\nvoid main(void) {\nvec4 baseColor = texture2D(diffuseSampler, vUV);\n\nif (alphaTest)\n{\nif (baseColor.a < 0.95)\ndiscard;\n}\n\nbaseColor *= vColor;\n\n#ifdef FOG\nfloat fog = CalcFogFactor();\nbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\n#endif\n\ngl_FragColor = baseColor;\n}",
  14767. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) {\nvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz;\nvec2 cornerPos;\n\nfloat angle = position.w;\nvec2 size = vec2(options.x, options.y);\nvec2 offset = options.zw;\nvec2 uvScale = textureInfos.xy;\n\ncornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\n\nvec3 rotatedCorner;\nrotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\nrotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\nrotatedCorner.z = 0.;\n\nviewPos += rotatedCorner;\ngl_Position = projection * vec4(viewPos, 1.0);\n\nvColor = color;\n\nvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\nvUV = (uvOffset + cellInfo.zw) * uvScale;\n\n#ifdef FOG\nfFogDistance = viewPos.z;\n#endif\n}",
  14768. ssaoPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define SAMPLES 16\n\nuniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\n\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[16];\n\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\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) {\nfloat depth1 = texture2D(textureSampler, coords + offset1).r;\nfloat depth2 = texture2D(textureSampler, coords + offset2).r;\n\nvec3 p1 = vec3(offset1, depth1 - depth);\nvec3 p2 = vec3(offset2, depth2 - depth);\n\nvec3 normal = cross(p1, p2);\nnormal.z = -normal.z;\n\nreturn normalize(normal);\n}\n\nvoid main(void)\n{\nconst float base = 0.2;\n\nvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\nfloat depth = texture2D(textureSampler, vUV).r;\nvec3 position = vec3(vUV, depth);\nvec3 normal = normalFromDepth(depth, vUV);\nfloat radiusDepth = radius / depth;\nfloat occlusion = 0.0;\n\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\n\nfor (int i = 0; i < SAMPLES; i++)\n{\nray = radiusDepth * reflect(sampleSphere[i], random);\nhemiRay = position + sign(dot(ray, normal)) * ray;\n\nocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\ndifference = depth - occlusionDepth;\n\nocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\n}\n\nfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\n\nfloat result = clamp(ao + base, 0.0, 1.0);\ngl_FragColor.r = result;\ngl_FragColor.g = result;\ngl_FragColor.b = result;\ngl_FragColor.a = 1.0;\n}",
  14769. ssaoCombinePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D originalColor;\n\nvarying vec2 vUV;\n\nvoid main(void) {\ngl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\n}",
  14770. volumetricLightScatteringPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\n\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\n\nvarying vec2 vUV;\n\nvoid main(void) {\nvec2 tc = vUV;\nvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\ndeltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\n\nfloat illuminationDecay = 1.0;\n\nvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\n\nfor(int i=0; i < NUM_SAMPLES; i++) {\ntc -= deltaTexCoord;\nvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\nsample *= illuminationDecay * weight;\ncolor += sample;\nilluminationDecay *= decay;\n}\n\nvec4 realColor = texture2D(textureSampler, vUV);\ngl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\n}",
  14771. volumetricLightScatteringPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\nvarying vec2 vUV;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\nuniform float opacityLevel;\n#endif\n\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nvec4 diffuseColor = texture2D(diffuseSampler, vUV);\n#endif\n\n#ifdef ALPHATEST\nif (diffuseColor.a < 0.4)\ndiscard;\n#endif\n\n#ifdef OPACITY\nvec4 opacityColor = texture2D(opacitySampler, vUV);\nfloat alpha = 1.0;\n\n#ifdef OPACITYRGB\nopacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\nalpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\n#else\nalpha *= opacityColor.a * opacityLevel;\n#endif\n\n#if defined(BASIC_RENDER)\ngl_FragColor = vec4(diffuseColor.rgb, alpha);\n#else\ngl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\n#endif\n\ngl_FragColor.a = alpha;\n#else\n#ifndef BASIC_RENDER\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n#else\ngl_FragColor = diffuseColor;\n#endif\n#endif\n\n}",
  14772. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main(void) {\nfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\nvec3 wood = woodColor * ratioy;\ngl_FragColor = vec4(wood, 1.0);\n}",
  14773. };
  14774. return Effect;
  14775. })();
  14776. BABYLON.Effect = Effect;
  14777. })(BABYLON || (BABYLON = {}));
  14778. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  14779. (function (BABYLON) {
  14780. var Material = (function () {
  14781. function Material(name, scene, doNotAdd) {
  14782. this.name = name;
  14783. this.checkReadyOnEveryCall = true;
  14784. this.checkReadyOnlyOnce = false;
  14785. this.state = "";
  14786. this.alpha = 1.0;
  14787. this.backFaceCulling = true;
  14788. this._wasPreviouslyReady = false;
  14789. this._fillMode = Material.TriangleFillMode;
  14790. this.pointSize = 1.0;
  14791. this.zOffset = 0;
  14792. this.id = name;
  14793. this._scene = scene;
  14794. if (!doNotAdd) {
  14795. scene.materials.push(this);
  14796. }
  14797. }
  14798. Object.defineProperty(Material, "TriangleFillMode", {
  14799. get: function () {
  14800. return Material._TriangleFillMode;
  14801. },
  14802. enumerable: true,
  14803. configurable: true
  14804. });
  14805. Object.defineProperty(Material, "WireFrameFillMode", {
  14806. get: function () {
  14807. return Material._WireFrameFillMode;
  14808. },
  14809. enumerable: true,
  14810. configurable: true
  14811. });
  14812. Object.defineProperty(Material, "PointFillMode", {
  14813. get: function () {
  14814. return Material._PointFillMode;
  14815. },
  14816. enumerable: true,
  14817. configurable: true
  14818. });
  14819. Object.defineProperty(Material.prototype, "wireframe", {
  14820. get: function () {
  14821. return this._fillMode === Material.WireFrameFillMode;
  14822. },
  14823. set: function (value) {
  14824. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  14825. },
  14826. enumerable: true,
  14827. configurable: true
  14828. });
  14829. Object.defineProperty(Material.prototype, "pointsCloud", {
  14830. get: function () {
  14831. return this._fillMode === Material.PointFillMode;
  14832. },
  14833. set: function (value) {
  14834. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  14835. },
  14836. enumerable: true,
  14837. configurable: true
  14838. });
  14839. Object.defineProperty(Material.prototype, "fillMode", {
  14840. get: function () {
  14841. return this._fillMode;
  14842. },
  14843. set: function (value) {
  14844. this._fillMode = value;
  14845. },
  14846. enumerable: true,
  14847. configurable: true
  14848. });
  14849. Material.prototype.isReady = function (mesh, useInstances) {
  14850. return true;
  14851. };
  14852. Material.prototype.getEffect = function () {
  14853. return this._effect;
  14854. };
  14855. Material.prototype.getScene = function () {
  14856. return this._scene;
  14857. };
  14858. Material.prototype.needAlphaBlending = function () {
  14859. return (this.alpha < 1.0);
  14860. };
  14861. Material.prototype.needAlphaTesting = function () {
  14862. return false;
  14863. };
  14864. Material.prototype.getAlphaTestTexture = function () {
  14865. return null;
  14866. };
  14867. Material.prototype.trackCreation = function (onCompiled, onError) {
  14868. };
  14869. Material.prototype._preBind = function () {
  14870. var engine = this._scene.getEngine();
  14871. engine.enableEffect(this._effect);
  14872. engine.setState(this.backFaceCulling, this.zOffset);
  14873. };
  14874. Material.prototype.bind = function (world, mesh) {
  14875. this._scene._cachedMaterial = this;
  14876. if (this.onBind) {
  14877. this.onBind(this, mesh);
  14878. }
  14879. };
  14880. Material.prototype.bindOnlyWorldMatrix = function (world) {
  14881. };
  14882. Material.prototype.unbind = function () {
  14883. };
  14884. Material.prototype.dispose = function (forceDisposeEffect) {
  14885. // Remove from scene
  14886. var index = this._scene.materials.indexOf(this);
  14887. this._scene.materials.splice(index, 1);
  14888. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  14889. if (forceDisposeEffect && this._effect) {
  14890. this._scene.getEngine()._releaseEffect(this._effect);
  14891. this._effect = null;
  14892. }
  14893. // Callback
  14894. if (this.onDispose) {
  14895. this.onDispose();
  14896. }
  14897. };
  14898. Material._TriangleFillMode = 0;
  14899. Material._WireFrameFillMode = 1;
  14900. Material._PointFillMode = 2;
  14901. return Material;
  14902. })();
  14903. BABYLON.Material = Material;
  14904. })(BABYLON || (BABYLON = {}));
  14905. //# sourceMappingURL=babylon.material.js.map
  14906. var BABYLON;
  14907. (function (BABYLON) {
  14908. var maxSimultaneousLights = 4;
  14909. var FresnelParameters = (function () {
  14910. function FresnelParameters() {
  14911. this.isEnabled = true;
  14912. this.leftColor = BABYLON.Color3.White();
  14913. this.rightColor = BABYLON.Color3.Black();
  14914. this.bias = 0;
  14915. this.power = 1;
  14916. }
  14917. return FresnelParameters;
  14918. })();
  14919. BABYLON.FresnelParameters = FresnelParameters;
  14920. var StandardMaterial = (function (_super) {
  14921. __extends(StandardMaterial, _super);
  14922. function StandardMaterial(name, scene) {
  14923. var _this = this;
  14924. _super.call(this, name, scene);
  14925. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14926. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14927. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14928. this.specularPower = 64;
  14929. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14930. this.useAlphaFromDiffuseTexture = false;
  14931. this.useSpecularOverAlpha = true;
  14932. this.fogEnabled = true;
  14933. this._cachedDefines = null;
  14934. this._renderTargets = new BABYLON.SmartArray(16);
  14935. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14936. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14937. this._scaledDiffuse = new BABYLON.Color3();
  14938. this._scaledSpecular = new BABYLON.Color3();
  14939. this.getRenderTargetTextures = function () {
  14940. _this._renderTargets.reset();
  14941. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14942. _this._renderTargets.push(_this.reflectionTexture);
  14943. }
  14944. return _this._renderTargets;
  14945. };
  14946. }
  14947. StandardMaterial.prototype.needAlphaBlending = function () {
  14948. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14949. };
  14950. StandardMaterial.prototype.needAlphaTesting = function () {
  14951. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  14952. };
  14953. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14954. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14955. };
  14956. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14957. return this.diffuseTexture;
  14958. };
  14959. // Methods
  14960. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14961. if (this.checkReadyOnlyOnce) {
  14962. if (this._wasPreviouslyReady) {
  14963. }
  14964. }
  14965. var scene = this.getScene();
  14966. if (!this.checkReadyOnEveryCall) {
  14967. if (this._renderId === scene.getRenderId()) {
  14968. }
  14969. }
  14970. var engine = scene.getEngine();
  14971. var defines = [];
  14972. var fallbacks = new BABYLON.EffectFallbacks();
  14973. var needNormals = false;
  14974. var needUVs = false;
  14975. // Textures
  14976. if (scene.texturesEnabled) {
  14977. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14978. if (!this.diffuseTexture.isReady()) {
  14979. return false;
  14980. }
  14981. else {
  14982. needUVs = true;
  14983. defines.push("#define DIFFUSE");
  14984. }
  14985. }
  14986. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14987. if (!this.ambientTexture.isReady()) {
  14988. return false;
  14989. }
  14990. else {
  14991. needUVs = true;
  14992. defines.push("#define AMBIENT");
  14993. }
  14994. }
  14995. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14996. if (!this.opacityTexture.isReady()) {
  14997. return false;
  14998. }
  14999. else {
  15000. needUVs = true;
  15001. defines.push("#define OPACITY");
  15002. if (this.opacityTexture.getAlphaFromRGB) {
  15003. defines.push("#define OPACITYRGB");
  15004. }
  15005. }
  15006. }
  15007. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  15008. if (!this.reflectionTexture.isReady()) {
  15009. return false;
  15010. }
  15011. else {
  15012. needNormals = true;
  15013. needUVs = true;
  15014. defines.push("#define REFLECTION");
  15015. fallbacks.addFallback(0, "REFLECTION");
  15016. }
  15017. }
  15018. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  15019. if (!this.emissiveTexture.isReady()) {
  15020. return false;
  15021. }
  15022. else {
  15023. needUVs = true;
  15024. defines.push("#define EMISSIVE");
  15025. }
  15026. }
  15027. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  15028. if (!this.specularTexture.isReady()) {
  15029. return false;
  15030. }
  15031. else {
  15032. needUVs = true;
  15033. defines.push("#define SPECULAR");
  15034. fallbacks.addFallback(0, "SPECULAR");
  15035. }
  15036. }
  15037. }
  15038. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  15039. if (!this.bumpTexture.isReady()) {
  15040. return false;
  15041. }
  15042. else {
  15043. needUVs = true;
  15044. defines.push("#define BUMP");
  15045. fallbacks.addFallback(0, "BUMP");
  15046. }
  15047. }
  15048. // Effect
  15049. if (this.useSpecularOverAlpha) {
  15050. defines.push("#define SPECULAROVERALPHA");
  15051. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  15052. }
  15053. if (scene.clipPlane) {
  15054. defines.push("#define CLIPPLANE");
  15055. }
  15056. if (engine.getAlphaTesting()) {
  15057. defines.push("#define ALPHATEST");
  15058. }
  15059. if (this._shouldUseAlphaFromDiffuseTexture()) {
  15060. defines.push("#define ALPHAFROMDIFFUSE");
  15061. }
  15062. // Point size
  15063. if (this.pointsCloud || scene.forcePointsCloud) {
  15064. defines.push("#define POINTSIZE");
  15065. }
  15066. // Fog
  15067. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15068. defines.push("#define FOG");
  15069. fallbacks.addFallback(1, "FOG");
  15070. }
  15071. var shadowsActivated = false;
  15072. var lightIndex = 0;
  15073. if (scene.lightsEnabled) {
  15074. for (var index = 0; index < scene.lights.length; index++) {
  15075. var light = scene.lights[index];
  15076. if (!light.isEnabled()) {
  15077. continue;
  15078. }
  15079. // Excluded check
  15080. if (light._excludedMeshesIds.length > 0) {
  15081. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  15082. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  15083. if (excludedMesh) {
  15084. light.excludedMeshes.push(excludedMesh);
  15085. }
  15086. }
  15087. light._excludedMeshesIds = [];
  15088. }
  15089. // Included check
  15090. if (light._includedOnlyMeshesIds.length > 0) {
  15091. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  15092. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  15093. if (includedOnlyMesh) {
  15094. light.includedOnlyMeshes.push(includedOnlyMesh);
  15095. }
  15096. }
  15097. light._includedOnlyMeshesIds = [];
  15098. }
  15099. if (!light.canAffectMesh(mesh)) {
  15100. continue;
  15101. }
  15102. needNormals = true;
  15103. defines.push("#define LIGHT" + lightIndex);
  15104. if (lightIndex > 0) {
  15105. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  15106. }
  15107. var type;
  15108. if (light instanceof BABYLON.SpotLight) {
  15109. type = "#define SPOTLIGHT" + lightIndex;
  15110. }
  15111. else if (light instanceof BABYLON.HemisphericLight) {
  15112. type = "#define HEMILIGHT" + lightIndex;
  15113. }
  15114. else {
  15115. type = "#define POINTDIRLIGHT" + lightIndex;
  15116. }
  15117. defines.push(type);
  15118. if (lightIndex > 0) {
  15119. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  15120. }
  15121. // Shadows
  15122. if (scene.shadowsEnabled) {
  15123. var shadowGenerator = light.getShadowGenerator();
  15124. if (mesh && mesh.receiveShadows && shadowGenerator) {
  15125. defines.push("#define SHADOW" + lightIndex);
  15126. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  15127. if (!shadowsActivated) {
  15128. defines.push("#define SHADOWS");
  15129. shadowsActivated = true;
  15130. }
  15131. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  15132. defines.push("#define SHADOWVSM" + lightIndex);
  15133. if (lightIndex > 0) {
  15134. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  15135. }
  15136. }
  15137. if (shadowGenerator.usePoissonSampling) {
  15138. defines.push("#define SHADOWPCF" + lightIndex);
  15139. if (lightIndex > 0) {
  15140. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  15141. }
  15142. }
  15143. }
  15144. }
  15145. lightIndex++;
  15146. if (lightIndex === maxSimultaneousLights)
  15147. break;
  15148. }
  15149. }
  15150. if (StandardMaterial.FresnelEnabled) {
  15151. // Fresnel
  15152. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15153. var fresnelRank = 1;
  15154. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  15155. defines.push("#define DIFFUSEFRESNEL");
  15156. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  15157. fresnelRank++;
  15158. }
  15159. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  15160. defines.push("#define OPACITYFRESNEL");
  15161. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  15162. fresnelRank++;
  15163. }
  15164. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15165. defines.push("#define REFLECTIONFRESNEL");
  15166. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  15167. fresnelRank++;
  15168. }
  15169. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  15170. defines.push("#define EMISSIVEFRESNEL");
  15171. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  15172. fresnelRank++;
  15173. }
  15174. needNormals = true;
  15175. defines.push("#define FRESNEL");
  15176. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  15177. }
  15178. }
  15179. // Attribs
  15180. var attribs = [BABYLON.VertexBuffer.PositionKind];
  15181. if (mesh) {
  15182. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15183. attribs.push(BABYLON.VertexBuffer.NormalKind);
  15184. defines.push("#define NORMAL");
  15185. }
  15186. if (needUVs) {
  15187. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15188. attribs.push(BABYLON.VertexBuffer.UVKind);
  15189. defines.push("#define UV1");
  15190. }
  15191. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15192. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  15193. defines.push("#define UV2");
  15194. }
  15195. }
  15196. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  15197. attribs.push(BABYLON.VertexBuffer.ColorKind);
  15198. defines.push("#define VERTEXCOLOR");
  15199. if (mesh.hasVertexAlpha) {
  15200. defines.push("#define VERTEXALPHA");
  15201. }
  15202. }
  15203. if (mesh.useBones) {
  15204. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15205. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15206. defines.push("#define BONES");
  15207. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  15208. defines.push("#define BONES4");
  15209. fallbacks.addFallback(0, "BONES4");
  15210. }
  15211. // Instances
  15212. if (useInstances) {
  15213. defines.push("#define INSTANCES");
  15214. attribs.push("world0");
  15215. attribs.push("world1");
  15216. attribs.push("world2");
  15217. attribs.push("world3");
  15218. }
  15219. }
  15220. // Get correct effect
  15221. var join = defines.join("\n");
  15222. if (this._cachedDefines !== join) {
  15223. this._cachedDefines = join;
  15224. scene.resetCachedMaterial();
  15225. // Legacy browser patch
  15226. var shaderName = "default";
  15227. if (!scene.getEngine().getCaps().standardDerivatives) {
  15228. shaderName = "legacydefault";
  15229. }
  15230. 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", "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "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);
  15231. }
  15232. if (!this._effect.isReady()) {
  15233. return false;
  15234. }
  15235. this._renderId = scene.getRenderId();
  15236. this._wasPreviouslyReady = true;
  15237. return true;
  15238. };
  15239. StandardMaterial.prototype.unbind = function () {
  15240. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  15241. this._effect.setTexture("reflection2DSampler", null);
  15242. }
  15243. };
  15244. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  15245. this._effect.setMatrix("world", world);
  15246. };
  15247. StandardMaterial.prototype.bind = function (world, mesh) {
  15248. var scene = this.getScene();
  15249. // Matrices
  15250. this.bindOnlyWorldMatrix(world);
  15251. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  15252. // Bones
  15253. if (mesh && mesh.useBones) {
  15254. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  15255. }
  15256. if (scene.getCachedMaterial() !== this) {
  15257. if (StandardMaterial.FresnelEnabled) {
  15258. // Fresnel
  15259. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  15260. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  15261. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  15262. }
  15263. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  15264. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  15265. }
  15266. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15267. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  15268. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  15269. }
  15270. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  15271. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  15272. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  15273. }
  15274. }
  15275. // Textures
  15276. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  15277. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  15278. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  15279. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  15280. }
  15281. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  15282. this._effect.setTexture("ambientSampler", this.ambientTexture);
  15283. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  15284. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  15285. }
  15286. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  15287. this._effect.setTexture("opacitySampler", this.opacityTexture);
  15288. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  15289. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  15290. }
  15291. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  15292. if (this.reflectionTexture.isCube) {
  15293. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  15294. }
  15295. else {
  15296. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  15297. }
  15298. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  15299. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  15300. }
  15301. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  15302. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  15303. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  15304. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  15305. }
  15306. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  15307. this._effect.setTexture("specularSampler", this.specularTexture);
  15308. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  15309. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  15310. }
  15311. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  15312. this._effect.setTexture("bumpSampler", this.bumpTexture);
  15313. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  15314. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  15315. }
  15316. // Clip plane
  15317. if (scene.clipPlane) {
  15318. var clipPlane = scene.clipPlane;
  15319. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15320. }
  15321. // Point size
  15322. if (this.pointsCloud) {
  15323. this._effect.setFloat("pointSize", this.pointSize);
  15324. }
  15325. // Colors
  15326. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  15327. // Scaling down color according to emissive
  15328. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15329. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15330. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15331. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  15332. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  15333. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  15334. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  15335. }
  15336. // Scaling down color according to emissive
  15337. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15338. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15339. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15340. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  15341. if (scene.lightsEnabled) {
  15342. var lightIndex = 0;
  15343. for (var index = 0; index < scene.lights.length; index++) {
  15344. var light = scene.lights[index];
  15345. if (!light.isEnabled()) {
  15346. continue;
  15347. }
  15348. if (!light.canAffectMesh(mesh)) {
  15349. continue;
  15350. }
  15351. if (light instanceof BABYLON.PointLight) {
  15352. // Point Light
  15353. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15354. }
  15355. else if (light instanceof BABYLON.DirectionalLight) {
  15356. // Directional Light
  15357. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15358. }
  15359. else if (light instanceof BABYLON.SpotLight) {
  15360. // Spot Light
  15361. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  15362. }
  15363. else if (light instanceof BABYLON.HemisphericLight) {
  15364. // Hemispheric Light
  15365. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  15366. }
  15367. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  15368. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  15369. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  15370. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  15371. // Shadows
  15372. if (scene.shadowsEnabled) {
  15373. var shadowGenerator = light.getShadowGenerator();
  15374. if (mesh.receiveShadows && shadowGenerator) {
  15375. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  15376. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  15377. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  15378. }
  15379. }
  15380. lightIndex++;
  15381. if (lightIndex === maxSimultaneousLights)
  15382. break;
  15383. }
  15384. }
  15385. // View
  15386. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  15387. this._effect.setMatrix("view", scene.getViewMatrix());
  15388. }
  15389. // Fog
  15390. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  15391. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  15392. this._effect.setColor3("vFogColor", scene.fogColor);
  15393. }
  15394. _super.prototype.bind.call(this, world, mesh);
  15395. };
  15396. StandardMaterial.prototype.getAnimatables = function () {
  15397. var results = [];
  15398. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  15399. results.push(this.diffuseTexture);
  15400. }
  15401. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  15402. results.push(this.ambientTexture);
  15403. }
  15404. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  15405. results.push(this.opacityTexture);
  15406. }
  15407. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  15408. results.push(this.reflectionTexture);
  15409. }
  15410. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  15411. results.push(this.emissiveTexture);
  15412. }
  15413. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  15414. results.push(this.specularTexture);
  15415. }
  15416. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  15417. results.push(this.bumpTexture);
  15418. }
  15419. return results;
  15420. };
  15421. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  15422. if (this.diffuseTexture) {
  15423. this.diffuseTexture.dispose();
  15424. }
  15425. if (this.ambientTexture) {
  15426. this.ambientTexture.dispose();
  15427. }
  15428. if (this.opacityTexture) {
  15429. this.opacityTexture.dispose();
  15430. }
  15431. if (this.reflectionTexture) {
  15432. this.reflectionTexture.dispose();
  15433. }
  15434. if (this.emissiveTexture) {
  15435. this.emissiveTexture.dispose();
  15436. }
  15437. if (this.specularTexture) {
  15438. this.specularTexture.dispose();
  15439. }
  15440. if (this.bumpTexture) {
  15441. this.bumpTexture.dispose();
  15442. }
  15443. _super.prototype.dispose.call(this, forceDisposeEffect);
  15444. };
  15445. StandardMaterial.prototype.clone = function (name) {
  15446. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  15447. // Base material
  15448. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  15449. newStandardMaterial.alpha = this.alpha;
  15450. newStandardMaterial.fillMode = this.fillMode;
  15451. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  15452. // Standard material
  15453. if (this.diffuseTexture && this.diffuseTexture.clone) {
  15454. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  15455. }
  15456. if (this.ambientTexture && this.ambientTexture.clone) {
  15457. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  15458. }
  15459. if (this.opacityTexture && this.opacityTexture.clone) {
  15460. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  15461. }
  15462. if (this.reflectionTexture && this.reflectionTexture.clone) {
  15463. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  15464. }
  15465. if (this.emissiveTexture && this.emissiveTexture.clone) {
  15466. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  15467. }
  15468. if (this.specularTexture && this.specularTexture.clone) {
  15469. newStandardMaterial.specularTexture = this.specularTexture.clone();
  15470. }
  15471. if (this.bumpTexture && this.bumpTexture.clone) {
  15472. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  15473. }
  15474. newStandardMaterial.ambientColor = this.ambientColor.clone();
  15475. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  15476. newStandardMaterial.specularColor = this.specularColor.clone();
  15477. newStandardMaterial.specularPower = this.specularPower;
  15478. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  15479. return newStandardMaterial;
  15480. };
  15481. // Statics
  15482. // Flags used to enable or disable a type of texture for all Standard Materials
  15483. StandardMaterial.DiffuseTextureEnabled = true;
  15484. StandardMaterial.AmbientTextureEnabled = true;
  15485. StandardMaterial.OpacityTextureEnabled = true;
  15486. StandardMaterial.ReflectionTextureEnabled = true;
  15487. StandardMaterial.EmissiveTextureEnabled = true;
  15488. StandardMaterial.SpecularTextureEnabled = true;
  15489. StandardMaterial.BumpTextureEnabled = true;
  15490. StandardMaterial.FresnelEnabled = true;
  15491. return StandardMaterial;
  15492. })(BABYLON.Material);
  15493. BABYLON.StandardMaterial = StandardMaterial;
  15494. })(BABYLON || (BABYLON = {}));
  15495. //# sourceMappingURL=babylon.standardMaterial.js.map
  15496. var BABYLON;
  15497. (function (BABYLON) {
  15498. var MultiMaterial = (function (_super) {
  15499. __extends(MultiMaterial, _super);
  15500. function MultiMaterial(name, scene) {
  15501. _super.call(this, name, scene, true);
  15502. this.subMaterials = new Array();
  15503. scene.multiMaterials.push(this);
  15504. }
  15505. // Properties
  15506. MultiMaterial.prototype.getSubMaterial = function (index) {
  15507. if (index < 0 || index >= this.subMaterials.length) {
  15508. return this.getScene().defaultMaterial;
  15509. }
  15510. return this.subMaterials[index];
  15511. };
  15512. // Methods
  15513. MultiMaterial.prototype.isReady = function (mesh) {
  15514. for (var index = 0; index < this.subMaterials.length; index++) {
  15515. var subMaterial = this.subMaterials[index];
  15516. if (subMaterial) {
  15517. if (!this.subMaterials[index].isReady(mesh)) {
  15518. return false;
  15519. }
  15520. }
  15521. }
  15522. return true;
  15523. };
  15524. return MultiMaterial;
  15525. })(BABYLON.Material);
  15526. BABYLON.MultiMaterial = MultiMaterial;
  15527. })(BABYLON || (BABYLON = {}));
  15528. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  15529. (function (BABYLON) {
  15530. var Database = (function () {
  15531. function Database(urlToScene, callbackManifestChecked) {
  15532. // Handling various flavors of prefixed version of IndexedDB
  15533. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  15534. this.callbackManifestChecked = callbackManifestChecked;
  15535. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  15536. this.db = null;
  15537. this.enableSceneOffline = false;
  15538. this.enableTexturesOffline = false;
  15539. this.manifestVersionFound = 0;
  15540. this.mustUpdateRessources = false;
  15541. this.hasReachedQuota = false;
  15542. this.checkManifestFile();
  15543. }
  15544. Database.prototype.checkManifestFile = function () {
  15545. var _this = this;
  15546. function noManifestFile() {
  15547. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  15548. that.enableSceneOffline = false;
  15549. that.enableTexturesOffline = false;
  15550. that.callbackManifestChecked(false);
  15551. }
  15552. var that = this;
  15553. var manifestURL = this.currentSceneUrl + ".manifest";
  15554. var xhr = new XMLHttpRequest();
  15555. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  15556. xhr.open("GET", manifestURLTimeStamped, true);
  15557. xhr.addEventListener("load", function () {
  15558. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15559. try {
  15560. var manifestFile = JSON.parse(xhr.response);
  15561. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  15562. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  15563. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  15564. _this.manifestVersionFound = manifestFile.version;
  15565. }
  15566. if (_this.callbackManifestChecked) {
  15567. _this.callbackManifestChecked(true);
  15568. }
  15569. }
  15570. catch (ex) {
  15571. noManifestFile();
  15572. }
  15573. }
  15574. else {
  15575. noManifestFile();
  15576. }
  15577. }, false);
  15578. xhr.addEventListener("error", function (event) {
  15579. noManifestFile();
  15580. }, false);
  15581. try {
  15582. xhr.send();
  15583. }
  15584. catch (ex) {
  15585. BABYLON.Tools.Error("Error on XHR send request.");
  15586. that.callbackManifestChecked(false);
  15587. }
  15588. };
  15589. Database.prototype.openAsync = function (successCallback, errorCallback) {
  15590. var _this = this;
  15591. function handleError() {
  15592. that.isSupported = false;
  15593. if (errorCallback)
  15594. errorCallback();
  15595. }
  15596. var that = this;
  15597. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  15598. // Your browser doesn't support IndexedDB
  15599. this.isSupported = false;
  15600. if (errorCallback)
  15601. errorCallback();
  15602. }
  15603. else {
  15604. // If the DB hasn't been opened or created yet
  15605. if (!this.db) {
  15606. this.hasReachedQuota = false;
  15607. this.isSupported = true;
  15608. var request = this.idbFactory.open("babylonjs", 1);
  15609. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  15610. request.onerror = function (event) {
  15611. handleError();
  15612. };
  15613. // executes when a version change transaction cannot complete due to other active transactions
  15614. request.onblocked = function (event) {
  15615. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  15616. handleError();
  15617. };
  15618. // DB has been opened successfully
  15619. request.onsuccess = function (event) {
  15620. _this.db = request.result;
  15621. successCallback();
  15622. };
  15623. // Initialization of the DB. Creating Scenes & Textures stores
  15624. request.onupgradeneeded = function (event) {
  15625. _this.db = (event.target).result;
  15626. try {
  15627. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  15628. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  15629. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  15630. }
  15631. catch (ex) {
  15632. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  15633. handleError();
  15634. }
  15635. };
  15636. }
  15637. else {
  15638. if (successCallback)
  15639. successCallback();
  15640. }
  15641. }
  15642. };
  15643. Database.prototype.loadImageFromDB = function (url, image) {
  15644. var _this = this;
  15645. var completeURL = Database.ReturnFullUrlLocation(url);
  15646. var saveAndLoadImage = function () {
  15647. if (!_this.hasReachedQuota && _this.db !== null) {
  15648. // the texture is not yet in the DB, let's try to save it
  15649. _this._saveImageIntoDBAsync(completeURL, image);
  15650. }
  15651. else {
  15652. image.src = url;
  15653. }
  15654. };
  15655. if (!this.mustUpdateRessources) {
  15656. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  15657. }
  15658. else {
  15659. saveAndLoadImage();
  15660. }
  15661. };
  15662. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  15663. if (this.isSupported && this.db !== null) {
  15664. var texture;
  15665. var transaction = this.db.transaction(["textures"]);
  15666. transaction.onabort = function (event) {
  15667. image.src = url;
  15668. };
  15669. transaction.oncomplete = function (event) {
  15670. var blobTextureURL;
  15671. if (texture) {
  15672. var URL = window.URL || window.webkitURL;
  15673. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  15674. image.onerror = function () {
  15675. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  15676. image.src = url;
  15677. };
  15678. image.src = blobTextureURL;
  15679. }
  15680. else {
  15681. notInDBCallback();
  15682. }
  15683. };
  15684. var getRequest = transaction.objectStore("textures").get(url);
  15685. getRequest.onsuccess = function (event) {
  15686. texture = (event.target).result;
  15687. };
  15688. getRequest.onerror = function (event) {
  15689. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  15690. image.src = url;
  15691. };
  15692. }
  15693. else {
  15694. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15695. image.src = url;
  15696. }
  15697. };
  15698. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  15699. var _this = this;
  15700. if (this.isSupported) {
  15701. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  15702. var generateBlobUrl = function () {
  15703. var blobTextureURL;
  15704. if (blob) {
  15705. var URL = window.URL || window.webkitURL;
  15706. try {
  15707. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  15708. }
  15709. catch (ex) {
  15710. blobTextureURL = URL.createObjectURL(blob);
  15711. }
  15712. }
  15713. image.src = blobTextureURL;
  15714. };
  15715. if (Database.isUASupportingBlobStorage) {
  15716. var xhr = new XMLHttpRequest(), blob;
  15717. xhr.open("GET", url, true);
  15718. xhr.responseType = "blob";
  15719. xhr.addEventListener("load", function () {
  15720. if (xhr.status === 200) {
  15721. // Blob as response (XHR2)
  15722. blob = xhr.response;
  15723. var transaction = _this.db.transaction(["textures"], "readwrite");
  15724. // the transaction could abort because of a QuotaExceededError error
  15725. transaction.onabort = function (event) {
  15726. try {
  15727. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15728. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15729. this.hasReachedQuota = true;
  15730. }
  15731. }
  15732. catch (ex) {
  15733. }
  15734. generateBlobUrl();
  15735. };
  15736. transaction.oncomplete = function (event) {
  15737. generateBlobUrl();
  15738. };
  15739. var newTexture = { textureUrl: url, data: blob };
  15740. try {
  15741. // Put the blob into the dabase
  15742. var addRequest = transaction.objectStore("textures").put(newTexture);
  15743. addRequest.onsuccess = function (event) {
  15744. };
  15745. addRequest.onerror = function (event) {
  15746. generateBlobUrl();
  15747. };
  15748. }
  15749. catch (ex) {
  15750. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  15751. if (ex.code === 25) {
  15752. Database.isUASupportingBlobStorage = false;
  15753. }
  15754. image.src = url;
  15755. }
  15756. }
  15757. else {
  15758. image.src = url;
  15759. }
  15760. }, false);
  15761. xhr.addEventListener("error", function (event) {
  15762. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  15763. image.src = url;
  15764. }, false);
  15765. xhr.send();
  15766. }
  15767. else {
  15768. image.src = url;
  15769. }
  15770. }
  15771. else {
  15772. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15773. image.src = url;
  15774. }
  15775. };
  15776. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  15777. var _this = this;
  15778. var updateVersion = function (event) {
  15779. // the version is not yet in the DB or we need to update it
  15780. _this._saveVersionIntoDBAsync(url, versionLoaded);
  15781. };
  15782. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  15783. };
  15784. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  15785. var _this = this;
  15786. if (this.isSupported) {
  15787. var version;
  15788. try {
  15789. var transaction = this.db.transaction(["versions"]);
  15790. transaction.oncomplete = function (event) {
  15791. if (version) {
  15792. // If the version in the JSON file is > than the version in DB
  15793. if (_this.manifestVersionFound > version.data) {
  15794. _this.mustUpdateRessources = true;
  15795. updateInDBCallback();
  15796. }
  15797. else {
  15798. callback(version.data);
  15799. }
  15800. }
  15801. else {
  15802. _this.mustUpdateRessources = true;
  15803. updateInDBCallback();
  15804. }
  15805. };
  15806. transaction.onabort = function (event) {
  15807. callback(-1);
  15808. };
  15809. var getRequest = transaction.objectStore("versions").get(url);
  15810. getRequest.onsuccess = function (event) {
  15811. version = (event.target).result;
  15812. };
  15813. getRequest.onerror = function (event) {
  15814. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  15815. callback(-1);
  15816. };
  15817. }
  15818. catch (ex) {
  15819. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  15820. callback(-1);
  15821. }
  15822. }
  15823. else {
  15824. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15825. callback(-1);
  15826. }
  15827. };
  15828. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  15829. var _this = this;
  15830. if (this.isSupported && !this.hasReachedQuota) {
  15831. try {
  15832. // Open a transaction to the database
  15833. var transaction = this.db.transaction(["versions"], "readwrite");
  15834. // the transaction could abort because of a QuotaExceededError error
  15835. transaction.onabort = function (event) {
  15836. try {
  15837. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15838. _this.hasReachedQuota = true;
  15839. }
  15840. }
  15841. catch (ex) {
  15842. }
  15843. callback(-1);
  15844. };
  15845. transaction.oncomplete = function (event) {
  15846. callback(_this.manifestVersionFound);
  15847. };
  15848. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  15849. // Put the scene into the database
  15850. var addRequest = transaction.objectStore("versions").put(newVersion);
  15851. addRequest.onsuccess = function (event) {
  15852. };
  15853. addRequest.onerror = function (event) {
  15854. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  15855. };
  15856. }
  15857. catch (ex) {
  15858. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  15859. callback(-1);
  15860. }
  15861. }
  15862. else {
  15863. callback(-1);
  15864. }
  15865. };
  15866. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  15867. var _this = this;
  15868. var completeUrl = Database.ReturnFullUrlLocation(url);
  15869. var saveAndLoadFile = function (event) {
  15870. // the scene is not yet in the DB, let's try to save it
  15871. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  15872. };
  15873. this._checkVersionFromDB(completeUrl, function (version) {
  15874. if (version !== -1) {
  15875. if (!_this.mustUpdateRessources) {
  15876. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  15877. }
  15878. else {
  15879. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  15880. }
  15881. }
  15882. else {
  15883. errorCallback();
  15884. }
  15885. });
  15886. };
  15887. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  15888. if (this.isSupported) {
  15889. var targetStore;
  15890. if (url.indexOf(".babylon") !== -1) {
  15891. targetStore = "scenes";
  15892. }
  15893. else {
  15894. targetStore = "textures";
  15895. }
  15896. var file;
  15897. var transaction = this.db.transaction([targetStore]);
  15898. transaction.oncomplete = function (event) {
  15899. if (file) {
  15900. callback(file.data);
  15901. }
  15902. else {
  15903. notInDBCallback();
  15904. }
  15905. };
  15906. transaction.onabort = function (event) {
  15907. notInDBCallback();
  15908. };
  15909. var getRequest = transaction.objectStore(targetStore).get(url);
  15910. getRequest.onsuccess = function (event) {
  15911. file = (event.target).result;
  15912. };
  15913. getRequest.onerror = function (event) {
  15914. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15915. notInDBCallback();
  15916. };
  15917. }
  15918. else {
  15919. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15920. callback();
  15921. }
  15922. };
  15923. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15924. var _this = this;
  15925. if (this.isSupported) {
  15926. var targetStore;
  15927. if (url.indexOf(".babylon") !== -1) {
  15928. targetStore = "scenes";
  15929. }
  15930. else {
  15931. targetStore = "textures";
  15932. }
  15933. // Create XHR
  15934. var xhr = new XMLHttpRequest(), fileData;
  15935. xhr.open("GET", url, true);
  15936. if (useArrayBuffer) {
  15937. xhr.responseType = "arraybuffer";
  15938. }
  15939. xhr.onprogress = progressCallback;
  15940. xhr.addEventListener("load", function () {
  15941. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15942. // Blob as response (XHR2)
  15943. //fileData = xhr.responseText;
  15944. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15945. if (!_this.hasReachedQuota) {
  15946. // Open a transaction to the database
  15947. var transaction = _this.db.transaction([targetStore], "readwrite");
  15948. // the transaction could abort because of a QuotaExceededError error
  15949. transaction.onabort = function (event) {
  15950. try {
  15951. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15952. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15953. this.hasReachedQuota = true;
  15954. }
  15955. }
  15956. catch (ex) {
  15957. }
  15958. callback(fileData);
  15959. };
  15960. transaction.oncomplete = function (event) {
  15961. callback(fileData);
  15962. };
  15963. var newFile;
  15964. if (targetStore === "scenes") {
  15965. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15966. }
  15967. else {
  15968. newFile = { textureUrl: url, data: fileData };
  15969. }
  15970. try {
  15971. // Put the scene into the database
  15972. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15973. addRequest.onsuccess = function (event) {
  15974. };
  15975. addRequest.onerror = function (event) {
  15976. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15977. };
  15978. }
  15979. catch (ex) {
  15980. callback(fileData);
  15981. }
  15982. }
  15983. else {
  15984. callback(fileData);
  15985. }
  15986. }
  15987. else {
  15988. callback();
  15989. }
  15990. }, false);
  15991. xhr.addEventListener("error", function (event) {
  15992. BABYLON.Tools.Error("error on XHR request.");
  15993. callback();
  15994. }, false);
  15995. xhr.send();
  15996. }
  15997. else {
  15998. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15999. callback();
  16000. }
  16001. };
  16002. Database.isUASupportingBlobStorage = true;
  16003. Database.parseURL = function (url) {
  16004. var a = document.createElement('a');
  16005. a.href = url;
  16006. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  16007. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  16008. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  16009. return absLocation;
  16010. };
  16011. Database.ReturnFullUrlLocation = function (url) {
  16012. if (url.indexOf("http:/") === -1) {
  16013. return (BABYLON.Database.parseURL(window.location.href) + url);
  16014. }
  16015. else {
  16016. return url;
  16017. }
  16018. };
  16019. return Database;
  16020. })();
  16021. BABYLON.Database = Database;
  16022. })(BABYLON || (BABYLON = {}));
  16023. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  16024. (function (BABYLON) {
  16025. var SpriteManager = (function () {
  16026. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  16027. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16028. this.name = name;
  16029. this.cellSize = cellSize;
  16030. this.sprites = new Array();
  16031. this.renderingGroupId = 0;
  16032. this.fogEnabled = true;
  16033. this._vertexDeclaration = [4, 4, 4, 4];
  16034. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  16035. this._capacity = capacity;
  16036. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  16037. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16038. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16039. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  16040. this._scene = scene;
  16041. this._scene.spriteManagers.push(this);
  16042. // VBO
  16043. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  16044. var indices = [];
  16045. var index = 0;
  16046. for (var count = 0; count < capacity; count++) {
  16047. indices.push(index);
  16048. indices.push(index + 1);
  16049. indices.push(index + 2);
  16050. indices.push(index);
  16051. indices.push(index + 2);
  16052. indices.push(index + 3);
  16053. index += 4;
  16054. }
  16055. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16056. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  16057. // Effects
  16058. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  16059. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  16060. }
  16061. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  16062. var arrayOffset = index * 16;
  16063. if (offsetX === 0)
  16064. offsetX = this._epsilon;
  16065. else if (offsetX === 1)
  16066. offsetX = 1 - this._epsilon;
  16067. if (offsetY === 0)
  16068. offsetY = this._epsilon;
  16069. else if (offsetY === 1)
  16070. offsetY = 1 - this._epsilon;
  16071. this._vertices[arrayOffset] = sprite.position.x;
  16072. this._vertices[arrayOffset + 1] = sprite.position.y;
  16073. this._vertices[arrayOffset + 2] = sprite.position.z;
  16074. this._vertices[arrayOffset + 3] = sprite.angle;
  16075. this._vertices[arrayOffset + 4] = sprite.width;
  16076. this._vertices[arrayOffset + 5] = sprite.height;
  16077. this._vertices[arrayOffset + 6] = offsetX;
  16078. this._vertices[arrayOffset + 7] = offsetY;
  16079. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  16080. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  16081. var offset = (sprite.cellIndex / rowSize) >> 0;
  16082. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  16083. this._vertices[arrayOffset + 11] = offset;
  16084. // Color
  16085. this._vertices[arrayOffset + 12] = sprite.color.r;
  16086. this._vertices[arrayOffset + 13] = sprite.color.g;
  16087. this._vertices[arrayOffset + 14] = sprite.color.b;
  16088. this._vertices[arrayOffset + 15] = sprite.color.a;
  16089. };
  16090. SpriteManager.prototype.render = function () {
  16091. // Check
  16092. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  16093. return;
  16094. var engine = this._scene.getEngine();
  16095. var baseSize = this._spriteTexture.getBaseSize();
  16096. // Sprites
  16097. var deltaTime = engine.getDeltaTime();
  16098. var max = Math.min(this._capacity, this.sprites.length);
  16099. var rowSize = baseSize.width / this.cellSize;
  16100. var offset = 0;
  16101. for (var index = 0; index < max; index++) {
  16102. var sprite = this.sprites[index];
  16103. if (!sprite) {
  16104. continue;
  16105. }
  16106. sprite._animate(deltaTime);
  16107. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  16108. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  16109. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  16110. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  16111. }
  16112. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16113. // Render
  16114. var effect = this._effectBase;
  16115. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  16116. effect = this._effectFog;
  16117. }
  16118. engine.enableEffect(effect);
  16119. var viewMatrix = this._scene.getViewMatrix();
  16120. effect.setTexture("diffuseSampler", this._spriteTexture);
  16121. effect.setMatrix("view", viewMatrix);
  16122. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16123. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  16124. // Fog
  16125. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  16126. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  16127. effect.setColor3("vFogColor", this._scene.fogColor);
  16128. }
  16129. // VBOs
  16130. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16131. // Draw order
  16132. engine.setDepthFunctionToLessOrEqual();
  16133. effect.setBool("alphaTest", true);
  16134. engine.setColorWrite(false);
  16135. engine.draw(true, 0, max * 6);
  16136. engine.setColorWrite(true);
  16137. effect.setBool("alphaTest", false);
  16138. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16139. engine.draw(true, 0, max * 6);
  16140. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16141. };
  16142. SpriteManager.prototype.dispose = function () {
  16143. if (this._vertexBuffer) {
  16144. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16145. this._vertexBuffer = null;
  16146. }
  16147. if (this._indexBuffer) {
  16148. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16149. this._indexBuffer = null;
  16150. }
  16151. if (this._spriteTexture) {
  16152. this._spriteTexture.dispose();
  16153. this._spriteTexture = null;
  16154. }
  16155. // Remove from scene
  16156. var index = this._scene.spriteManagers.indexOf(this);
  16157. this._scene.spriteManagers.splice(index, 1);
  16158. // Callback
  16159. if (this.onDispose) {
  16160. this.onDispose();
  16161. }
  16162. };
  16163. return SpriteManager;
  16164. })();
  16165. BABYLON.SpriteManager = SpriteManager;
  16166. })(BABYLON || (BABYLON = {}));
  16167. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  16168. (function (BABYLON) {
  16169. var Sprite = (function () {
  16170. function Sprite(name, manager) {
  16171. this.name = name;
  16172. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16173. this.width = 1.0;
  16174. this.height = 1.0;
  16175. this.angle = 0;
  16176. this.cellIndex = 0;
  16177. this.invertU = 0;
  16178. this.invertV = 0;
  16179. this.animations = new Array();
  16180. this._animationStarted = false;
  16181. this._loopAnimation = false;
  16182. this._fromIndex = 0;
  16183. this._toIndex = 0;
  16184. this._delay = 0;
  16185. this._direction = 1;
  16186. this._frameCount = 0;
  16187. this._time = 0;
  16188. this._manager = manager;
  16189. this._manager.sprites.push(this);
  16190. this.position = BABYLON.Vector3.Zero();
  16191. }
  16192. Object.defineProperty(Sprite.prototype, "size", {
  16193. get: function () {
  16194. return this.width;
  16195. },
  16196. set: function (value) {
  16197. this.width = value;
  16198. this.height = value;
  16199. },
  16200. enumerable: true,
  16201. configurable: true
  16202. });
  16203. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  16204. this._fromIndex = from;
  16205. this._toIndex = to;
  16206. this._loopAnimation = loop;
  16207. this._delay = delay;
  16208. this._animationStarted = true;
  16209. this._direction = from < to ? 1 : -1;
  16210. this.cellIndex = from;
  16211. this._time = 0;
  16212. };
  16213. Sprite.prototype.stopAnimation = function () {
  16214. this._animationStarted = false;
  16215. };
  16216. Sprite.prototype._animate = function (deltaTime) {
  16217. if (!this._animationStarted)
  16218. return;
  16219. this._time += deltaTime;
  16220. if (this._time > this._delay) {
  16221. this._time = this._time % this._delay;
  16222. this.cellIndex += this._direction;
  16223. if (this.cellIndex == this._toIndex) {
  16224. if (this._loopAnimation) {
  16225. this.cellIndex = this._fromIndex;
  16226. }
  16227. else {
  16228. this._animationStarted = false;
  16229. if (this.disposeWhenFinishedAnimating) {
  16230. this.dispose();
  16231. }
  16232. }
  16233. }
  16234. }
  16235. };
  16236. Sprite.prototype.dispose = function () {
  16237. for (var i = 0; i < this._manager.sprites.length; i++) {
  16238. if (this._manager.sprites[i] == this) {
  16239. this._manager.sprites.splice(i, 1);
  16240. }
  16241. }
  16242. };
  16243. return Sprite;
  16244. })();
  16245. BABYLON.Sprite = Sprite;
  16246. })(BABYLON || (BABYLON = {}));
  16247. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  16248. (function (BABYLON) {
  16249. var Layer = (function () {
  16250. function Layer(name, imgUrl, scene, isBackground, color) {
  16251. this.name = name;
  16252. this._vertexDeclaration = [2];
  16253. this._vertexStrideSize = 2 * 4;
  16254. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  16255. this.isBackground = isBackground === undefined ? true : isBackground;
  16256. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  16257. this._scene = scene;
  16258. this._scene.layers.push(this);
  16259. // VBO
  16260. var vertices = [];
  16261. vertices.push(1, 1);
  16262. vertices.push(-1, 1);
  16263. vertices.push(-1, -1);
  16264. vertices.push(1, -1);
  16265. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16266. // Indices
  16267. var indices = [];
  16268. indices.push(0);
  16269. indices.push(1);
  16270. indices.push(2);
  16271. indices.push(0);
  16272. indices.push(2);
  16273. indices.push(3);
  16274. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16275. // Effects
  16276. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  16277. }
  16278. Layer.prototype.render = function () {
  16279. // Check
  16280. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  16281. return;
  16282. var engine = this._scene.getEngine();
  16283. // Render
  16284. engine.enableEffect(this._effect);
  16285. engine.setState(false);
  16286. // Texture
  16287. this._effect.setTexture("textureSampler", this.texture);
  16288. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  16289. // Color
  16290. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  16291. // VBOs
  16292. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16293. // Draw order
  16294. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16295. engine.draw(true, 0, 6);
  16296. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16297. };
  16298. Layer.prototype.dispose = function () {
  16299. if (this._vertexBuffer) {
  16300. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16301. this._vertexBuffer = null;
  16302. }
  16303. if (this._indexBuffer) {
  16304. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16305. this._indexBuffer = null;
  16306. }
  16307. if (this.texture) {
  16308. this.texture.dispose();
  16309. this.texture = null;
  16310. }
  16311. // Remove from scene
  16312. var index = this._scene.layers.indexOf(this);
  16313. this._scene.layers.splice(index, 1);
  16314. // Callback
  16315. if (this.onDispose) {
  16316. this.onDispose();
  16317. }
  16318. };
  16319. return Layer;
  16320. })();
  16321. BABYLON.Layer = Layer;
  16322. })(BABYLON || (BABYLON = {}));
  16323. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  16324. (function (BABYLON) {
  16325. var Particle = (function () {
  16326. function Particle() {
  16327. this.position = BABYLON.Vector3.Zero();
  16328. this.direction = BABYLON.Vector3.Zero();
  16329. this.color = new BABYLON.Color4(0, 0, 0, 0);
  16330. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  16331. this.lifeTime = 1.0;
  16332. this.age = 0;
  16333. this.size = 0;
  16334. this.angle = 0;
  16335. this.angularSpeed = 0;
  16336. }
  16337. Particle.prototype.copyTo = function (other) {
  16338. other.position.copyFrom(this.position);
  16339. other.direction.copyFrom(this.direction);
  16340. other.color.copyFrom(this.color);
  16341. other.colorStep.copyFrom(this.colorStep);
  16342. other.lifeTime = this.lifeTime;
  16343. other.age = this.age;
  16344. other.size = this.size;
  16345. other.angle = this.angle;
  16346. other.angularSpeed = this.angularSpeed;
  16347. };
  16348. return Particle;
  16349. })();
  16350. BABYLON.Particle = Particle;
  16351. })(BABYLON || (BABYLON = {}));
  16352. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  16353. (function (BABYLON) {
  16354. var randomNumber = function (min, max) {
  16355. if (min === max) {
  16356. return (min);
  16357. }
  16358. var random = Math.random();
  16359. return ((random * (max - min)) + min);
  16360. };
  16361. var ParticleSystem = (function () {
  16362. function ParticleSystem(name, capacity, scene, customEffect) {
  16363. var _this = this;
  16364. this.name = name;
  16365. this.renderingGroupId = 0;
  16366. this.emitter = null;
  16367. this.emitRate = 10;
  16368. this.manualEmitCount = -1;
  16369. this.updateSpeed = 0.01;
  16370. this.targetStopDuration = 0;
  16371. this.disposeOnStop = false;
  16372. this.minEmitPower = 1;
  16373. this.maxEmitPower = 1;
  16374. this.minLifeTime = 1;
  16375. this.maxLifeTime = 1;
  16376. this.minSize = 1;
  16377. this.maxSize = 1;
  16378. this.minAngularSpeed = 0;
  16379. this.maxAngularSpeed = 0;
  16380. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  16381. this.forceDepthWrite = false;
  16382. this.gravity = BABYLON.Vector3.Zero();
  16383. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  16384. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  16385. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  16386. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  16387. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16388. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16389. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  16390. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16391. this.particles = new Array();
  16392. this._vertexDeclaration = [3, 4, 4];
  16393. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  16394. this._stockParticles = new Array();
  16395. this._newPartsExcess = 0;
  16396. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  16397. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  16398. this._scaledDirection = BABYLON.Vector3.Zero();
  16399. this._scaledGravity = BABYLON.Vector3.Zero();
  16400. this._currentRenderId = -1;
  16401. this._started = false;
  16402. this._stopped = false;
  16403. this._actualFrame = 0;
  16404. this.id = name;
  16405. this._capacity = capacity;
  16406. this._scene = scene;
  16407. this._customEffect = customEffect;
  16408. scene.particleSystems.push(this);
  16409. // VBO
  16410. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  16411. var indices = [];
  16412. var index = 0;
  16413. for (var count = 0; count < capacity; count++) {
  16414. indices.push(index);
  16415. indices.push(index + 1);
  16416. indices.push(index + 2);
  16417. indices.push(index);
  16418. indices.push(index + 2);
  16419. indices.push(index + 3);
  16420. index += 4;
  16421. }
  16422. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16423. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  16424. // Default behaviors
  16425. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  16426. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  16427. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  16428. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  16429. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  16430. };
  16431. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  16432. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  16433. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  16434. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  16435. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  16436. };
  16437. this.updateFunction = function (particles) {
  16438. for (var index = 0; index < particles.length; index++) {
  16439. var particle = particles[index];
  16440. particle.age += _this._scaledUpdateSpeed;
  16441. if (particle.age >= particle.lifeTime) {
  16442. _this.recycleParticle(particle);
  16443. index--;
  16444. continue;
  16445. }
  16446. else {
  16447. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  16448. particle.color.addInPlace(_this._scaledColorStep);
  16449. if (particle.color.a < 0)
  16450. particle.color.a = 0;
  16451. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  16452. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  16453. particle.position.addInPlace(_this._scaledDirection);
  16454. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  16455. particle.direction.addInPlace(_this._scaledGravity);
  16456. }
  16457. }
  16458. };
  16459. }
  16460. ParticleSystem.prototype.recycleParticle = function (particle) {
  16461. var lastParticle = this.particles.pop();
  16462. if (lastParticle !== particle) {
  16463. lastParticle.copyTo(particle);
  16464. this._stockParticles.push(lastParticle);
  16465. }
  16466. };
  16467. ParticleSystem.prototype.getCapacity = function () {
  16468. return this._capacity;
  16469. };
  16470. ParticleSystem.prototype.isAlive = function () {
  16471. return this._alive;
  16472. };
  16473. ParticleSystem.prototype.isStarted = function () {
  16474. return this._started;
  16475. };
  16476. ParticleSystem.prototype.start = function () {
  16477. this._started = true;
  16478. this._stopped = false;
  16479. this._actualFrame = 0;
  16480. };
  16481. ParticleSystem.prototype.stop = function () {
  16482. this._stopped = true;
  16483. };
  16484. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  16485. var offset = index * 11;
  16486. this._vertices[offset] = particle.position.x;
  16487. this._vertices[offset + 1] = particle.position.y;
  16488. this._vertices[offset + 2] = particle.position.z;
  16489. this._vertices[offset + 3] = particle.color.r;
  16490. this._vertices[offset + 4] = particle.color.g;
  16491. this._vertices[offset + 5] = particle.color.b;
  16492. this._vertices[offset + 6] = particle.color.a;
  16493. this._vertices[offset + 7] = particle.angle;
  16494. this._vertices[offset + 8] = particle.size;
  16495. this._vertices[offset + 9] = offsetX;
  16496. this._vertices[offset + 10] = offsetY;
  16497. };
  16498. ParticleSystem.prototype._update = function (newParticles) {
  16499. // Update current
  16500. this._alive = this.particles.length > 0;
  16501. this.updateFunction(this.particles);
  16502. // Add new ones
  16503. var worldMatrix;
  16504. if (this.emitter.position) {
  16505. worldMatrix = this.emitter.getWorldMatrix();
  16506. }
  16507. else {
  16508. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  16509. }
  16510. for (var index = 0; index < newParticles; index++) {
  16511. if (this.particles.length === this._capacity) {
  16512. break;
  16513. }
  16514. if (this._stockParticles.length !== 0) {
  16515. var particle = this._stockParticles.pop();
  16516. particle.age = 0;
  16517. }
  16518. else {
  16519. particle = new BABYLON.Particle();
  16520. }
  16521. this.particles.push(particle);
  16522. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  16523. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  16524. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  16525. particle.size = randomNumber(this.minSize, this.maxSize);
  16526. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  16527. this.startPositionFunction(worldMatrix, particle.position);
  16528. var step = randomNumber(0, 1.0);
  16529. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  16530. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  16531. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  16532. }
  16533. };
  16534. ParticleSystem.prototype._getEffect = function () {
  16535. if (this._customEffect) {
  16536. return this._customEffect;
  16537. }
  16538. ;
  16539. var defines = [];
  16540. if (this._scene.clipPlane) {
  16541. defines.push("#define CLIPPLANE");
  16542. }
  16543. // Effect
  16544. var join = defines.join("\n");
  16545. if (this._cachedDefines !== join) {
  16546. this._cachedDefines = join;
  16547. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  16548. }
  16549. return this._effect;
  16550. };
  16551. ParticleSystem.prototype.animate = function () {
  16552. if (!this._started)
  16553. return;
  16554. var effect = this._getEffect();
  16555. // Check
  16556. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  16557. return;
  16558. if (this._currentRenderId === this._scene.getRenderId()) {
  16559. return;
  16560. }
  16561. this._currentRenderId = this._scene.getRenderId();
  16562. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  16563. // determine the number of particles we need to create
  16564. var emitCout;
  16565. if (this.manualEmitCount > -1) {
  16566. emitCout = this.manualEmitCount;
  16567. this.manualEmitCount = 0;
  16568. }
  16569. else {
  16570. emitCout = this.emitRate;
  16571. }
  16572. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  16573. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  16574. if (this._newPartsExcess > 1.0) {
  16575. newParticles += this._newPartsExcess >> 0;
  16576. this._newPartsExcess -= this._newPartsExcess >> 0;
  16577. }
  16578. this._alive = false;
  16579. if (!this._stopped) {
  16580. this._actualFrame += this._scaledUpdateSpeed;
  16581. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  16582. this.stop();
  16583. }
  16584. else {
  16585. newParticles = 0;
  16586. }
  16587. this._update(newParticles);
  16588. // Stopped?
  16589. if (this._stopped) {
  16590. if (!this._alive) {
  16591. this._started = false;
  16592. if (this.disposeOnStop) {
  16593. this._scene._toBeDisposed.push(this);
  16594. }
  16595. }
  16596. }
  16597. // Update VBO
  16598. var offset = 0;
  16599. for (var index = 0; index < this.particles.length; index++) {
  16600. var particle = this.particles[index];
  16601. this._appendParticleVertex(offset++, particle, 0, 0);
  16602. this._appendParticleVertex(offset++, particle, 1, 0);
  16603. this._appendParticleVertex(offset++, particle, 1, 1);
  16604. this._appendParticleVertex(offset++, particle, 0, 1);
  16605. }
  16606. var engine = this._scene.getEngine();
  16607. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16608. };
  16609. ParticleSystem.prototype.render = function () {
  16610. var effect = this._getEffect();
  16611. // Check
  16612. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  16613. return 0;
  16614. var engine = this._scene.getEngine();
  16615. // Render
  16616. engine.enableEffect(effect);
  16617. engine.setState(false);
  16618. var viewMatrix = this._scene.getViewMatrix();
  16619. effect.setTexture("diffuseSampler", this.particleTexture);
  16620. effect.setMatrix("view", viewMatrix);
  16621. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16622. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  16623. if (this._scene.clipPlane) {
  16624. var clipPlane = this._scene.clipPlane;
  16625. var invView = viewMatrix.clone();
  16626. invView.invert();
  16627. effect.setMatrix("invView", invView);
  16628. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  16629. }
  16630. // VBOs
  16631. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16632. // Draw order
  16633. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  16634. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16635. }
  16636. else {
  16637. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16638. }
  16639. if (this.forceDepthWrite) {
  16640. engine.setDepthWrite(true);
  16641. }
  16642. engine.draw(true, 0, this.particles.length * 6);
  16643. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16644. return this.particles.length;
  16645. };
  16646. ParticleSystem.prototype.dispose = function () {
  16647. if (this._vertexBuffer) {
  16648. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16649. this._vertexBuffer = null;
  16650. }
  16651. if (this._indexBuffer) {
  16652. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16653. this._indexBuffer = null;
  16654. }
  16655. if (this.particleTexture) {
  16656. this.particleTexture.dispose();
  16657. this.particleTexture = null;
  16658. }
  16659. // Remove from scene
  16660. var index = this._scene.particleSystems.indexOf(this);
  16661. this._scene.particleSystems.splice(index, 1);
  16662. // Callback
  16663. if (this.onDispose) {
  16664. this.onDispose();
  16665. }
  16666. };
  16667. // Clone
  16668. ParticleSystem.prototype.clone = function (name, newEmitter) {
  16669. var result = new ParticleSystem(name, this._capacity, this._scene);
  16670. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  16671. if (newEmitter === undefined) {
  16672. newEmitter = this.emitter;
  16673. }
  16674. result.emitter = newEmitter;
  16675. if (this.particleTexture) {
  16676. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  16677. }
  16678. result.start();
  16679. return result;
  16680. };
  16681. // Statics
  16682. ParticleSystem.BLENDMODE_ONEONE = 0;
  16683. ParticleSystem.BLENDMODE_STANDARD = 1;
  16684. return ParticleSystem;
  16685. })();
  16686. BABYLON.ParticleSystem = ParticleSystem;
  16687. })(BABYLON || (BABYLON = {}));
  16688. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  16689. (function (BABYLON) {
  16690. var Animation = (function () {
  16691. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  16692. this.name = name;
  16693. this.targetProperty = targetProperty;
  16694. this.framePerSecond = framePerSecond;
  16695. this.dataType = dataType;
  16696. this.loopMode = loopMode;
  16697. this._offsetsCache = {};
  16698. this._highLimitsCache = {};
  16699. this._stopped = false;
  16700. this.targetPropertyPath = targetProperty.split(".");
  16701. this.dataType = dataType;
  16702. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  16703. }
  16704. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  16705. var dataType = undefined;
  16706. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  16707. dataType = Animation.ANIMATIONTYPE_FLOAT;
  16708. }
  16709. else if (from instanceof BABYLON.Quaternion) {
  16710. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  16711. }
  16712. else if (from instanceof BABYLON.Vector3) {
  16713. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  16714. }
  16715. else if (from instanceof BABYLON.Vector2) {
  16716. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  16717. }
  16718. else if (from instanceof BABYLON.Color3) {
  16719. dataType = Animation.ANIMATIONTYPE_COLOR3;
  16720. }
  16721. if (dataType == undefined) {
  16722. return null;
  16723. }
  16724. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  16725. var keys = [];
  16726. keys.push({ frame: 0, value: from });
  16727. keys.push({ frame: totalFrame, value: to });
  16728. animation.setKeys(keys);
  16729. mesh.animations.push(animation);
  16730. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  16731. };
  16732. // Methods
  16733. Animation.prototype.isStopped = function () {
  16734. return this._stopped;
  16735. };
  16736. Animation.prototype.getKeys = function () {
  16737. return this._keys;
  16738. };
  16739. Animation.prototype.getEasingFunction = function () {
  16740. return this._easingFunction;
  16741. };
  16742. Animation.prototype.setEasingFunction = function (easingFunction) {
  16743. this._easingFunction = easingFunction;
  16744. };
  16745. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  16746. return startValue + (endValue - startValue) * gradient;
  16747. };
  16748. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  16749. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  16750. };
  16751. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  16752. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  16753. };
  16754. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  16755. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  16756. };
  16757. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  16758. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  16759. };
  16760. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  16761. var startScale = new BABYLON.Vector3(0, 0, 0);
  16762. var startRotation = new BABYLON.Quaternion();
  16763. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  16764. startValue.decompose(startScale, startRotation, startTranslation);
  16765. var endScale = new BABYLON.Vector3(0, 0, 0);
  16766. var endRotation = new BABYLON.Quaternion();
  16767. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  16768. endValue.decompose(endScale, endRotation, endTranslation);
  16769. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  16770. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  16771. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  16772. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  16773. return result;
  16774. };
  16775. Animation.prototype.clone = function () {
  16776. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  16777. clone.setKeys(this._keys);
  16778. return clone;
  16779. };
  16780. Animation.prototype.setKeys = function (values) {
  16781. this._keys = values.slice(0);
  16782. this._offsetsCache = {};
  16783. this._highLimitsCache = {};
  16784. };
  16785. Animation.prototype._getKeyValue = function (value) {
  16786. if (typeof value === "function") {
  16787. return value();
  16788. }
  16789. return value;
  16790. };
  16791. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  16792. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  16793. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  16794. }
  16795. this.currentFrame = currentFrame;
  16796. // Try to get a hash to find the right key
  16797. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  16798. if (this._keys[startKey].frame >= currentFrame) {
  16799. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  16800. startKey--;
  16801. }
  16802. }
  16803. for (var key = startKey; key < this._keys.length; key++) {
  16804. if (this._keys[key + 1].frame >= currentFrame) {
  16805. var startValue = this._getKeyValue(this._keys[key].value);
  16806. var endValue = this._getKeyValue(this._keys[key + 1].value);
  16807. // gradient : percent of currentFrame between the frame inf and the frame sup
  16808. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  16809. // check for easingFunction and correction of gradient
  16810. if (this._easingFunction != null) {
  16811. gradient = this._easingFunction.ease(gradient);
  16812. }
  16813. switch (this.dataType) {
  16814. case Animation.ANIMATIONTYPE_FLOAT:
  16815. switch (loopMode) {
  16816. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16817. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16818. return this.floatInterpolateFunction(startValue, endValue, gradient);
  16819. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16820. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  16821. }
  16822. break;
  16823. case Animation.ANIMATIONTYPE_QUATERNION:
  16824. var quaternion = null;
  16825. switch (loopMode) {
  16826. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16827. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16828. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  16829. break;
  16830. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16831. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16832. break;
  16833. }
  16834. return quaternion;
  16835. case Animation.ANIMATIONTYPE_VECTOR3:
  16836. switch (loopMode) {
  16837. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16838. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16839. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  16840. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16841. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16842. }
  16843. case Animation.ANIMATIONTYPE_VECTOR2:
  16844. switch (loopMode) {
  16845. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16846. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16847. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  16848. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16849. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16850. }
  16851. case Animation.ANIMATIONTYPE_COLOR3:
  16852. switch (loopMode) {
  16853. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16854. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16855. return this.color3InterpolateFunction(startValue, endValue, gradient);
  16856. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16857. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16858. }
  16859. case Animation.ANIMATIONTYPE_MATRIX:
  16860. switch (loopMode) {
  16861. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16862. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16863. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16864. return startValue;
  16865. }
  16866. default:
  16867. break;
  16868. }
  16869. break;
  16870. }
  16871. }
  16872. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  16873. };
  16874. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  16875. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  16876. this._stopped = true;
  16877. return false;
  16878. }
  16879. var returnValue = true;
  16880. // Adding a start key at frame 0 if missing
  16881. if (this._keys[0].frame !== 0) {
  16882. var newKey = { frame: 0, value: this._keys[0].value };
  16883. this._keys.splice(0, 0, newKey);
  16884. }
  16885. // Check limits
  16886. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  16887. from = this._keys[0].frame;
  16888. }
  16889. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  16890. to = this._keys[this._keys.length - 1].frame;
  16891. }
  16892. // Compute ratio
  16893. var range = to - from;
  16894. var offsetValue;
  16895. // ratio represents the frame delta between from and to
  16896. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  16897. var highLimitValue = 0;
  16898. if (ratio > range && !loop) {
  16899. returnValue = false;
  16900. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  16901. }
  16902. else {
  16903. // Get max value if required
  16904. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  16905. var keyOffset = to.toString() + from.toString();
  16906. if (!this._offsetsCache[keyOffset]) {
  16907. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16908. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16909. switch (this.dataType) {
  16910. case Animation.ANIMATIONTYPE_FLOAT:
  16911. this._offsetsCache[keyOffset] = toValue - fromValue;
  16912. break;
  16913. case Animation.ANIMATIONTYPE_QUATERNION:
  16914. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16915. break;
  16916. case Animation.ANIMATIONTYPE_VECTOR3:
  16917. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16918. case Animation.ANIMATIONTYPE_VECTOR2:
  16919. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16920. case Animation.ANIMATIONTYPE_COLOR3:
  16921. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16922. default:
  16923. break;
  16924. }
  16925. this._highLimitsCache[keyOffset] = toValue;
  16926. }
  16927. highLimitValue = this._highLimitsCache[keyOffset];
  16928. offsetValue = this._offsetsCache[keyOffset];
  16929. }
  16930. }
  16931. if (offsetValue === undefined) {
  16932. switch (this.dataType) {
  16933. case Animation.ANIMATIONTYPE_FLOAT:
  16934. offsetValue = 0;
  16935. break;
  16936. case Animation.ANIMATIONTYPE_QUATERNION:
  16937. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16938. break;
  16939. case Animation.ANIMATIONTYPE_VECTOR3:
  16940. offsetValue = BABYLON.Vector3.Zero();
  16941. break;
  16942. case Animation.ANIMATIONTYPE_VECTOR2:
  16943. offsetValue = BABYLON.Vector2.Zero();
  16944. break;
  16945. case Animation.ANIMATIONTYPE_COLOR3:
  16946. offsetValue = BABYLON.Color3.Black();
  16947. }
  16948. }
  16949. // Compute value
  16950. var repeatCount = (ratio / range) >> 0;
  16951. var currentFrame = returnValue ? from + ratio % range : to;
  16952. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16953. // Set value
  16954. if (this.targetPropertyPath.length > 1) {
  16955. var property = this._target[this.targetPropertyPath[0]];
  16956. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16957. property = property[this.targetPropertyPath[index]];
  16958. }
  16959. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16960. }
  16961. else {
  16962. this._target[this.targetPropertyPath[0]] = currentValue;
  16963. }
  16964. if (this._target.markAsDirty) {
  16965. this._target.markAsDirty(this.targetProperty);
  16966. }
  16967. if (!returnValue) {
  16968. this._stopped = true;
  16969. }
  16970. return returnValue;
  16971. };
  16972. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16973. get: function () {
  16974. return Animation._ANIMATIONTYPE_FLOAT;
  16975. },
  16976. enumerable: true,
  16977. configurable: true
  16978. });
  16979. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16980. get: function () {
  16981. return Animation._ANIMATIONTYPE_VECTOR3;
  16982. },
  16983. enumerable: true,
  16984. configurable: true
  16985. });
  16986. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16987. get: function () {
  16988. return Animation._ANIMATIONTYPE_VECTOR2;
  16989. },
  16990. enumerable: true,
  16991. configurable: true
  16992. });
  16993. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16994. get: function () {
  16995. return Animation._ANIMATIONTYPE_QUATERNION;
  16996. },
  16997. enumerable: true,
  16998. configurable: true
  16999. });
  17000. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  17001. get: function () {
  17002. return Animation._ANIMATIONTYPE_MATRIX;
  17003. },
  17004. enumerable: true,
  17005. configurable: true
  17006. });
  17007. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  17008. get: function () {
  17009. return Animation._ANIMATIONTYPE_COLOR3;
  17010. },
  17011. enumerable: true,
  17012. configurable: true
  17013. });
  17014. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  17015. get: function () {
  17016. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  17017. },
  17018. enumerable: true,
  17019. configurable: true
  17020. });
  17021. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  17022. get: function () {
  17023. return Animation._ANIMATIONLOOPMODE_CYCLE;
  17024. },
  17025. enumerable: true,
  17026. configurable: true
  17027. });
  17028. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  17029. get: function () {
  17030. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  17031. },
  17032. enumerable: true,
  17033. configurable: true
  17034. });
  17035. // Statics
  17036. Animation._ANIMATIONTYPE_FLOAT = 0;
  17037. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  17038. Animation._ANIMATIONTYPE_QUATERNION = 2;
  17039. Animation._ANIMATIONTYPE_MATRIX = 3;
  17040. Animation._ANIMATIONTYPE_COLOR3 = 4;
  17041. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  17042. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  17043. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  17044. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  17045. return Animation;
  17046. })();
  17047. BABYLON.Animation = Animation;
  17048. })(BABYLON || (BABYLON = {}));
  17049. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  17050. (function (BABYLON) {
  17051. var Animatable = (function () {
  17052. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  17053. if (fromFrame === void 0) { fromFrame = 0; }
  17054. if (toFrame === void 0) { toFrame = 100; }
  17055. if (loopAnimation === void 0) { loopAnimation = false; }
  17056. if (speedRatio === void 0) { speedRatio = 1.0; }
  17057. this.target = target;
  17058. this.fromFrame = fromFrame;
  17059. this.toFrame = toFrame;
  17060. this.loopAnimation = loopAnimation;
  17061. this.speedRatio = speedRatio;
  17062. this.onAnimationEnd = onAnimationEnd;
  17063. this._animations = new Array();
  17064. this._paused = false;
  17065. this.animationStarted = false;
  17066. if (animations) {
  17067. this.appendAnimations(target, animations);
  17068. }
  17069. this._scene = scene;
  17070. scene._activeAnimatables.push(this);
  17071. }
  17072. // Methods
  17073. Animatable.prototype.appendAnimations = function (target, animations) {
  17074. for (var index = 0; index < animations.length; index++) {
  17075. var animation = animations[index];
  17076. animation._target = target;
  17077. this._animations.push(animation);
  17078. }
  17079. };
  17080. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  17081. var animations = this._animations;
  17082. for (var index = 0; index < animations.length; index++) {
  17083. if (animations[index].targetProperty === property) {
  17084. return animations[index];
  17085. }
  17086. }
  17087. return null;
  17088. };
  17089. Animatable.prototype.pause = function () {
  17090. if (this._paused) {
  17091. return;
  17092. }
  17093. this._paused = true;
  17094. };
  17095. Animatable.prototype.restart = function () {
  17096. this._paused = false;
  17097. };
  17098. Animatable.prototype.stop = function () {
  17099. var index = this._scene._activeAnimatables.indexOf(this);
  17100. if (index > -1) {
  17101. this._scene._activeAnimatables.splice(index, 1);
  17102. }
  17103. if (this.onAnimationEnd) {
  17104. this.onAnimationEnd();
  17105. }
  17106. };
  17107. Animatable.prototype._animate = function (delay) {
  17108. if (this._paused) {
  17109. if (!this._pausedDelay) {
  17110. this._pausedDelay = delay;
  17111. }
  17112. return true;
  17113. }
  17114. if (!this._localDelayOffset) {
  17115. this._localDelayOffset = delay;
  17116. }
  17117. else if (this._pausedDelay) {
  17118. this._localDelayOffset += delay - this._pausedDelay;
  17119. this._pausedDelay = null;
  17120. }
  17121. // Animating
  17122. var running = false;
  17123. var animations = this._animations;
  17124. for (var index = 0; index < animations.length; index++) {
  17125. var animation = animations[index];
  17126. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  17127. running = running || isRunning;
  17128. }
  17129. if (!running) {
  17130. // Remove from active animatables
  17131. index = this._scene._activeAnimatables.indexOf(this);
  17132. this._scene._activeAnimatables.splice(index, 1);
  17133. }
  17134. if (!running && this.onAnimationEnd) {
  17135. this.onAnimationEnd();
  17136. }
  17137. return running;
  17138. };
  17139. return Animatable;
  17140. })();
  17141. BABYLON.Animatable = Animatable;
  17142. })(BABYLON || (BABYLON = {}));
  17143. //# sourceMappingURL=babylon.animatable.js.map
  17144. var BABYLON;
  17145. (function (BABYLON) {
  17146. var EasingFunction = (function () {
  17147. function EasingFunction() {
  17148. // Properties
  17149. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  17150. }
  17151. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  17152. get: function () {
  17153. return EasingFunction._EASINGMODE_EASEIN;
  17154. },
  17155. enumerable: true,
  17156. configurable: true
  17157. });
  17158. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  17159. get: function () {
  17160. return EasingFunction._EASINGMODE_EASEOUT;
  17161. },
  17162. enumerable: true,
  17163. configurable: true
  17164. });
  17165. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  17166. get: function () {
  17167. return EasingFunction._EASINGMODE_EASEINOUT;
  17168. },
  17169. enumerable: true,
  17170. configurable: true
  17171. });
  17172. EasingFunction.prototype.setEasingMode = function (easingMode) {
  17173. var n = Math.min(Math.max(easingMode, 0), 2);
  17174. this._easingMode = n;
  17175. };
  17176. EasingFunction.prototype.getEasingMode = function () {
  17177. return this._easingMode;
  17178. };
  17179. EasingFunction.prototype.easeInCore = function (gradient) {
  17180. throw new Error('You must implement this method');
  17181. };
  17182. EasingFunction.prototype.ease = function (gradient) {
  17183. switch (this._easingMode) {
  17184. case EasingFunction.EASINGMODE_EASEIN:
  17185. return this.easeInCore(gradient);
  17186. case EasingFunction.EASINGMODE_EASEOUT:
  17187. return (1 - this.easeInCore(1 - gradient));
  17188. }
  17189. if (gradient >= 0.5) {
  17190. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  17191. }
  17192. return (this.easeInCore(gradient * 2) * 0.5);
  17193. };
  17194. //Statics
  17195. EasingFunction._EASINGMODE_EASEIN = 0;
  17196. EasingFunction._EASINGMODE_EASEOUT = 1;
  17197. EasingFunction._EASINGMODE_EASEINOUT = 2;
  17198. return EasingFunction;
  17199. })();
  17200. BABYLON.EasingFunction = EasingFunction;
  17201. var CircleEase = (function (_super) {
  17202. __extends(CircleEase, _super);
  17203. function CircleEase() {
  17204. _super.apply(this, arguments);
  17205. }
  17206. CircleEase.prototype.easeInCore = function (gradient) {
  17207. gradient = Math.max(0, Math.min(1, gradient));
  17208. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  17209. };
  17210. return CircleEase;
  17211. })(EasingFunction);
  17212. BABYLON.CircleEase = CircleEase;
  17213. var BackEase = (function (_super) {
  17214. __extends(BackEase, _super);
  17215. function BackEase(amplitude) {
  17216. if (amplitude === void 0) { amplitude = 1; }
  17217. _super.call(this);
  17218. this.amplitude = amplitude;
  17219. }
  17220. BackEase.prototype.easeInCore = function (gradient) {
  17221. var num = Math.max(0, this.amplitude);
  17222. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  17223. };
  17224. return BackEase;
  17225. })(EasingFunction);
  17226. BABYLON.BackEase = BackEase;
  17227. var BounceEase = (function (_super) {
  17228. __extends(BounceEase, _super);
  17229. function BounceEase(bounces, bounciness) {
  17230. if (bounces === void 0) { bounces = 3; }
  17231. if (bounciness === void 0) { bounciness = 2; }
  17232. _super.call(this);
  17233. this.bounces = bounces;
  17234. this.bounciness = bounciness;
  17235. }
  17236. BounceEase.prototype.easeInCore = function (gradient) {
  17237. var y = Math.max(0.0, this.bounces);
  17238. var bounciness = this.bounciness;
  17239. if (bounciness <= 1.0) {
  17240. bounciness = 1.001;
  17241. }
  17242. var num9 = Math.pow(bounciness, y);
  17243. var num5 = 1.0 - bounciness;
  17244. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  17245. var num15 = gradient * num4;
  17246. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  17247. var num3 = Math.floor(num65);
  17248. var num13 = num3 + 1.0;
  17249. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  17250. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  17251. var num7 = (num8 + num12) * 0.5;
  17252. var num6 = gradient - num7;
  17253. var num2 = num7 - num8;
  17254. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  17255. };
  17256. return BounceEase;
  17257. })(EasingFunction);
  17258. BABYLON.BounceEase = BounceEase;
  17259. var CubicEase = (function (_super) {
  17260. __extends(CubicEase, _super);
  17261. function CubicEase() {
  17262. _super.apply(this, arguments);
  17263. }
  17264. CubicEase.prototype.easeInCore = function (gradient) {
  17265. return (gradient * gradient * gradient);
  17266. };
  17267. return CubicEase;
  17268. })(EasingFunction);
  17269. BABYLON.CubicEase = CubicEase;
  17270. var ElasticEase = (function (_super) {
  17271. __extends(ElasticEase, _super);
  17272. function ElasticEase(oscillations, springiness) {
  17273. if (oscillations === void 0) { oscillations = 3; }
  17274. if (springiness === void 0) { springiness = 3; }
  17275. _super.call(this);
  17276. this.oscillations = oscillations;
  17277. this.springiness = springiness;
  17278. }
  17279. ElasticEase.prototype.easeInCore = function (gradient) {
  17280. var num2;
  17281. var num3 = Math.max(0.0, this.oscillations);
  17282. var num = Math.max(0.0, this.springiness);
  17283. if (num == 0) {
  17284. num2 = gradient;
  17285. }
  17286. else {
  17287. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  17288. }
  17289. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  17290. };
  17291. return ElasticEase;
  17292. })(EasingFunction);
  17293. BABYLON.ElasticEase = ElasticEase;
  17294. var ExponentialEase = (function (_super) {
  17295. __extends(ExponentialEase, _super);
  17296. function ExponentialEase(exponent) {
  17297. if (exponent === void 0) { exponent = 2; }
  17298. _super.call(this);
  17299. this.exponent = exponent;
  17300. }
  17301. ExponentialEase.prototype.easeInCore = function (gradient) {
  17302. if (this.exponent <= 0) {
  17303. return gradient;
  17304. }
  17305. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  17306. };
  17307. return ExponentialEase;
  17308. })(EasingFunction);
  17309. BABYLON.ExponentialEase = ExponentialEase;
  17310. var PowerEase = (function (_super) {
  17311. __extends(PowerEase, _super);
  17312. function PowerEase(power) {
  17313. if (power === void 0) { power = 2; }
  17314. _super.call(this);
  17315. this.power = power;
  17316. }
  17317. PowerEase.prototype.easeInCore = function (gradient) {
  17318. var y = Math.max(0.0, this.power);
  17319. return Math.pow(gradient, y);
  17320. };
  17321. return PowerEase;
  17322. })(EasingFunction);
  17323. BABYLON.PowerEase = PowerEase;
  17324. var QuadraticEase = (function (_super) {
  17325. __extends(QuadraticEase, _super);
  17326. function QuadraticEase() {
  17327. _super.apply(this, arguments);
  17328. }
  17329. QuadraticEase.prototype.easeInCore = function (gradient) {
  17330. return (gradient * gradient);
  17331. };
  17332. return QuadraticEase;
  17333. })(EasingFunction);
  17334. BABYLON.QuadraticEase = QuadraticEase;
  17335. var QuarticEase = (function (_super) {
  17336. __extends(QuarticEase, _super);
  17337. function QuarticEase() {
  17338. _super.apply(this, arguments);
  17339. }
  17340. QuarticEase.prototype.easeInCore = function (gradient) {
  17341. return (gradient * gradient * gradient * gradient);
  17342. };
  17343. return QuarticEase;
  17344. })(EasingFunction);
  17345. BABYLON.QuarticEase = QuarticEase;
  17346. var QuinticEase = (function (_super) {
  17347. __extends(QuinticEase, _super);
  17348. function QuinticEase() {
  17349. _super.apply(this, arguments);
  17350. }
  17351. QuinticEase.prototype.easeInCore = function (gradient) {
  17352. return (gradient * gradient * gradient * gradient * gradient);
  17353. };
  17354. return QuinticEase;
  17355. })(EasingFunction);
  17356. BABYLON.QuinticEase = QuinticEase;
  17357. var SineEase = (function (_super) {
  17358. __extends(SineEase, _super);
  17359. function SineEase() {
  17360. _super.apply(this, arguments);
  17361. }
  17362. SineEase.prototype.easeInCore = function (gradient) {
  17363. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  17364. };
  17365. return SineEase;
  17366. })(EasingFunction);
  17367. BABYLON.SineEase = SineEase;
  17368. var BezierCurveEase = (function (_super) {
  17369. __extends(BezierCurveEase, _super);
  17370. function BezierCurveEase(x1, y1, x2, y2) {
  17371. if (x1 === void 0) { x1 = 0; }
  17372. if (y1 === void 0) { y1 = 0; }
  17373. if (x2 === void 0) { x2 = 1; }
  17374. if (y2 === void 0) { y2 = 1; }
  17375. _super.call(this);
  17376. this.x1 = x1;
  17377. this.y1 = y1;
  17378. this.x2 = x2;
  17379. this.y2 = y2;
  17380. }
  17381. BezierCurveEase.prototype.easeInCore = function (gradient) {
  17382. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  17383. };
  17384. return BezierCurveEase;
  17385. })(EasingFunction);
  17386. BABYLON.BezierCurveEase = BezierCurveEase;
  17387. })(BABYLON || (BABYLON = {}));
  17388. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  17389. (function (BABYLON) {
  17390. var Octree = (function () {
  17391. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  17392. if (maxDepth === void 0) { maxDepth = 2; }
  17393. this.maxDepth = maxDepth;
  17394. this.dynamicContent = new Array();
  17395. this._maxBlockCapacity = maxBlockCapacity || 64;
  17396. this._selectionContent = new BABYLON.SmartArray(1024);
  17397. this._creationFunc = creationFunc;
  17398. }
  17399. // Methods
  17400. Octree.prototype.update = function (worldMin, worldMax, entries) {
  17401. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  17402. };
  17403. Octree.prototype.addMesh = function (entry) {
  17404. for (var index = 0; index < this.blocks.length; index++) {
  17405. var block = this.blocks[index];
  17406. block.addEntry(entry);
  17407. }
  17408. };
  17409. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  17410. this._selectionContent.reset();
  17411. for (var index = 0; index < this.blocks.length; index++) {
  17412. var block = this.blocks[index];
  17413. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  17414. }
  17415. if (allowDuplicate) {
  17416. this._selectionContent.concat(this.dynamicContent);
  17417. }
  17418. else {
  17419. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17420. }
  17421. return this._selectionContent;
  17422. };
  17423. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  17424. this._selectionContent.reset();
  17425. for (var index = 0; index < this.blocks.length; index++) {
  17426. var block = this.blocks[index];
  17427. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  17428. }
  17429. if (allowDuplicate) {
  17430. this._selectionContent.concat(this.dynamicContent);
  17431. }
  17432. else {
  17433. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17434. }
  17435. return this._selectionContent;
  17436. };
  17437. Octree.prototype.intersectsRay = function (ray) {
  17438. this._selectionContent.reset();
  17439. for (var index = 0; index < this.blocks.length; index++) {
  17440. var block = this.blocks[index];
  17441. block.intersectsRay(ray, this._selectionContent);
  17442. }
  17443. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17444. return this._selectionContent;
  17445. };
  17446. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  17447. target.blocks = new Array();
  17448. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  17449. for (var x = 0; x < 2; x++) {
  17450. for (var y = 0; y < 2; y++) {
  17451. for (var z = 0; z < 2; z++) {
  17452. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  17453. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  17454. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  17455. block.addEntries(entries);
  17456. target.blocks.push(block);
  17457. }
  17458. }
  17459. }
  17460. };
  17461. Octree.CreationFuncForMeshes = function (entry, block) {
  17462. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17463. block.entries.push(entry);
  17464. }
  17465. };
  17466. Octree.CreationFuncForSubMeshes = function (entry, block) {
  17467. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17468. block.entries.push(entry);
  17469. }
  17470. };
  17471. return Octree;
  17472. })();
  17473. BABYLON.Octree = Octree;
  17474. })(BABYLON || (BABYLON = {}));
  17475. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  17476. (function (BABYLON) {
  17477. var OctreeBlock = (function () {
  17478. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  17479. this.entries = new Array();
  17480. this._boundingVectors = new Array();
  17481. this._capacity = capacity;
  17482. this._depth = depth;
  17483. this._maxDepth = maxDepth;
  17484. this._creationFunc = creationFunc;
  17485. this._minPoint = minPoint;
  17486. this._maxPoint = maxPoint;
  17487. this._boundingVectors.push(minPoint.clone());
  17488. this._boundingVectors.push(maxPoint.clone());
  17489. this._boundingVectors.push(minPoint.clone());
  17490. this._boundingVectors[2].x = maxPoint.x;
  17491. this._boundingVectors.push(minPoint.clone());
  17492. this._boundingVectors[3].y = maxPoint.y;
  17493. this._boundingVectors.push(minPoint.clone());
  17494. this._boundingVectors[4].z = maxPoint.z;
  17495. this._boundingVectors.push(maxPoint.clone());
  17496. this._boundingVectors[5].z = minPoint.z;
  17497. this._boundingVectors.push(maxPoint.clone());
  17498. this._boundingVectors[6].x = minPoint.x;
  17499. this._boundingVectors.push(maxPoint.clone());
  17500. this._boundingVectors[7].y = minPoint.y;
  17501. }
  17502. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  17503. // Property
  17504. get: function () {
  17505. return this._capacity;
  17506. },
  17507. enumerable: true,
  17508. configurable: true
  17509. });
  17510. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  17511. get: function () {
  17512. return this._minPoint;
  17513. },
  17514. enumerable: true,
  17515. configurable: true
  17516. });
  17517. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  17518. get: function () {
  17519. return this._maxPoint;
  17520. },
  17521. enumerable: true,
  17522. configurable: true
  17523. });
  17524. // Methods
  17525. OctreeBlock.prototype.addEntry = function (entry) {
  17526. if (this.blocks) {
  17527. for (var index = 0; index < this.blocks.length; index++) {
  17528. var block = this.blocks[index];
  17529. block.addEntry(entry);
  17530. }
  17531. return;
  17532. }
  17533. this._creationFunc(entry, this);
  17534. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  17535. this.createInnerBlocks();
  17536. }
  17537. };
  17538. OctreeBlock.prototype.addEntries = function (entries) {
  17539. for (var index = 0; index < entries.length; index++) {
  17540. var mesh = entries[index];
  17541. this.addEntry(mesh);
  17542. }
  17543. };
  17544. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  17545. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  17546. if (this.blocks) {
  17547. for (var index = 0; index < this.blocks.length; index++) {
  17548. var block = this.blocks[index];
  17549. block.select(frustumPlanes, selection, allowDuplicate);
  17550. }
  17551. return;
  17552. }
  17553. if (allowDuplicate) {
  17554. selection.concat(this.entries);
  17555. }
  17556. else {
  17557. selection.concatWithNoDuplicate(this.entries);
  17558. }
  17559. }
  17560. };
  17561. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  17562. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  17563. if (this.blocks) {
  17564. for (var index = 0; index < this.blocks.length; index++) {
  17565. var block = this.blocks[index];
  17566. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  17567. }
  17568. return;
  17569. }
  17570. if (allowDuplicate) {
  17571. selection.concat(this.entries);
  17572. }
  17573. else {
  17574. selection.concatWithNoDuplicate(this.entries);
  17575. }
  17576. }
  17577. };
  17578. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  17579. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  17580. if (this.blocks) {
  17581. for (var index = 0; index < this.blocks.length; index++) {
  17582. var block = this.blocks[index];
  17583. block.intersectsRay(ray, selection);
  17584. }
  17585. return;
  17586. }
  17587. selection.concatWithNoDuplicate(this.entries);
  17588. }
  17589. };
  17590. OctreeBlock.prototype.createInnerBlocks = function () {
  17591. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  17592. };
  17593. return OctreeBlock;
  17594. })();
  17595. BABYLON.OctreeBlock = OctreeBlock;
  17596. })(BABYLON || (BABYLON = {}));
  17597. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  17598. (function (BABYLON) {
  17599. var Bone = (function () {
  17600. function Bone(name, skeleton, parentBone, matrix) {
  17601. this.name = name;
  17602. this.children = new Array();
  17603. this.animations = new Array();
  17604. this._worldTransform = new BABYLON.Matrix();
  17605. this._absoluteTransform = new BABYLON.Matrix();
  17606. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  17607. this._skeleton = skeleton;
  17608. this._matrix = matrix;
  17609. this._baseMatrix = matrix;
  17610. skeleton.bones.push(this);
  17611. if (parentBone) {
  17612. this._parent = parentBone;
  17613. parentBone.children.push(this);
  17614. }
  17615. else {
  17616. this._parent = null;
  17617. }
  17618. this._updateDifferenceMatrix();
  17619. }
  17620. // Members
  17621. Bone.prototype.getParent = function () {
  17622. return this._parent;
  17623. };
  17624. Bone.prototype.getLocalMatrix = function () {
  17625. return this._matrix;
  17626. };
  17627. Bone.prototype.getBaseMatrix = function () {
  17628. return this._baseMatrix;
  17629. };
  17630. Bone.prototype.getWorldMatrix = function () {
  17631. return this._worldTransform;
  17632. };
  17633. Bone.prototype.getInvertedAbsoluteTransform = function () {
  17634. return this._invertedAbsoluteTransform;
  17635. };
  17636. Bone.prototype.getAbsoluteMatrix = function () {
  17637. var matrix = this._matrix.clone();
  17638. var parent = this._parent;
  17639. while (parent) {
  17640. matrix = matrix.multiply(parent.getLocalMatrix());
  17641. parent = parent.getParent();
  17642. }
  17643. return matrix;
  17644. };
  17645. // Methods
  17646. Bone.prototype.updateMatrix = function (matrix) {
  17647. this._matrix = matrix;
  17648. this._skeleton._markAsDirty();
  17649. this._updateDifferenceMatrix();
  17650. };
  17651. Bone.prototype._updateDifferenceMatrix = function () {
  17652. if (this._parent) {
  17653. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  17654. }
  17655. else {
  17656. this._absoluteTransform.copyFrom(this._matrix);
  17657. }
  17658. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  17659. for (var index = 0; index < this.children.length; index++) {
  17660. this.children[index]._updateDifferenceMatrix();
  17661. }
  17662. };
  17663. Bone.prototype.markAsDirty = function () {
  17664. this._skeleton._markAsDirty();
  17665. };
  17666. return Bone;
  17667. })();
  17668. BABYLON.Bone = Bone;
  17669. })(BABYLON || (BABYLON = {}));
  17670. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  17671. (function (BABYLON) {
  17672. var Skeleton = (function () {
  17673. function Skeleton(name, id, scene) {
  17674. this.name = name;
  17675. this.id = id;
  17676. this.bones = new Array();
  17677. this._isDirty = true;
  17678. this._identity = BABYLON.Matrix.Identity();
  17679. this.bones = [];
  17680. this._scene = scene;
  17681. scene.skeletons.push(this);
  17682. this.prepare();
  17683. //make sure it will recalculate the matrix next time prepare is called.
  17684. this._isDirty = true;
  17685. }
  17686. // Members
  17687. Skeleton.prototype.getTransformMatrices = function () {
  17688. return this._transformMatrices;
  17689. };
  17690. // Methods
  17691. Skeleton.prototype._markAsDirty = function () {
  17692. this._isDirty = true;
  17693. };
  17694. Skeleton.prototype.prepare = function () {
  17695. if (!this._isDirty) {
  17696. return;
  17697. }
  17698. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  17699. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  17700. }
  17701. for (var index = 0; index < this.bones.length; index++) {
  17702. var bone = this.bones[index];
  17703. var parentBone = bone.getParent();
  17704. if (parentBone) {
  17705. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  17706. }
  17707. else {
  17708. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  17709. }
  17710. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  17711. }
  17712. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  17713. this._isDirty = false;
  17714. this._scene._activeBones += this.bones.length;
  17715. };
  17716. Skeleton.prototype.getAnimatables = function () {
  17717. if (!this._animatables || this._animatables.length !== this.bones.length) {
  17718. this._animatables = [];
  17719. for (var index = 0; index < this.bones.length; index++) {
  17720. this._animatables.push(this.bones[index]);
  17721. }
  17722. }
  17723. return this._animatables;
  17724. };
  17725. Skeleton.prototype.clone = function (name, id) {
  17726. var result = new Skeleton(name, id || name, this._scene);
  17727. for (var index = 0; index < this.bones.length; index++) {
  17728. var source = this.bones[index];
  17729. var parentBone = null;
  17730. if (source.getParent()) {
  17731. var parentIndex = this.bones.indexOf(source.getParent());
  17732. parentBone = result.bones[parentIndex];
  17733. }
  17734. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  17735. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  17736. }
  17737. return result;
  17738. };
  17739. return Skeleton;
  17740. })();
  17741. BABYLON.Skeleton = Skeleton;
  17742. })(BABYLON || (BABYLON = {}));
  17743. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  17744. (function (BABYLON) {
  17745. var PostProcess = (function () {
  17746. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  17747. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  17748. this.name = name;
  17749. this.width = -1;
  17750. this.height = -1;
  17751. this._reusable = false;
  17752. this._textures = new BABYLON.SmartArray(2);
  17753. this._currentRenderTextureInd = 0;
  17754. if (camera != null) {
  17755. this._camera = camera;
  17756. this._scene = camera.getScene();
  17757. camera.attachPostProcess(this);
  17758. this._engine = this._scene.getEngine();
  17759. }
  17760. else {
  17761. this._engine = engine;
  17762. }
  17763. this._renderRatio = ratio;
  17764. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  17765. this._reusable = reusable || false;
  17766. samplers = samplers || [];
  17767. samplers.push("textureSampler");
  17768. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  17769. }
  17770. PostProcess.prototype.isReusable = function () {
  17771. return this._reusable;
  17772. };
  17773. PostProcess.prototype.activate = function (camera, sourceTexture) {
  17774. camera = camera || this._camera;
  17775. var scene = camera.getScene();
  17776. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  17777. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  17778. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  17779. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  17780. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  17781. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  17782. if (this._textures.length > 0) {
  17783. for (var i = 0; i < this._textures.length; i++) {
  17784. this._engine._releaseTexture(this._textures.data[i]);
  17785. }
  17786. this._textures.reset();
  17787. }
  17788. this.width = desiredWidth;
  17789. this.height = desiredHeight;
  17790. 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 }));
  17791. if (this._reusable) {
  17792. 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 }));
  17793. }
  17794. if (this.onSizeChanged) {
  17795. this.onSizeChanged();
  17796. }
  17797. }
  17798. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  17799. if (this.onActivate) {
  17800. this.onActivate(camera);
  17801. }
  17802. // Clear
  17803. if (this.clearColor) {
  17804. this._engine.clear(this.clearColor, true, true);
  17805. }
  17806. else {
  17807. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  17808. }
  17809. if (this._reusable) {
  17810. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  17811. }
  17812. };
  17813. PostProcess.prototype.apply = function () {
  17814. // Check
  17815. if (!this._effect.isReady())
  17816. return null;
  17817. // States
  17818. this._engine.enableEffect(this._effect);
  17819. this._engine.setState(false);
  17820. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17821. this._engine.setDepthBuffer(false);
  17822. this._engine.setDepthWrite(false);
  17823. // Texture
  17824. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  17825. // Parameters
  17826. if (this.onApply) {
  17827. this.onApply(this._effect);
  17828. }
  17829. return this._effect;
  17830. };
  17831. PostProcess.prototype.dispose = function (camera) {
  17832. camera = camera || this._camera;
  17833. if (this._textures.length > 0) {
  17834. for (var i = 0; i < this._textures.length; i++) {
  17835. this._engine._releaseTexture(this._textures.data[i]);
  17836. }
  17837. this._textures.reset();
  17838. }
  17839. if (!camera) {
  17840. return;
  17841. }
  17842. camera.detachPostProcess(this);
  17843. var index = camera._postProcesses.indexOf(this);
  17844. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  17845. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  17846. }
  17847. };
  17848. return PostProcess;
  17849. })();
  17850. BABYLON.PostProcess = PostProcess;
  17851. })(BABYLON || (BABYLON = {}));
  17852. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  17853. (function (BABYLON) {
  17854. var PostProcessManager = (function () {
  17855. function PostProcessManager(scene) {
  17856. this._vertexDeclaration = [2];
  17857. this._vertexStrideSize = 2 * 4;
  17858. this._scene = scene;
  17859. }
  17860. PostProcessManager.prototype._prepareBuffers = function () {
  17861. if (this._vertexBuffer) {
  17862. return;
  17863. }
  17864. // VBO
  17865. var vertices = [];
  17866. vertices.push(1, 1);
  17867. vertices.push(-1, 1);
  17868. vertices.push(-1, -1);
  17869. vertices.push(1, -1);
  17870. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  17871. // Indices
  17872. var indices = [];
  17873. indices.push(0);
  17874. indices.push(1);
  17875. indices.push(2);
  17876. indices.push(0);
  17877. indices.push(2);
  17878. indices.push(3);
  17879. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  17880. };
  17881. // Methods
  17882. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  17883. var postProcesses = this._scene.activeCamera._postProcesses;
  17884. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17885. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17886. return false;
  17887. }
  17888. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  17889. return true;
  17890. };
  17891. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  17892. var engine = this._scene.getEngine();
  17893. for (var index = 0; index < postProcesses.length; index++) {
  17894. if (index < postProcesses.length - 1) {
  17895. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  17896. }
  17897. else {
  17898. if (targetTexture) {
  17899. engine.bindFramebuffer(targetTexture);
  17900. }
  17901. else {
  17902. engine.restoreDefaultFramebuffer();
  17903. }
  17904. }
  17905. var pp = postProcesses[index];
  17906. var effect = pp.apply();
  17907. if (effect) {
  17908. if (pp.onBeforeRender) {
  17909. pp.onBeforeRender(effect);
  17910. }
  17911. // VBOs
  17912. this._prepareBuffers();
  17913. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17914. // Draw order
  17915. engine.draw(true, 0, 6);
  17916. }
  17917. }
  17918. // Restore depth buffer
  17919. engine.setDepthBuffer(true);
  17920. engine.setDepthWrite(true);
  17921. };
  17922. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  17923. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  17924. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17925. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17926. return;
  17927. }
  17928. var engine = this._scene.getEngine();
  17929. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17930. if (index < postProcessesTakenIndices.length - 1) {
  17931. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17932. }
  17933. else {
  17934. if (targetTexture) {
  17935. engine.bindFramebuffer(targetTexture);
  17936. }
  17937. else {
  17938. engine.restoreDefaultFramebuffer();
  17939. }
  17940. }
  17941. if (doNotPresent) {
  17942. break;
  17943. }
  17944. var pp = postProcesses[postProcessesTakenIndices[index]];
  17945. var effect = pp.apply();
  17946. if (effect) {
  17947. if (pp.onBeforeRender) {
  17948. pp.onBeforeRender(effect);
  17949. }
  17950. // VBOs
  17951. this._prepareBuffers();
  17952. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17953. // Draw order
  17954. engine.draw(true, 0, 6);
  17955. }
  17956. }
  17957. // Restore depth buffer
  17958. engine.setDepthBuffer(true);
  17959. engine.setDepthWrite(true);
  17960. };
  17961. PostProcessManager.prototype.dispose = function () {
  17962. if (this._vertexBuffer) {
  17963. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17964. this._vertexBuffer = null;
  17965. }
  17966. if (this._indexBuffer) {
  17967. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17968. this._indexBuffer = null;
  17969. }
  17970. };
  17971. return PostProcessManager;
  17972. })();
  17973. BABYLON.PostProcessManager = PostProcessManager;
  17974. })(BABYLON || (BABYLON = {}));
  17975. //# sourceMappingURL=babylon.postProcessManager.js.map
  17976. var BABYLON;
  17977. (function (BABYLON) {
  17978. var PassPostProcess = (function (_super) {
  17979. __extends(PassPostProcess, _super);
  17980. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17981. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17982. }
  17983. return PassPostProcess;
  17984. })(BABYLON.PostProcess);
  17985. BABYLON.PassPostProcess = PassPostProcess;
  17986. })(BABYLON || (BABYLON = {}));
  17987. //# sourceMappingURL=babylon.passPostProcess.js.map
  17988. var BABYLON;
  17989. (function (BABYLON) {
  17990. var BlurPostProcess = (function (_super) {
  17991. __extends(BlurPostProcess, _super);
  17992. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17993. var _this = this;
  17994. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17995. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17996. this.direction = direction;
  17997. this.blurWidth = blurWidth;
  17998. this.onApply = function (effect) {
  17999. effect.setFloat2("screenSize", _this.width, _this.height);
  18000. effect.setVector2("direction", _this.direction);
  18001. effect.setFloat("blurWidth", _this.blurWidth);
  18002. };
  18003. }
  18004. return BlurPostProcess;
  18005. })(BABYLON.PostProcess);
  18006. BABYLON.BlurPostProcess = BlurPostProcess;
  18007. })(BABYLON || (BABYLON = {}));
  18008. //# sourceMappingURL=babylon.blurPostProcess.js.map
  18009. var BABYLON;
  18010. (function (BABYLON) {
  18011. var FilterPostProcess = (function (_super) {
  18012. __extends(FilterPostProcess, _super);
  18013. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  18014. var _this = this;
  18015. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  18016. this.kernelMatrix = kernelMatrix;
  18017. this.onApply = function (effect) {
  18018. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  18019. };
  18020. }
  18021. return FilterPostProcess;
  18022. })(BABYLON.PostProcess);
  18023. BABYLON.FilterPostProcess = FilterPostProcess;
  18024. })(BABYLON || (BABYLON = {}));
  18025. //# sourceMappingURL=babylon.filterPostProcess.js.map
  18026. var BABYLON;
  18027. (function (BABYLON) {
  18028. var RefractionPostProcess = (function (_super) {
  18029. __extends(RefractionPostProcess, _super);
  18030. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  18031. var _this = this;
  18032. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  18033. this.color = color;
  18034. this.depth = depth;
  18035. this.colorLevel = colorLevel;
  18036. this.onActivate = function (cam) {
  18037. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  18038. };
  18039. this.onApply = function (effect) {
  18040. effect.setColor3("baseColor", _this.color);
  18041. effect.setFloat("depth", _this.depth);
  18042. effect.setFloat("colorLevel", _this.colorLevel);
  18043. effect.setTexture("refractionSampler", _this._refRexture);
  18044. };
  18045. }
  18046. // Methods
  18047. RefractionPostProcess.prototype.dispose = function (camera) {
  18048. if (this._refRexture) {
  18049. this._refRexture.dispose();
  18050. }
  18051. _super.prototype.dispose.call(this, camera);
  18052. };
  18053. return RefractionPostProcess;
  18054. })(BABYLON.PostProcess);
  18055. BABYLON.RefractionPostProcess = RefractionPostProcess;
  18056. })(BABYLON || (BABYLON = {}));
  18057. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  18058. var BABYLON;
  18059. (function (BABYLON) {
  18060. var BlackAndWhitePostProcess = (function (_super) {
  18061. __extends(BlackAndWhitePostProcess, _super);
  18062. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18063. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  18064. }
  18065. return BlackAndWhitePostProcess;
  18066. })(BABYLON.PostProcess);
  18067. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  18068. })(BABYLON || (BABYLON = {}));
  18069. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  18070. var BABYLON;
  18071. (function (BABYLON) {
  18072. var ConvolutionPostProcess = (function (_super) {
  18073. __extends(ConvolutionPostProcess, _super);
  18074. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  18075. var _this = this;
  18076. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  18077. this.kernel = kernel;
  18078. this.onApply = function (effect) {
  18079. effect.setFloat2("screenSize", _this.width, _this.height);
  18080. effect.setArray("kernel", _this.kernel);
  18081. };
  18082. }
  18083. // Statics
  18084. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  18085. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  18086. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  18087. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  18088. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  18089. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  18090. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  18091. return ConvolutionPostProcess;
  18092. })(BABYLON.PostProcess);
  18093. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  18094. })(BABYLON || (BABYLON = {}));
  18095. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  18096. var BABYLON;
  18097. (function (BABYLON) {
  18098. var FxaaPostProcess = (function (_super) {
  18099. __extends(FxaaPostProcess, _super);
  18100. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18101. var _this = this;
  18102. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  18103. this.onSizeChanged = function () {
  18104. _this.texelWidth = 1.0 / _this.width;
  18105. _this.texelHeight = 1.0 / _this.height;
  18106. };
  18107. this.onApply = function (effect) {
  18108. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  18109. };
  18110. }
  18111. return FxaaPostProcess;
  18112. })(BABYLON.PostProcess);
  18113. BABYLON.FxaaPostProcess = FxaaPostProcess;
  18114. })(BABYLON || (BABYLON = {}));
  18115. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  18116. (function (BABYLON) {
  18117. var LensFlare = (function () {
  18118. function LensFlare(size, position, color, imgUrl, system) {
  18119. this.size = size;
  18120. this.position = position;
  18121. this.dispose = function () {
  18122. if (this.texture) {
  18123. this.texture.dispose();
  18124. }
  18125. // Remove from scene
  18126. var index = this._system.lensFlares.indexOf(this);
  18127. this._system.lensFlares.splice(index, 1);
  18128. };
  18129. this.color = color || new BABYLON.Color3(1, 1, 1);
  18130. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  18131. this._system = system;
  18132. system.lensFlares.push(this);
  18133. }
  18134. return LensFlare;
  18135. })();
  18136. BABYLON.LensFlare = LensFlare;
  18137. })(BABYLON || (BABYLON = {}));
  18138. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  18139. (function (BABYLON) {
  18140. var LensFlareSystem = (function () {
  18141. function LensFlareSystem(name, emitter, scene) {
  18142. this.name = name;
  18143. this.lensFlares = new Array();
  18144. this.borderLimit = 300;
  18145. this._vertexDeclaration = [2];
  18146. this._vertexStrideSize = 2 * 4;
  18147. this._isEnabled = true;
  18148. this._scene = scene;
  18149. this._emitter = emitter;
  18150. scene.lensFlareSystems.push(this);
  18151. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  18152. // VBO
  18153. var vertices = [];
  18154. vertices.push(1, 1);
  18155. vertices.push(-1, 1);
  18156. vertices.push(-1, -1);
  18157. vertices.push(1, -1);
  18158. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18159. // Indices
  18160. var indices = [];
  18161. indices.push(0);
  18162. indices.push(1);
  18163. indices.push(2);
  18164. indices.push(0);
  18165. indices.push(2);
  18166. indices.push(3);
  18167. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18168. // Effects
  18169. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  18170. }
  18171. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  18172. get: function () {
  18173. return this._isEnabled;
  18174. },
  18175. set: function (value) {
  18176. this._isEnabled = value;
  18177. },
  18178. enumerable: true,
  18179. configurable: true
  18180. });
  18181. LensFlareSystem.prototype.getScene = function () {
  18182. return this._scene;
  18183. };
  18184. LensFlareSystem.prototype.getEmitter = function () {
  18185. return this._emitter;
  18186. };
  18187. LensFlareSystem.prototype.getEmitterPosition = function () {
  18188. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  18189. };
  18190. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  18191. var position = this.getEmitterPosition();
  18192. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  18193. this._positionX = position.x;
  18194. this._positionY = position.y;
  18195. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  18196. if (position.z > 0) {
  18197. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  18198. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  18199. return true;
  18200. }
  18201. }
  18202. return false;
  18203. };
  18204. LensFlareSystem.prototype._isVisible = function () {
  18205. if (!this._isEnabled) {
  18206. return false;
  18207. }
  18208. var emitterPosition = this.getEmitterPosition();
  18209. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  18210. var distance = direction.length();
  18211. direction.normalize();
  18212. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  18213. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  18214. return !pickInfo.hit || pickInfo.distance > distance;
  18215. };
  18216. LensFlareSystem.prototype.render = function () {
  18217. if (!this._effect.isReady())
  18218. return false;
  18219. var engine = this._scene.getEngine();
  18220. var viewport = this._scene.activeCamera.viewport;
  18221. var globalViewport = viewport.toGlobal(engine);
  18222. // Position
  18223. if (!this.computeEffectivePosition(globalViewport)) {
  18224. return false;
  18225. }
  18226. // Visibility
  18227. if (!this._isVisible()) {
  18228. return false;
  18229. }
  18230. // Intensity
  18231. var awayX;
  18232. var awayY;
  18233. if (this._positionX < this.borderLimit + globalViewport.x) {
  18234. awayX = this.borderLimit + globalViewport.x - this._positionX;
  18235. }
  18236. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  18237. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  18238. }
  18239. else {
  18240. awayX = 0;
  18241. }
  18242. if (this._positionY < this.borderLimit + globalViewport.y) {
  18243. awayY = this.borderLimit + globalViewport.y - this._positionY;
  18244. }
  18245. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  18246. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  18247. }
  18248. else {
  18249. awayY = 0;
  18250. }
  18251. var away = (awayX > awayY) ? awayX : awayY;
  18252. if (away > this.borderLimit) {
  18253. away = this.borderLimit;
  18254. }
  18255. var intensity = 1.0 - (away / this.borderLimit);
  18256. if (intensity < 0) {
  18257. return false;
  18258. }
  18259. if (intensity > 1.0) {
  18260. intensity = 1.0;
  18261. }
  18262. // Position
  18263. var centerX = globalViewport.x + globalViewport.width / 2;
  18264. var centerY = globalViewport.y + globalViewport.height / 2;
  18265. var distX = centerX - this._positionX;
  18266. var distY = centerY - this._positionY;
  18267. // Effects
  18268. engine.enableEffect(this._effect);
  18269. engine.setState(false);
  18270. engine.setDepthBuffer(false);
  18271. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  18272. // VBOs
  18273. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18274. for (var index = 0; index < this.lensFlares.length; index++) {
  18275. var flare = this.lensFlares[index];
  18276. var x = centerX - (distX * flare.position);
  18277. var y = centerY - (distY * flare.position);
  18278. var cw = flare.size;
  18279. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  18280. var cx = 2 * (x / globalViewport.width) - 1.0;
  18281. var cy = 1.0 - 2 * (y / globalViewport.height);
  18282. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  18283. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  18284. // Texture
  18285. this._effect.setTexture("textureSampler", flare.texture);
  18286. // Color
  18287. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  18288. // Draw order
  18289. engine.draw(true, 0, 6);
  18290. }
  18291. engine.setDepthBuffer(true);
  18292. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18293. return true;
  18294. };
  18295. LensFlareSystem.prototype.dispose = function () {
  18296. if (this._vertexBuffer) {
  18297. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  18298. this._vertexBuffer = null;
  18299. }
  18300. if (this._indexBuffer) {
  18301. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  18302. this._indexBuffer = null;
  18303. }
  18304. while (this.lensFlares.length) {
  18305. this.lensFlares[0].dispose();
  18306. }
  18307. // Remove from scene
  18308. var index = this._scene.lensFlareSystems.indexOf(this);
  18309. this._scene.lensFlareSystems.splice(index, 1);
  18310. };
  18311. return LensFlareSystem;
  18312. })();
  18313. BABYLON.LensFlareSystem = LensFlareSystem;
  18314. })(BABYLON || (BABYLON = {}));
  18315. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  18316. (function (BABYLON) {
  18317. var IntersectionInfo = (function () {
  18318. function IntersectionInfo(bu, bv, distance) {
  18319. this.bu = bu;
  18320. this.bv = bv;
  18321. this.distance = distance;
  18322. this.faceId = 0;
  18323. this.subMeshId = 0;
  18324. }
  18325. return IntersectionInfo;
  18326. })();
  18327. BABYLON.IntersectionInfo = IntersectionInfo;
  18328. var PickingInfo = (function () {
  18329. function PickingInfo() {
  18330. this.hit = false;
  18331. this.distance = 0;
  18332. this.pickedPoint = null;
  18333. this.pickedMesh = null;
  18334. this.bu = 0;
  18335. this.bv = 0;
  18336. this.faceId = -1;
  18337. this.subMeshId = 0;
  18338. }
  18339. // Methods
  18340. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  18341. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  18342. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18343. return null;
  18344. }
  18345. var indices = this.pickedMesh.getIndices();
  18346. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18347. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  18348. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  18349. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  18350. normal0 = normal0.scale(this.bu);
  18351. normal1 = normal1.scale(this.bv);
  18352. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  18353. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  18354. if (useWorldCoordinates) {
  18355. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  18356. }
  18357. return result;
  18358. };
  18359. PickingInfo.prototype.getTextureCoordinates = function () {
  18360. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18361. return null;
  18362. }
  18363. var indices = this.pickedMesh.getIndices();
  18364. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18365. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  18366. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  18367. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  18368. uv0 = uv0.scale(this.bu);
  18369. uv1 = uv1.scale(this.bv);
  18370. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  18371. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  18372. };
  18373. return PickingInfo;
  18374. })();
  18375. BABYLON.PickingInfo = PickingInfo;
  18376. })(BABYLON || (BABYLON = {}));
  18377. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  18378. (function (BABYLON) {
  18379. var FilesInput = (function () {
  18380. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  18381. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  18382. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  18383. this._engine = p_engine;
  18384. this._canvas = p_canvas;
  18385. this._currentScene = p_scene;
  18386. this._sceneLoadedCallback = p_sceneLoadedCallback;
  18387. this._progressCallback = p_progressCallback;
  18388. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  18389. this._textureLoadingCallback = p_textureLoadingCallback;
  18390. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  18391. }
  18392. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  18393. var _this = this;
  18394. if (p_elementToMonitor) {
  18395. this._elementToMonitor = p_elementToMonitor;
  18396. this._elementToMonitor.addEventListener("dragenter", function (e) {
  18397. _this.drag(e);
  18398. }, false);
  18399. this._elementToMonitor.addEventListener("dragover", function (e) {
  18400. _this.drag(e);
  18401. }, false);
  18402. this._elementToMonitor.addEventListener("drop", function (e) {
  18403. _this.drop(e);
  18404. }, false);
  18405. }
  18406. };
  18407. FilesInput.prototype.renderFunction = function () {
  18408. if (this._additionnalRenderLoopLogicCallback) {
  18409. this._additionnalRenderLoopLogicCallback();
  18410. }
  18411. if (this._currentScene) {
  18412. if (this._textureLoadingCallback) {
  18413. var remaining = this._currentScene.getWaitingItemsCount();
  18414. if (remaining > 0) {
  18415. this._textureLoadingCallback(remaining);
  18416. }
  18417. }
  18418. this._currentScene.render();
  18419. }
  18420. };
  18421. FilesInput.prototype.drag = function (e) {
  18422. e.stopPropagation();
  18423. e.preventDefault();
  18424. };
  18425. FilesInput.prototype.drop = function (eventDrop) {
  18426. eventDrop.stopPropagation();
  18427. eventDrop.preventDefault();
  18428. this.loadFiles(eventDrop);
  18429. };
  18430. FilesInput.prototype.loadFiles = function (event) {
  18431. if (this._startingProcessingFilesCallback)
  18432. this._startingProcessingFilesCallback();
  18433. // Handling data transfer via drag'n'drop
  18434. if (event && event.dataTransfer && event.dataTransfer.files) {
  18435. this._filesToLoad = event.dataTransfer.files;
  18436. }
  18437. // Handling files from input files
  18438. if (event && event.target && event.target.files) {
  18439. this._filesToLoad = event.target.files;
  18440. }
  18441. if (this._filesToLoad && this._filesToLoad.length > 0) {
  18442. for (var i = 0; i < this._filesToLoad.length; i++) {
  18443. switch (this._filesToLoad[i].type) {
  18444. case "image/jpeg":
  18445. case "image/png":
  18446. case "image/bmp":
  18447. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  18448. break;
  18449. case "image/targa":
  18450. case "image/vnd.ms-dds":
  18451. case "audio/wav":
  18452. case "audio/x-wav":
  18453. case "audio/mp3":
  18454. case "audio/mpeg":
  18455. case "audio/mpeg3":
  18456. case "audio/x-mpeg-3":
  18457. case "audio/ogg":
  18458. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  18459. break;
  18460. default:
  18461. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1 && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  18462. this._sceneFileToLoad = this._filesToLoad[i];
  18463. }
  18464. break;
  18465. }
  18466. }
  18467. this.reload();
  18468. }
  18469. };
  18470. FilesInput.prototype.reload = function () {
  18471. var _this = this;
  18472. var that = this;
  18473. // If a ".babylon" file has been provided
  18474. if (this._sceneFileToLoad) {
  18475. if (this._currentScene) {
  18476. this._engine.stopRenderLoop();
  18477. this._currentScene.dispose();
  18478. }
  18479. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  18480. that._currentScene = newScene;
  18481. // Wait for textures and shaders to be ready
  18482. that._currentScene.executeWhenReady(function () {
  18483. // Attach camera to canvas inputs
  18484. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  18485. that._currentScene.createDefaultCameraOrLight();
  18486. }
  18487. that._currentScene.activeCamera.attachControl(that._canvas);
  18488. if (that._sceneLoadedCallback) {
  18489. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  18490. }
  18491. that._engine.runRenderLoop(function () {
  18492. that.renderFunction();
  18493. });
  18494. });
  18495. }, function (progress) {
  18496. if (_this._progressCallback) {
  18497. _this._progressCallback(progress);
  18498. }
  18499. });
  18500. }
  18501. else {
  18502. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  18503. }
  18504. };
  18505. FilesInput.FilesTextures = new Array();
  18506. FilesInput.FilesToLoad = new Array();
  18507. return FilesInput;
  18508. })();
  18509. BABYLON.FilesInput = FilesInput;
  18510. })(BABYLON || (BABYLON = {}));
  18511. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  18512. (function (BABYLON) {
  18513. var OimoJSPlugin = (function () {
  18514. function OimoJSPlugin() {
  18515. this._registeredMeshes = [];
  18516. /**
  18517. * Update the body position according to the mesh position
  18518. * @param mesh
  18519. */
  18520. this.updateBodyPosition = function (mesh) {
  18521. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18522. var registeredMesh = this._registeredMeshes[index];
  18523. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18524. var body = registeredMesh.body.body;
  18525. mesh.computeWorldMatrix(true);
  18526. var center = mesh.getBoundingInfo().boundingBox.center;
  18527. body.setPosition(center.x, center.y, center.z);
  18528. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  18529. return;
  18530. }
  18531. // Case where the parent has been updated
  18532. if (registeredMesh.mesh.parent === mesh) {
  18533. mesh.computeWorldMatrix(true);
  18534. registeredMesh.mesh.computeWorldMatrix(true);
  18535. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  18536. var absoluteRotation = mesh.rotation;
  18537. body = registeredMesh.body.body;
  18538. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  18539. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  18540. return;
  18541. }
  18542. }
  18543. };
  18544. }
  18545. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  18546. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  18547. };
  18548. OimoJSPlugin.prototype.initialize = function (iterations) {
  18549. this._world = new OIMO.World();
  18550. this._world.clear();
  18551. };
  18552. OimoJSPlugin.prototype.setGravity = function (gravity) {
  18553. this._world.gravity = gravity;
  18554. };
  18555. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18556. var body = null;
  18557. this.unregisterMesh(mesh);
  18558. mesh.computeWorldMatrix(true);
  18559. var initialRotation = null;
  18560. if (mesh.rotationQuaternion) {
  18561. initialRotation = mesh.rotationQuaternion.clone();
  18562. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18563. mesh.computeWorldMatrix(true);
  18564. }
  18565. var bbox = mesh.getBoundingInfo().boundingBox;
  18566. // The delta between the mesh position and the mesh bounding box center
  18567. var deltaPosition = mesh.position.subtract(bbox.center);
  18568. // Transform delta position with the rotation
  18569. if (initialRotation) {
  18570. var m = new BABYLON.Matrix();
  18571. initialRotation.toRotationMatrix(m);
  18572. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  18573. }
  18574. switch (impostor) {
  18575. case BABYLON.PhysicsEngine.SphereImpostor:
  18576. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18577. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18578. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18579. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18580. body = new OIMO.Body({
  18581. type: 'sphere',
  18582. size: [size],
  18583. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18584. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18585. move: options.mass != 0,
  18586. config: [options.mass, options.friction, options.restitution],
  18587. world: this._world
  18588. });
  18589. break;
  18590. case BABYLON.PhysicsEngine.PlaneImpostor:
  18591. case BABYLON.PhysicsEngine.CylinderImpostor:
  18592. case BABYLON.PhysicsEngine.BoxImpostor:
  18593. var min = bbox.minimumWorld;
  18594. var max = bbox.maximumWorld;
  18595. var box = max.subtract(min);
  18596. var sizeX = this._checkWithEpsilon(box.x);
  18597. var sizeY = this._checkWithEpsilon(box.y);
  18598. var sizeZ = this._checkWithEpsilon(box.z);
  18599. body = new OIMO.Body({
  18600. type: 'box',
  18601. size: [sizeX, sizeY, sizeZ],
  18602. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18603. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18604. move: options.mass != 0,
  18605. config: [options.mass, options.friction, options.restitution],
  18606. world: this._world
  18607. });
  18608. break;
  18609. }
  18610. //If quaternion was set as the rotation of the object
  18611. if (initialRotation) {
  18612. //We have to access the rigid body's properties to set the quaternion.
  18613. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  18614. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  18615. //update the internal rotation matrix
  18616. body.body.syncShapes();
  18617. }
  18618. this._registeredMeshes.push({
  18619. mesh: mesh,
  18620. body: body,
  18621. delta: deltaPosition
  18622. });
  18623. return body;
  18624. };
  18625. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18626. var types = [], sizes = [], positions = [], rotations = [];
  18627. var initialMesh = parts[0].mesh;
  18628. for (var index = 0; index < parts.length; index++) {
  18629. var part = parts[index];
  18630. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  18631. types.push(bodyParameters.type);
  18632. sizes.push.apply(sizes, bodyParameters.size);
  18633. positions.push.apply(positions, bodyParameters.pos);
  18634. rotations.push.apply(rotations, bodyParameters.rot);
  18635. }
  18636. var body = new OIMO.Body({
  18637. type: types,
  18638. size: sizes,
  18639. pos: positions,
  18640. rot: rotations,
  18641. move: options.mass != 0,
  18642. config: [options.mass, options.friction, options.restitution],
  18643. world: this._world
  18644. });
  18645. this._registeredMeshes.push({
  18646. mesh: initialMesh,
  18647. body: body
  18648. });
  18649. return body;
  18650. };
  18651. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  18652. var bodyParameters = null;
  18653. var mesh = part.mesh;
  18654. // We need the bounding box/sphere info to compute the physics body
  18655. mesh.computeWorldMatrix();
  18656. switch (part.impostor) {
  18657. case BABYLON.PhysicsEngine.SphereImpostor:
  18658. var bbox = mesh.getBoundingInfo().boundingBox;
  18659. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18660. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18661. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18662. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18663. bodyParameters = {
  18664. type: 'sphere',
  18665. /* bug with oimo : sphere needs 3 sizes in this case */
  18666. size: [size, -1, -1],
  18667. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  18668. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18669. };
  18670. break;
  18671. case BABYLON.PhysicsEngine.PlaneImpostor:
  18672. case BABYLON.PhysicsEngine.BoxImpostor:
  18673. bbox = mesh.getBoundingInfo().boundingBox;
  18674. var min = bbox.minimumWorld;
  18675. var max = bbox.maximumWorld;
  18676. var box = max.subtract(min);
  18677. var sizeX = this._checkWithEpsilon(box.x);
  18678. var sizeY = this._checkWithEpsilon(box.y);
  18679. var sizeZ = this._checkWithEpsilon(box.z);
  18680. var relativePosition = mesh.position;
  18681. bodyParameters = {
  18682. type: 'box',
  18683. size: [sizeX, sizeY, sizeZ],
  18684. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  18685. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18686. };
  18687. break;
  18688. }
  18689. return bodyParameters;
  18690. };
  18691. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  18692. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18693. var registeredMesh = this._registeredMeshes[index];
  18694. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18695. if (registeredMesh.body) {
  18696. this._world.removeRigidBody(registeredMesh.body.body);
  18697. this._unbindBody(registeredMesh.body);
  18698. }
  18699. this._registeredMeshes.splice(index, 1);
  18700. return;
  18701. }
  18702. }
  18703. };
  18704. OimoJSPlugin.prototype._unbindBody = function (body) {
  18705. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18706. var registeredMesh = this._registeredMeshes[index];
  18707. if (registeredMesh.body === body) {
  18708. registeredMesh.body = null;
  18709. }
  18710. }
  18711. };
  18712. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18713. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18714. var registeredMesh = this._registeredMeshes[index];
  18715. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18716. // Get object mass to have a behaviour similar to cannon.js
  18717. var mass = registeredMesh.body.body.massInfo.mass;
  18718. // The force is scaled with the mass of object
  18719. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  18720. return;
  18721. }
  18722. }
  18723. };
  18724. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18725. var body1 = null, body2 = null;
  18726. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18727. var registeredMesh = this._registeredMeshes[index];
  18728. if (registeredMesh.mesh === mesh1) {
  18729. body1 = registeredMesh.body.body;
  18730. }
  18731. else if (registeredMesh.mesh === mesh2) {
  18732. body2 = registeredMesh.body.body;
  18733. }
  18734. }
  18735. if (!body1 || !body2) {
  18736. return false;
  18737. }
  18738. if (!options) {
  18739. options = {};
  18740. }
  18741. new OIMO.Link({
  18742. type: options.type,
  18743. body1: body1,
  18744. body2: body2,
  18745. min: options.min,
  18746. max: options.max,
  18747. axe1: options.axe1,
  18748. axe2: options.axe2,
  18749. pos1: [pivot1.x, pivot1.y, pivot1.z],
  18750. pos2: [pivot2.x, pivot2.y, pivot2.z],
  18751. collision: options.collision,
  18752. spring: options.spring,
  18753. world: this._world
  18754. });
  18755. return true;
  18756. };
  18757. OimoJSPlugin.prototype.dispose = function () {
  18758. this._world.clear();
  18759. while (this._registeredMeshes.length) {
  18760. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18761. }
  18762. };
  18763. OimoJSPlugin.prototype.isSupported = function () {
  18764. return OIMO !== undefined;
  18765. };
  18766. OimoJSPlugin.prototype._getLastShape = function (body) {
  18767. var lastShape = body.shapes;
  18768. while (lastShape.next) {
  18769. lastShape = lastShape.next;
  18770. }
  18771. return lastShape;
  18772. };
  18773. OimoJSPlugin.prototype.runOneStep = function (time) {
  18774. this._world.step();
  18775. // Update the position of all registered meshes
  18776. var i = this._registeredMeshes.length;
  18777. var m;
  18778. while (i--) {
  18779. var body = this._registeredMeshes[i].body.body;
  18780. var mesh = this._registeredMeshes[i].mesh;
  18781. var delta = this._registeredMeshes[i].delta;
  18782. if (!body.sleeping) {
  18783. if (body.shapes.next) {
  18784. var parentShape = this._getLastShape(body);
  18785. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  18786. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  18787. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  18788. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  18789. if (!mesh.rotationQuaternion) {
  18790. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18791. }
  18792. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  18793. mesh.computeWorldMatrix();
  18794. }
  18795. else {
  18796. m = body.getMatrix();
  18797. mtx = BABYLON.Matrix.FromArray(m);
  18798. // Body position
  18799. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  18800. if (!delta) {
  18801. mesh.position.x = bodyX;
  18802. mesh.position.y = bodyY;
  18803. mesh.position.z = bodyZ;
  18804. }
  18805. else {
  18806. mesh.position.x = bodyX + delta.x;
  18807. mesh.position.y = bodyY + delta.y;
  18808. mesh.position.z = bodyZ + delta.z;
  18809. }
  18810. if (!mesh.rotationQuaternion) {
  18811. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18812. }
  18813. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  18814. mesh.computeWorldMatrix();
  18815. }
  18816. }
  18817. }
  18818. };
  18819. return OimoJSPlugin;
  18820. })();
  18821. BABYLON.OimoJSPlugin = OimoJSPlugin;
  18822. })(BABYLON || (BABYLON = {}));
  18823. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  18824. (function (BABYLON) {
  18825. var PhysicsEngine = (function () {
  18826. function PhysicsEngine(plugin) {
  18827. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  18828. }
  18829. PhysicsEngine.prototype._initialize = function (gravity) {
  18830. this._currentPlugin.initialize();
  18831. this._setGravity(gravity);
  18832. };
  18833. PhysicsEngine.prototype._runOneStep = function (delta) {
  18834. if (delta > 0.1) {
  18835. delta = 0.1;
  18836. }
  18837. else if (delta <= 0) {
  18838. delta = 1.0 / 60.0;
  18839. }
  18840. this._currentPlugin.runOneStep(delta);
  18841. };
  18842. PhysicsEngine.prototype._setGravity = function (gravity) {
  18843. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  18844. this._currentPlugin.setGravity(this.gravity);
  18845. };
  18846. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  18847. return this._currentPlugin.registerMesh(mesh, impostor, options);
  18848. };
  18849. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  18850. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  18851. };
  18852. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  18853. this._currentPlugin.unregisterMesh(mesh);
  18854. };
  18855. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  18856. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  18857. };
  18858. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18859. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  18860. };
  18861. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  18862. this._currentPlugin.updateBodyPosition(mesh);
  18863. };
  18864. PhysicsEngine.prototype.dispose = function () {
  18865. this._currentPlugin.dispose();
  18866. };
  18867. PhysicsEngine.prototype.isSupported = function () {
  18868. return this._currentPlugin.isSupported();
  18869. };
  18870. // Statics
  18871. PhysicsEngine.NoImpostor = 0;
  18872. PhysicsEngine.SphereImpostor = 1;
  18873. PhysicsEngine.BoxImpostor = 2;
  18874. PhysicsEngine.PlaneImpostor = 3;
  18875. PhysicsEngine.MeshImpostor = 4;
  18876. PhysicsEngine.CapsuleImpostor = 5;
  18877. PhysicsEngine.ConeImpostor = 6;
  18878. PhysicsEngine.CylinderImpostor = 7;
  18879. PhysicsEngine.ConvexHullImpostor = 8;
  18880. PhysicsEngine.Epsilon = 0.001;
  18881. return PhysicsEngine;
  18882. })();
  18883. BABYLON.PhysicsEngine = PhysicsEngine;
  18884. })(BABYLON || (BABYLON = {}));
  18885. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  18886. (function (BABYLON) {
  18887. var serializeLight = function (light) {
  18888. var serializationObject = {};
  18889. serializationObject.name = light.name;
  18890. serializationObject.id = light.id;
  18891. serializationObject.tags = BABYLON.Tags.GetTags(light);
  18892. if (light instanceof BABYLON.PointLight) {
  18893. serializationObject.type = 0;
  18894. serializationObject.position = light.position.asArray();
  18895. }
  18896. else if (light instanceof BABYLON.DirectionalLight) {
  18897. serializationObject.type = 1;
  18898. var directionalLight = light;
  18899. serializationObject.position = directionalLight.position.asArray();
  18900. serializationObject.direction = directionalLight.direction.asArray();
  18901. }
  18902. else if (light instanceof BABYLON.SpotLight) {
  18903. serializationObject.type = 2;
  18904. var spotLight = light;
  18905. serializationObject.position = spotLight.position.asArray();
  18906. serializationObject.direction = spotLight.position.asArray();
  18907. serializationObject.angle = spotLight.angle;
  18908. serializationObject.exponent = spotLight.exponent;
  18909. }
  18910. else if (light instanceof BABYLON.HemisphericLight) {
  18911. serializationObject.type = 3;
  18912. var hemisphericLight = light;
  18913. serializationObject.direction = hemisphericLight.direction.asArray();
  18914. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  18915. }
  18916. if (light.intensity) {
  18917. serializationObject.intensity = light.intensity;
  18918. }
  18919. serializationObject.range = light.range;
  18920. serializationObject.diffuse = light.diffuse.asArray();
  18921. serializationObject.specular = light.specular.asArray();
  18922. return serializationObject;
  18923. };
  18924. var serializeFresnelParameter = function (fresnelParameter) {
  18925. var serializationObject = {};
  18926. serializationObject.isEnabled = fresnelParameter.isEnabled;
  18927. serializationObject.leftColor = fresnelParameter.leftColor;
  18928. serializationObject.rightColor = fresnelParameter.rightColor;
  18929. serializationObject.bias = fresnelParameter.bias;
  18930. serializationObject.power = fresnelParameter.power;
  18931. return serializationObject;
  18932. };
  18933. var appendAnimations = function (source, destination) {
  18934. if (source.animations) {
  18935. destination.animations = [];
  18936. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18937. var animation = source.animations[animationIndex];
  18938. destination.animations.push(serializeAnimation(animation));
  18939. }
  18940. }
  18941. };
  18942. var serializeCamera = function (camera) {
  18943. var serializationObject = {};
  18944. serializationObject.name = camera.name;
  18945. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  18946. serializationObject.id = camera.id;
  18947. serializationObject.position = camera.position.asArray();
  18948. // Parent
  18949. if (camera.parent) {
  18950. serializationObject.parentId = camera.parent.id;
  18951. }
  18952. serializationObject.fov = camera.fov;
  18953. serializationObject.minZ = camera.minZ;
  18954. serializationObject.maxZ = camera.maxZ;
  18955. serializationObject.inertia = camera.inertia;
  18956. //setting the type
  18957. if (camera instanceof BABYLON.FreeCamera) {
  18958. serializationObject.type = "FreeCamera";
  18959. }
  18960. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18961. serializationObject.type = "ArcRotateCamera";
  18962. }
  18963. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18964. serializationObject.type = "AnaglyphArcRotateCamera";
  18965. }
  18966. else if (camera instanceof BABYLON.GamepadCamera) {
  18967. serializationObject.type = "GamepadCamera";
  18968. }
  18969. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18970. serializationObject.type = "AnaglyphFreeCamera";
  18971. }
  18972. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18973. serializationObject.type = "DeviceOrientationCamera";
  18974. }
  18975. else if (camera instanceof BABYLON.FollowCamera) {
  18976. serializationObject.type = "FollowCamera";
  18977. }
  18978. else if (camera instanceof BABYLON.OculusCamera) {
  18979. serializationObject.type = "OculusCamera";
  18980. }
  18981. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18982. serializationObject.type = "OculusGamepadCamera";
  18983. }
  18984. else if (camera instanceof BABYLON.TouchCamera) {
  18985. serializationObject.type = "TouchCamera";
  18986. }
  18987. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18988. serializationObject.type = "VirtualJoysticksCamera";
  18989. }
  18990. else if (camera instanceof BABYLON.WebVRCamera) {
  18991. serializationObject.type = "WebVRCamera";
  18992. }
  18993. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18994. serializationObject.type = "VRDeviceOrientationCamera";
  18995. }
  18996. //special properties of specific cameras
  18997. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18998. var arcCamera = camera;
  18999. serializationObject.alpha = arcCamera.alpha;
  19000. serializationObject.beta = arcCamera.beta;
  19001. serializationObject.radius = arcCamera.radius;
  19002. if (arcCamera.target && arcCamera.target.id) {
  19003. serializationObject.lockedTargetId = arcCamera.target.id;
  19004. }
  19005. }
  19006. else if (camera instanceof BABYLON.FollowCamera) {
  19007. var followCam = camera;
  19008. serializationObject.radius = followCam.radius;
  19009. serializationObject.heightOffset = followCam.heightOffset;
  19010. serializationObject.rotationOffset = followCam.rotationOffset;
  19011. }
  19012. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  19013. //eye space is a private member and can only be access like this. Without changing the implementation this is the best way to get it.
  19014. if (camera['_eyeSpace'] !== undefined) {
  19015. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  19016. }
  19017. }
  19018. //general properties that not all cameras have. The [] is due to typescript's type safety
  19019. if (camera['speed'] !== undefined) {
  19020. serializationObject.speed = camera['speed'];
  19021. }
  19022. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  19023. serializationObject.target = camera['target'].asArray();
  19024. }
  19025. // Target
  19026. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  19027. serializationObject.rotation = camera['rotation'].asArray();
  19028. }
  19029. // Locked target
  19030. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  19031. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  19032. }
  19033. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  19034. serializationObject.applyGravity = camera['applyGravity'] || false;
  19035. if (camera['ellipsoid']) {
  19036. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  19037. }
  19038. // Animations
  19039. appendAnimations(camera, serializationObject);
  19040. // Layer mask
  19041. serializationObject.layerMask = camera.layerMask;
  19042. return serializationObject;
  19043. };
  19044. var serializeAnimation = function (animation) {
  19045. var serializationObject = {};
  19046. serializationObject.name = animation.name;
  19047. serializationObject.property = animation.targetProperty;
  19048. serializationObject.framePerSecond = animation.framePerSecond;
  19049. serializationObject.dataType = animation.dataType;
  19050. serializationObject.loopBehavior = animation.loopMode;
  19051. var dataType = animation.dataType;
  19052. serializationObject.keys = [];
  19053. var keys = animation.getKeys();
  19054. for (var index = 0; index < keys.length; index++) {
  19055. var animationKey = keys[index];
  19056. var key = {};
  19057. key.frame = animationKey.frame;
  19058. switch (dataType) {
  19059. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19060. key.values = [animationKey.value];
  19061. break;
  19062. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19063. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19064. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19065. key.values = animationKey.value.asArray();
  19066. break;
  19067. }
  19068. serializationObject.keys.push(key);
  19069. }
  19070. return serializationObject;
  19071. };
  19072. var serializeMultiMaterial = function (material) {
  19073. var serializationObject = {};
  19074. serializationObject.name = material.name;
  19075. serializationObject.id = material.id;
  19076. serializationObject.tags = BABYLON.Tags.GetTags(material);
  19077. serializationObject.materials = [];
  19078. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  19079. var subMat = material.subMaterials[matIndex];
  19080. if (subMat) {
  19081. serializationObject.materials.push(subMat.id);
  19082. }
  19083. else {
  19084. serializationObject.materials.push(null);
  19085. }
  19086. }
  19087. return serializationObject;
  19088. };
  19089. var serializeMaterial = function (material) {
  19090. var serializationObject = {};
  19091. serializationObject.name = material.name;
  19092. serializationObject.ambient = material.ambientColor.asArray();
  19093. serializationObject.diffuse = material.diffuseColor.asArray();
  19094. serializationObject.specular = material.specularColor.asArray();
  19095. serializationObject.specularPower = material.specularPower;
  19096. serializationObject.emissive = material.emissiveColor.asArray();
  19097. serializationObject.alpha = material.alpha;
  19098. serializationObject.id = material.id;
  19099. serializationObject.tags = BABYLON.Tags.GetTags(material);
  19100. serializationObject.backFaceCulling = material.backFaceCulling;
  19101. if (material.diffuseTexture) {
  19102. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  19103. }
  19104. if (material.diffuseFresnelParameters) {
  19105. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  19106. }
  19107. if (material.ambientTexture) {
  19108. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  19109. }
  19110. if (material.opacityTexture) {
  19111. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  19112. }
  19113. if (material.opacityFresnelParameters) {
  19114. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  19115. }
  19116. if (material.reflectionTexture) {
  19117. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  19118. }
  19119. if (material.reflectionFresnelParameters) {
  19120. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  19121. }
  19122. if (material.emissiveTexture) {
  19123. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  19124. }
  19125. if (material.emissiveFresnelParameters) {
  19126. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  19127. }
  19128. if (material.specularTexture) {
  19129. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  19130. }
  19131. if (material.bumpTexture) {
  19132. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  19133. }
  19134. return serializationObject;
  19135. };
  19136. var serializeTexture = function (texture) {
  19137. var serializationObject = {};
  19138. if (!texture.name) {
  19139. return null;
  19140. }
  19141. if (texture instanceof BABYLON.CubeTexture) {
  19142. serializationObject.name = texture.name;
  19143. serializationObject.hasAlpha = texture.hasAlpha;
  19144. serializationObject.level = texture.level;
  19145. serializationObject.coordinatesMode = texture.coordinatesMode;
  19146. return serializationObject;
  19147. }
  19148. if (texture instanceof BABYLON.MirrorTexture) {
  19149. var mirrorTexture = texture;
  19150. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  19151. serializationObject.renderList = [];
  19152. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  19153. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  19154. }
  19155. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  19156. }
  19157. else if (texture instanceof BABYLON.RenderTargetTexture) {
  19158. var renderTargetTexture = texture;
  19159. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  19160. serializationObject.renderList = [];
  19161. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  19162. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  19163. }
  19164. }
  19165. var regularTexture = texture;
  19166. serializationObject.name = texture.name;
  19167. serializationObject.hasAlpha = texture.hasAlpha;
  19168. serializationObject.level = texture.level;
  19169. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  19170. serializationObject.coordinatesMode = texture.coordinatesMode;
  19171. serializationObject.uOffset = regularTexture.uOffset;
  19172. serializationObject.vOffset = regularTexture.vOffset;
  19173. serializationObject.uScale = regularTexture.uScale;
  19174. serializationObject.vScale = regularTexture.vScale;
  19175. serializationObject.uAng = regularTexture.uAng;
  19176. serializationObject.vAng = regularTexture.vAng;
  19177. serializationObject.wAng = regularTexture.wAng;
  19178. serializationObject.wrapU = texture.wrapU;
  19179. serializationObject.wrapV = texture.wrapV;
  19180. // Animations
  19181. appendAnimations(texture, serializationObject);
  19182. return serializationObject;
  19183. };
  19184. var serializeSkeleton = function (skeleton) {
  19185. var serializationObject = {};
  19186. serializationObject.name = skeleton.name;
  19187. serializationObject.id = skeleton.id;
  19188. serializationObject.bones = [];
  19189. for (var index = 0; index < skeleton.bones.length; index++) {
  19190. var bone = skeleton.bones[index];
  19191. var serializedBone = {
  19192. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  19193. name: bone.name,
  19194. matrix: bone.getLocalMatrix().toArray()
  19195. };
  19196. serializationObject.bones.push(serializedBone);
  19197. if (bone.animations && bone.animations.length > 0) {
  19198. serializedBone.animation = serializeAnimation(bone.animations[0]);
  19199. }
  19200. }
  19201. return serializationObject;
  19202. };
  19203. var serializeParticleSystem = function (particleSystem) {
  19204. var serializationObject = {};
  19205. serializationObject.emitterId = particleSystem.emitter.id;
  19206. serializationObject.capacity = particleSystem.getCapacity();
  19207. if (particleSystem.particleTexture) {
  19208. serializationObject.textureName = particleSystem.particleTexture.name;
  19209. }
  19210. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  19211. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  19212. serializationObject.minSize = particleSystem.minSize;
  19213. serializationObject.maxSize = particleSystem.maxSize;
  19214. serializationObject.minLifeTime = particleSystem.minLifeTime;
  19215. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  19216. serializationObject.emitRate = particleSystem.emitRate;
  19217. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  19218. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  19219. serializationObject.gravity = particleSystem.gravity.asArray();
  19220. serializationObject.direction1 = particleSystem.direction1.asArray();
  19221. serializationObject.direction2 = particleSystem.direction2.asArray();
  19222. serializationObject.color1 = particleSystem.color1.asArray();
  19223. serializationObject.color2 = particleSystem.color2.asArray();
  19224. serializationObject.colorDead = particleSystem.colorDead.asArray();
  19225. serializationObject.updateSpeed = particleSystem.updateSpeed;
  19226. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  19227. serializationObject.textureMask = particleSystem.textureMask.asArray();
  19228. serializationObject.blendMode = particleSystem.blendMode;
  19229. return serializationObject;
  19230. };
  19231. var serializeLensFlareSystem = function (lensFlareSystem) {
  19232. var serializationObject = {};
  19233. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  19234. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  19235. serializationObject.flares = [];
  19236. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  19237. var flare = lensFlareSystem.lensFlares[index];
  19238. serializationObject.flares.push({
  19239. size: flare.size,
  19240. position: flare.position,
  19241. color: flare.color.asArray(),
  19242. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  19243. });
  19244. }
  19245. return serializationObject;
  19246. };
  19247. var serializeShadowGenerator = function (light) {
  19248. var serializationObject = {};
  19249. var shadowGenerator = light.getShadowGenerator();
  19250. serializationObject.lightId = light.id;
  19251. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  19252. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  19253. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  19254. serializationObject.renderList = [];
  19255. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  19256. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  19257. serializationObject.renderList.push(mesh.id);
  19258. }
  19259. return serializationObject;
  19260. };
  19261. var serializedGeometries = [];
  19262. var serializeGeometry = function (geometry, serializationGeometries) {
  19263. if (serializedGeometries[geometry.id]) {
  19264. return;
  19265. }
  19266. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  19267. serializationGeometries.boxes.push(serializeBox(geometry));
  19268. }
  19269. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  19270. serializationGeometries.spheres.push(serializeSphere(geometry));
  19271. }
  19272. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  19273. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  19274. }
  19275. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  19276. serializationGeometries.toruses.push(serializeTorus(geometry));
  19277. }
  19278. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  19279. serializationGeometries.grounds.push(serializeGround(geometry));
  19280. }
  19281. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  19282. serializationGeometries.planes.push(serializePlane(geometry));
  19283. }
  19284. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  19285. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  19286. }
  19287. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  19288. throw new Error("Unknow primitive type");
  19289. }
  19290. else {
  19291. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  19292. }
  19293. serializedGeometries[geometry.id] = true;
  19294. };
  19295. var serializeGeometryBase = function (geometry) {
  19296. var serializationObject = {};
  19297. serializationObject.id = geometry.id;
  19298. if (BABYLON.Tags.HasTags(geometry)) {
  19299. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  19300. }
  19301. return serializationObject;
  19302. };
  19303. var serializeVertexData = function (vertexData) {
  19304. var serializationObject = serializeGeometryBase(vertexData);
  19305. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19306. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19307. }
  19308. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19309. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19310. }
  19311. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19312. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19313. }
  19314. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19315. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19316. }
  19317. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19318. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19319. }
  19320. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19321. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19322. serializationObject.matricesIndices._isExpanded = true;
  19323. }
  19324. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19325. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19326. }
  19327. serializationObject.indices = vertexData.getIndices();
  19328. return serializationObject;
  19329. };
  19330. var serializePrimitive = function (primitive) {
  19331. var serializationObject = serializeGeometryBase(primitive);
  19332. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  19333. return serializationObject;
  19334. };
  19335. var serializeBox = function (box) {
  19336. var serializationObject = serializePrimitive(box);
  19337. serializationObject.size = box.size;
  19338. return serializationObject;
  19339. };
  19340. var serializeSphere = function (sphere) {
  19341. var serializationObject = serializePrimitive(sphere);
  19342. serializationObject.segments = sphere.segments;
  19343. serializationObject.diameter = sphere.diameter;
  19344. return serializationObject;
  19345. };
  19346. var serializeCylinder = function (cylinder) {
  19347. var serializationObject = serializePrimitive(cylinder);
  19348. serializationObject.height = cylinder.height;
  19349. serializationObject.diameterTop = cylinder.diameterTop;
  19350. serializationObject.diameterBottom = cylinder.diameterBottom;
  19351. serializationObject.tessellation = cylinder.tessellation;
  19352. return serializationObject;
  19353. };
  19354. var serializeTorus = function (torus) {
  19355. var serializationObject = serializePrimitive(torus);
  19356. serializationObject.diameter = torus.diameter;
  19357. serializationObject.thickness = torus.thickness;
  19358. serializationObject.tessellation = torus.tessellation;
  19359. return serializationObject;
  19360. };
  19361. var serializeGround = function (ground) {
  19362. var serializationObject = serializePrimitive(ground);
  19363. serializationObject.width = ground.width;
  19364. serializationObject.height = ground.height;
  19365. serializationObject.subdivisions = ground.subdivisions;
  19366. return serializationObject;
  19367. };
  19368. var serializePlane = function (plane) {
  19369. var serializationObject = serializePrimitive(plane);
  19370. serializationObject.size = plane.size;
  19371. return serializationObject;
  19372. };
  19373. var serializeTorusKnot = function (torusKnot) {
  19374. var serializationObject = serializePrimitive(torusKnot);
  19375. serializationObject.radius = torusKnot.radius;
  19376. serializationObject.tube = torusKnot.tube;
  19377. serializationObject.radialSegments = torusKnot.radialSegments;
  19378. serializationObject.tubularSegments = torusKnot.tubularSegments;
  19379. serializationObject.p = torusKnot.p;
  19380. serializationObject.q = torusKnot.q;
  19381. return serializationObject;
  19382. };
  19383. var serializeMesh = function (mesh, serializationScene) {
  19384. var serializationObject = {};
  19385. serializationObject.name = mesh.name;
  19386. serializationObject.id = mesh.id;
  19387. if (BABYLON.Tags.HasTags(mesh)) {
  19388. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  19389. }
  19390. serializationObject.position = mesh.position.asArray();
  19391. if (mesh.rotationQuaternion) {
  19392. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  19393. }
  19394. else if (mesh.rotation) {
  19395. serializationObject.rotation = mesh.rotation.asArray();
  19396. }
  19397. serializationObject.scaling = mesh.scaling.asArray();
  19398. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  19399. serializationObject.isEnabled = mesh.isEnabled();
  19400. serializationObject.isVisible = mesh.isVisible;
  19401. serializationObject.infiniteDistance = mesh.infiniteDistance;
  19402. serializationObject.pickable = mesh.isPickable;
  19403. serializationObject.receiveShadows = mesh.receiveShadows;
  19404. serializationObject.billboardMode = mesh.billboardMode;
  19405. serializationObject.visibility = mesh.visibility;
  19406. serializationObject.checkCollisions = mesh.checkCollisions;
  19407. // Parent
  19408. if (mesh.parent) {
  19409. serializationObject.parentId = mesh.parent.id;
  19410. }
  19411. // Geometry
  19412. var geometry = mesh._geometry;
  19413. if (geometry) {
  19414. var geometryId = geometry.id;
  19415. serializationObject.geometryId = geometryId;
  19416. if (!mesh.getScene().getGeometryByID(geometryId)) {
  19417. // 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
  19418. serializeGeometry(geometry, serializationScene.geometries);
  19419. }
  19420. // SubMeshes
  19421. serializationObject.subMeshes = [];
  19422. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  19423. var subMesh = mesh.subMeshes[subIndex];
  19424. serializationObject.subMeshes.push({
  19425. materialIndex: subMesh.materialIndex,
  19426. verticesStart: subMesh.verticesStart,
  19427. verticesCount: subMesh.verticesCount,
  19428. indexStart: subMesh.indexStart,
  19429. indexCount: subMesh.indexCount
  19430. });
  19431. }
  19432. }
  19433. // Material
  19434. if (mesh.material) {
  19435. serializationObject.materialId = mesh.material.id;
  19436. }
  19437. else {
  19438. mesh.material = null;
  19439. }
  19440. // Skeleton
  19441. if (mesh.skeleton) {
  19442. serializationObject.skeletonId = mesh.skeleton.id;
  19443. }
  19444. // Physics
  19445. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  19446. serializationObject.physicsMass = mesh.getPhysicsMass();
  19447. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  19448. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  19449. switch (mesh.getPhysicsImpostor()) {
  19450. case BABYLON.PhysicsEngine.BoxImpostor:
  19451. serializationObject.physicsImpostor = 1;
  19452. break;
  19453. case BABYLON.PhysicsEngine.SphereImpostor:
  19454. serializationObject.physicsImpostor = 2;
  19455. break;
  19456. }
  19457. }
  19458. // Instances
  19459. serializationObject.instances = [];
  19460. for (var index = 0; index < mesh.instances.length; index++) {
  19461. var instance = mesh.instances[index];
  19462. var serializationInstance = {
  19463. name: instance.name,
  19464. position: instance.position,
  19465. rotation: instance.rotation,
  19466. rotationQuaternion: instance.rotationQuaternion,
  19467. scaling: instance.scaling
  19468. };
  19469. serializationObject.instances.push(serializationInstance);
  19470. // Animations
  19471. appendAnimations(instance, serializationInstance);
  19472. }
  19473. // Animations
  19474. appendAnimations(mesh, serializationObject);
  19475. // Layer mask
  19476. serializationObject.layerMask = mesh.layerMask;
  19477. return serializationObject;
  19478. };
  19479. var SceneSerializer = (function () {
  19480. function SceneSerializer() {
  19481. }
  19482. SceneSerializer.Serialize = function (scene) {
  19483. var serializationObject = {};
  19484. // Scene
  19485. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  19486. serializationObject.autoClear = scene.autoClear;
  19487. serializationObject.clearColor = scene.clearColor.asArray();
  19488. serializationObject.ambientColor = scene.ambientColor.asArray();
  19489. serializationObject.gravity = scene.gravity.asArray();
  19490. // Fog
  19491. if (scene.fogMode && scene.fogMode !== 0) {
  19492. serializationObject.fogMode = scene.fogMode;
  19493. serializationObject.fogColor = scene.fogColor.asArray();
  19494. serializationObject.fogStart = scene.fogStart;
  19495. serializationObject.fogEnd = scene.fogEnd;
  19496. serializationObject.fogDensity = scene.fogDensity;
  19497. }
  19498. // Lights
  19499. serializationObject.lights = [];
  19500. for (var index = 0; index < scene.lights.length; index++) {
  19501. var light = scene.lights[index];
  19502. serializationObject.lights.push(serializeLight(light));
  19503. }
  19504. // Cameras
  19505. serializationObject.cameras = [];
  19506. for (index = 0; index < scene.cameras.length; index++) {
  19507. var camera = scene.cameras[index];
  19508. serializationObject.cameras.push(serializeCamera(camera));
  19509. }
  19510. if (scene.activeCamera) {
  19511. serializationObject.activeCameraID = scene.activeCamera.id;
  19512. }
  19513. // Materials
  19514. serializationObject.materials = [];
  19515. serializationObject.multiMaterials = [];
  19516. for (index = 0; index < scene.materials.length; index++) {
  19517. var material = scene.materials[index];
  19518. if (material instanceof BABYLON.StandardMaterial) {
  19519. serializationObject.materials.push(serializeMaterial(material));
  19520. }
  19521. else if (material instanceof BABYLON.MultiMaterial) {
  19522. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  19523. }
  19524. }
  19525. // Skeletons
  19526. serializationObject.skeletons = [];
  19527. for (index = 0; index < scene.skeletons.length; index++) {
  19528. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  19529. }
  19530. // Geometries
  19531. serializationObject.geometries = {};
  19532. serializationObject.geometries.boxes = [];
  19533. serializationObject.geometries.spheres = [];
  19534. serializationObject.geometries.cylinders = [];
  19535. serializationObject.geometries.toruses = [];
  19536. serializationObject.geometries.grounds = [];
  19537. serializationObject.geometries.planes = [];
  19538. serializationObject.geometries.torusKnots = [];
  19539. serializationObject.geometries.vertexData = [];
  19540. serializedGeometries = [];
  19541. var geometries = scene.getGeometries();
  19542. for (index = 0; index < geometries.length; index++) {
  19543. var geometry = geometries[index];
  19544. if (geometry.isReady()) {
  19545. serializeGeometry(geometry, serializationObject.geometries);
  19546. }
  19547. }
  19548. // Meshes
  19549. serializationObject.meshes = [];
  19550. for (index = 0; index < scene.meshes.length; index++) {
  19551. var abstractMesh = scene.meshes[index];
  19552. if (abstractMesh instanceof BABYLON.Mesh) {
  19553. var mesh = abstractMesh;
  19554. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  19555. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  19556. }
  19557. }
  19558. }
  19559. // Particles Systems
  19560. serializationObject.particleSystems = [];
  19561. for (index = 0; index < scene.particleSystems.length; index++) {
  19562. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  19563. }
  19564. // Lens flares
  19565. serializationObject.lensFlareSystems = [];
  19566. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  19567. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  19568. }
  19569. // Shadows
  19570. serializationObject.shadowGenerators = [];
  19571. for (index = 0; index < scene.lights.length; index++) {
  19572. light = scene.lights[index];
  19573. if (light.getShadowGenerator()) {
  19574. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  19575. }
  19576. }
  19577. return serializationObject;
  19578. };
  19579. return SceneSerializer;
  19580. })();
  19581. BABYLON.SceneSerializer = SceneSerializer;
  19582. })(BABYLON || (BABYLON = {}));
  19583. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  19584. (function (BABYLON) {
  19585. var SceneLoader = (function () {
  19586. function SceneLoader() {
  19587. }
  19588. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19589. get: function () {
  19590. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19591. },
  19592. set: function (value) {
  19593. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19594. },
  19595. enumerable: true,
  19596. configurable: true
  19597. });
  19598. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19599. get: function () {
  19600. return SceneLoader._ShowLoadingScreen;
  19601. },
  19602. set: function (value) {
  19603. SceneLoader._ShowLoadingScreen = value;
  19604. },
  19605. enumerable: true,
  19606. configurable: true
  19607. });
  19608. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19609. var dotPosition = sceneFilename.lastIndexOf(".");
  19610. var queryStringPosition = sceneFilename.indexOf("?");
  19611. if (queryStringPosition === -1) {
  19612. queryStringPosition = sceneFilename.length;
  19613. }
  19614. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19615. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19616. var plugin = this._registeredPlugins[index];
  19617. if (plugin.extensions.indexOf(extension) !== -1) {
  19618. return plugin;
  19619. }
  19620. }
  19621. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19622. };
  19623. // Public functions
  19624. SceneLoader.RegisterPlugin = function (plugin) {
  19625. plugin.extensions = plugin.extensions.toLowerCase();
  19626. SceneLoader._registeredPlugins.push(plugin);
  19627. };
  19628. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19629. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19630. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19631. return;
  19632. }
  19633. var manifestChecked = function (success) {
  19634. scene.database = database;
  19635. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19636. var importMeshFromData = function (data) {
  19637. var meshes = [];
  19638. var particleSystems = [];
  19639. var skeletons = [];
  19640. try {
  19641. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19642. if (onerror) {
  19643. onerror(scene, 'unable to load the scene');
  19644. }
  19645. return;
  19646. }
  19647. }
  19648. catch (e) {
  19649. if (onerror) {
  19650. onerror(scene, e);
  19651. }
  19652. return;
  19653. }
  19654. if (onsuccess) {
  19655. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19656. onsuccess(meshes, particleSystems, skeletons);
  19657. }
  19658. };
  19659. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19660. // Direct load
  19661. importMeshFromData(sceneFilename.substr(5));
  19662. return;
  19663. }
  19664. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19665. importMeshFromData(data);
  19666. }, progressCallBack, database);
  19667. };
  19668. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19669. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19670. };
  19671. /**
  19672. * Load a scene
  19673. * @param rootUrl a string that defines the root url for scene and resources
  19674. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19675. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19676. */
  19677. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19678. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19679. };
  19680. /**
  19681. * Append a scene
  19682. * @param rootUrl a string that defines the root url for scene and resources
  19683. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19684. * @param scene is the instance of BABYLON.Scene to append to
  19685. */
  19686. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19687. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19688. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19689. return;
  19690. }
  19691. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19692. var database;
  19693. if (SceneLoader.ShowLoadingScreen) {
  19694. scene.getEngine().displayLoadingUI();
  19695. }
  19696. var loadSceneFromData = function (data) {
  19697. scene.database = database;
  19698. if (!plugin.load(scene, data, rootUrl)) {
  19699. if (onerror) {
  19700. onerror(scene);
  19701. }
  19702. scene.getEngine().hideLoadingUI();
  19703. return;
  19704. }
  19705. if (onsuccess) {
  19706. onsuccess(scene);
  19707. }
  19708. if (SceneLoader.ShowLoadingScreen) {
  19709. scene.executeWhenReady(function () {
  19710. scene.getEngine().hideLoadingUI();
  19711. });
  19712. }
  19713. };
  19714. var manifestChecked = function (success) {
  19715. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19716. };
  19717. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19718. // Direct load
  19719. loadSceneFromData(sceneFilename.substr(5));
  19720. return;
  19721. }
  19722. if (rootUrl.indexOf("file:") === -1) {
  19723. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19724. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19725. }
  19726. else {
  19727. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19728. }
  19729. };
  19730. // Flags
  19731. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19732. SceneLoader._ShowLoadingScreen = true;
  19733. // Members
  19734. SceneLoader._registeredPlugins = new Array();
  19735. return SceneLoader;
  19736. })();
  19737. BABYLON.SceneLoader = SceneLoader;
  19738. ;
  19739. })(BABYLON || (BABYLON = {}));
  19740. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  19741. (function (BABYLON) {
  19742. var Internals;
  19743. (function (Internals) {
  19744. var checkColors4 = function (colors, count) {
  19745. // Check if color3 was used
  19746. if (colors.length === count * 3) {
  19747. var colors4 = [];
  19748. for (var index = 0; index < colors.length; index += 3) {
  19749. var newIndex = (index / 3) * 4;
  19750. colors4[newIndex] = colors[index];
  19751. colors4[newIndex + 1] = colors[index + 1];
  19752. colors4[newIndex + 2] = colors[index + 2];
  19753. colors4[newIndex + 3] = 1.0;
  19754. }
  19755. return colors4;
  19756. }
  19757. return colors;
  19758. };
  19759. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19760. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  19761. texture.name = parsedTexture.name;
  19762. texture.hasAlpha = parsedTexture.hasAlpha;
  19763. texture.level = parsedTexture.level;
  19764. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19765. return texture;
  19766. };
  19767. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19768. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19769. return null;
  19770. }
  19771. if (parsedTexture.isCube) {
  19772. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19773. }
  19774. var texture;
  19775. if (parsedTexture.mirrorPlane) {
  19776. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19777. texture._waitingRenderList = parsedTexture.renderList;
  19778. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19779. }
  19780. else if (parsedTexture.isRenderTarget) {
  19781. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19782. texture._waitingRenderList = parsedTexture.renderList;
  19783. }
  19784. else {
  19785. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19786. }
  19787. texture.name = parsedTexture.name;
  19788. texture.hasAlpha = parsedTexture.hasAlpha;
  19789. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19790. texture.level = parsedTexture.level;
  19791. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19792. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19793. texture.uOffset = parsedTexture.uOffset;
  19794. texture.vOffset = parsedTexture.vOffset;
  19795. texture.uScale = parsedTexture.uScale;
  19796. texture.vScale = parsedTexture.vScale;
  19797. texture.uAng = parsedTexture.uAng;
  19798. texture.vAng = parsedTexture.vAng;
  19799. texture.wAng = parsedTexture.wAng;
  19800. texture.wrapU = parsedTexture.wrapU;
  19801. texture.wrapV = parsedTexture.wrapV;
  19802. // Animations
  19803. if (parsedTexture.animations) {
  19804. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19805. var parsedAnimation = parsedTexture.animations[animationIndex];
  19806. texture.animations.push(parseAnimation(parsedAnimation));
  19807. }
  19808. }
  19809. return texture;
  19810. };
  19811. var parseSkeleton = function (parsedSkeleton, scene) {
  19812. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19813. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19814. var parsedBone = parsedSkeleton.bones[index];
  19815. var parentBone = null;
  19816. if (parsedBone.parentBoneIndex > -1) {
  19817. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19818. }
  19819. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19820. if (parsedBone.animation) {
  19821. bone.animations.push(parseAnimation(parsedBone.animation));
  19822. }
  19823. }
  19824. return skeleton;
  19825. };
  19826. var parseFresnelParameters = function (parsedFresnelParameters) {
  19827. var fresnelParameters = new BABYLON.FresnelParameters();
  19828. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19829. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19830. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19831. fresnelParameters.bias = parsedFresnelParameters.bias;
  19832. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19833. return fresnelParameters;
  19834. };
  19835. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19836. var material;
  19837. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19838. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19839. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19840. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19841. material.specularPower = parsedMaterial.specularPower;
  19842. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19843. material.alpha = parsedMaterial.alpha;
  19844. material.id = parsedMaterial.id;
  19845. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19846. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19847. material.wireframe = parsedMaterial.wireframe;
  19848. if (parsedMaterial.diffuseTexture) {
  19849. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19850. }
  19851. if (parsedMaterial.diffuseFresnelParameters) {
  19852. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19853. }
  19854. if (parsedMaterial.ambientTexture) {
  19855. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19856. }
  19857. if (parsedMaterial.opacityTexture) {
  19858. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19859. }
  19860. if (parsedMaterial.opacityFresnelParameters) {
  19861. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19862. }
  19863. if (parsedMaterial.reflectionTexture) {
  19864. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19865. }
  19866. if (parsedMaterial.reflectionFresnelParameters) {
  19867. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19868. }
  19869. if (parsedMaterial.emissiveTexture) {
  19870. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19871. }
  19872. if (parsedMaterial.emissiveFresnelParameters) {
  19873. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19874. }
  19875. if (parsedMaterial.specularTexture) {
  19876. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19877. }
  19878. if (parsedMaterial.bumpTexture) {
  19879. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19880. }
  19881. return material;
  19882. };
  19883. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19884. for (var index = 0; index < parsedData.materials.length; index++) {
  19885. var parsedMaterial = parsedData.materials[index];
  19886. if (parsedMaterial.id === id) {
  19887. return parseMaterial(parsedMaterial, scene, rootUrl);
  19888. }
  19889. }
  19890. return null;
  19891. };
  19892. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19893. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19894. multiMaterial.id = parsedMultiMaterial.id;
  19895. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19896. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19897. var subMatId = parsedMultiMaterial.materials[matIndex];
  19898. if (subMatId) {
  19899. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19900. }
  19901. else {
  19902. multiMaterial.subMaterials.push(null);
  19903. }
  19904. }
  19905. return multiMaterial;
  19906. };
  19907. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19908. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19909. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19910. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19911. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19912. var parsedFlare = parsedLensFlareSystem.flares[index];
  19913. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19914. }
  19915. return lensFlareSystem;
  19916. };
  19917. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19918. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19919. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19920. if (parsedParticleSystem.textureName) {
  19921. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19922. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19923. }
  19924. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19925. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19926. particleSystem.minSize = parsedParticleSystem.minSize;
  19927. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19928. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19929. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19930. particleSystem.emitter = emitter;
  19931. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19932. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19933. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19934. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19935. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19936. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19937. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19938. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19939. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19940. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19941. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19942. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19943. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19944. particleSystem.start();
  19945. return particleSystem;
  19946. };
  19947. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19948. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19949. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19950. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19951. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19952. shadowGenerator.getShadowMap().renderList.push(mesh);
  19953. }
  19954. if (parsedShadowGenerator.usePoissonSampling) {
  19955. shadowGenerator.usePoissonSampling = true;
  19956. }
  19957. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19958. shadowGenerator.useVarianceShadowMap = true;
  19959. }
  19960. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19961. shadowGenerator.useBlurVarianceShadowMap = true;
  19962. if (parsedShadowGenerator.blurScale) {
  19963. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19964. }
  19965. if (parsedShadowGenerator.blurBoxOffset) {
  19966. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19967. }
  19968. }
  19969. if (parsedShadowGenerator.bias !== undefined) {
  19970. shadowGenerator.bias = parsedShadowGenerator.bias;
  19971. }
  19972. return shadowGenerator;
  19973. };
  19974. var parseAnimation = function (parsedAnimation) {
  19975. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19976. var dataType = parsedAnimation.dataType;
  19977. var keys = [];
  19978. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19979. var key = parsedAnimation.keys[index];
  19980. var data;
  19981. switch (dataType) {
  19982. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19983. data = key.values[0];
  19984. break;
  19985. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19986. data = BABYLON.Quaternion.FromArray(key.values);
  19987. break;
  19988. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19989. data = BABYLON.Matrix.FromArray(key.values);
  19990. break;
  19991. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19992. default:
  19993. data = BABYLON.Vector3.FromArray(key.values);
  19994. break;
  19995. }
  19996. keys.push({
  19997. frame: key.frame,
  19998. value: data
  19999. });
  20000. }
  20001. animation.setKeys(keys);
  20002. return animation;
  20003. };
  20004. var parseLight = function (parsedLight, scene) {
  20005. var light;
  20006. switch (parsedLight.type) {
  20007. case 0:
  20008. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  20009. break;
  20010. case 1:
  20011. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  20012. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  20013. break;
  20014. case 2:
  20015. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  20016. break;
  20017. case 3:
  20018. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  20019. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  20020. break;
  20021. }
  20022. light.id = parsedLight.id;
  20023. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  20024. if (parsedLight.intensity !== undefined) {
  20025. light.intensity = parsedLight.intensity;
  20026. }
  20027. if (parsedLight.range) {
  20028. light.range = parsedLight.range;
  20029. }
  20030. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  20031. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  20032. if (parsedLight.excludedMeshesIds) {
  20033. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  20034. }
  20035. // Parent
  20036. if (parsedLight.parentId) {
  20037. light._waitingParentId = parsedLight.parentId;
  20038. }
  20039. if (parsedLight.includedOnlyMeshesIds) {
  20040. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  20041. }
  20042. // Animations
  20043. if (parsedLight.animations) {
  20044. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  20045. var parsedAnimation = parsedLight.animations[animationIndex];
  20046. light.animations.push(parseAnimation(parsedAnimation));
  20047. }
  20048. }
  20049. if (parsedLight.autoAnimate) {
  20050. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  20051. }
  20052. };
  20053. var parseCamera = function (parsedCamera, scene) {
  20054. var camera;
  20055. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  20056. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  20057. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  20058. var alpha = parsedCamera.alpha;
  20059. var beta = parsedCamera.beta;
  20060. var radius = parsedCamera.radius;
  20061. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  20062. var eye_space = parsedCamera.eye_space;
  20063. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  20064. }
  20065. else {
  20066. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  20067. }
  20068. }
  20069. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  20070. eye_space = parsedCamera.eye_space;
  20071. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  20072. }
  20073. else if (parsedCamera.type === "DeviceOrientationCamera") {
  20074. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  20075. }
  20076. else if (parsedCamera.type === "FollowCamera") {
  20077. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  20078. camera.heightOffset = parsedCamera.heightOffset;
  20079. camera.radius = parsedCamera.radius;
  20080. camera.rotationOffset = parsedCamera.rotationOffset;
  20081. if (lockedTargetMesh)
  20082. camera.target = lockedTargetMesh;
  20083. }
  20084. else if (parsedCamera.type === "GamepadCamera") {
  20085. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  20086. }
  20087. else if (parsedCamera.type === "OculusCamera") {
  20088. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  20089. }
  20090. else if (parsedCamera.type === "OculusGamepadCamera") {
  20091. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  20092. }
  20093. else if (parsedCamera.type === "TouchCamera") {
  20094. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  20095. }
  20096. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  20097. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  20098. }
  20099. else if (parsedCamera.type === "WebVRCamera") {
  20100. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  20101. }
  20102. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  20103. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  20104. }
  20105. else {
  20106. // Free Camera is the default value
  20107. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  20108. }
  20109. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  20110. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  20111. camera.lockedTarget = lockedTargetMesh;
  20112. }
  20113. camera.id = parsedCamera.id;
  20114. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  20115. // Parent
  20116. if (parsedCamera.parentId) {
  20117. camera._waitingParentId = parsedCamera.parentId;
  20118. }
  20119. // Target
  20120. if (parsedCamera.target) {
  20121. if (camera.setTarget) {
  20122. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20123. }
  20124. else {
  20125. //For ArcRotate
  20126. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  20127. }
  20128. }
  20129. else {
  20130. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  20131. }
  20132. camera.fov = parsedCamera.fov;
  20133. camera.minZ = parsedCamera.minZ;
  20134. camera.maxZ = parsedCamera.maxZ;
  20135. camera.speed = parsedCamera.speed;
  20136. camera.inertia = parsedCamera.inertia;
  20137. camera.checkCollisions = parsedCamera.checkCollisions;
  20138. camera.applyGravity = parsedCamera.applyGravity;
  20139. if (parsedCamera.ellipsoid) {
  20140. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  20141. }
  20142. // Animations
  20143. if (parsedCamera.animations) {
  20144. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20145. var parsedAnimation = parsedCamera.animations[animationIndex];
  20146. camera.animations.push(parseAnimation(parsedAnimation));
  20147. }
  20148. }
  20149. if (parsedCamera.autoAnimate) {
  20150. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  20151. }
  20152. // Layer Mask
  20153. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  20154. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  20155. }
  20156. else {
  20157. camera.layerMask = 0xFFFFFFFF;
  20158. }
  20159. return camera;
  20160. };
  20161. var parseGeometry = function (parsedGeometry, scene) {
  20162. var id = parsedGeometry.id;
  20163. return scene.getGeometryByID(id);
  20164. };
  20165. var parseBox = function (parsedBox, scene) {
  20166. if (parseGeometry(parsedBox, scene)) {
  20167. return null; // null since geometry could be something else than a box...
  20168. }
  20169. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  20170. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  20171. scene.pushGeometry(box, true);
  20172. return box;
  20173. };
  20174. var parseSphere = function (parsedSphere, scene) {
  20175. if (parseGeometry(parsedSphere, scene)) {
  20176. return null; // null since geometry could be something else than a sphere...
  20177. }
  20178. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  20179. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  20180. scene.pushGeometry(sphere, true);
  20181. return sphere;
  20182. };
  20183. var parseCylinder = function (parsedCylinder, scene) {
  20184. if (parseGeometry(parsedCylinder, scene)) {
  20185. return null; // null since geometry could be something else than a cylinder...
  20186. }
  20187. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  20188. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  20189. scene.pushGeometry(cylinder, true);
  20190. return cylinder;
  20191. };
  20192. var parseTorus = function (parsedTorus, scene) {
  20193. if (parseGeometry(parsedTorus, scene)) {
  20194. return null; // null since geometry could be something else than a torus...
  20195. }
  20196. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  20197. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  20198. scene.pushGeometry(torus, true);
  20199. return torus;
  20200. };
  20201. var parseGround = function (parsedGround, scene) {
  20202. if (parseGeometry(parsedGround, scene)) {
  20203. return null; // null since geometry could be something else than a ground...
  20204. }
  20205. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  20206. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  20207. scene.pushGeometry(ground, true);
  20208. return ground;
  20209. };
  20210. var parsePlane = function (parsedPlane, scene) {
  20211. if (parseGeometry(parsedPlane, scene)) {
  20212. return null; // null since geometry could be something else than a plane...
  20213. }
  20214. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  20215. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  20216. scene.pushGeometry(plane, true);
  20217. return plane;
  20218. };
  20219. var parseTorusKnot = function (parsedTorusKnot, scene) {
  20220. if (parseGeometry(parsedTorusKnot, scene)) {
  20221. return null; // null since geometry could be something else than a torusKnot...
  20222. }
  20223. 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);
  20224. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  20225. scene.pushGeometry(torusKnot, true);
  20226. return torusKnot;
  20227. };
  20228. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  20229. if (parseGeometry(parsedVertexData, scene)) {
  20230. return null; // null since geometry could be a primitive
  20231. }
  20232. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  20233. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  20234. if (parsedVertexData.delayLoadingFile) {
  20235. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20236. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  20237. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  20238. geometry._delayInfo = [];
  20239. if (parsedVertexData.hasUVs) {
  20240. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20241. }
  20242. if (parsedVertexData.hasUVs2) {
  20243. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20244. }
  20245. if (parsedVertexData.hasColors) {
  20246. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20247. }
  20248. if (parsedVertexData.hasMatricesIndices) {
  20249. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20250. }
  20251. if (parsedVertexData.hasMatricesWeights) {
  20252. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20253. }
  20254. geometry._delayLoadingFunction = importVertexData;
  20255. }
  20256. else {
  20257. importVertexData(parsedVertexData, geometry);
  20258. }
  20259. scene.pushGeometry(geometry, true);
  20260. return geometry;
  20261. };
  20262. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20263. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20264. mesh.id = parsedMesh.id;
  20265. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20266. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20267. if (parsedMesh.rotationQuaternion) {
  20268. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20269. }
  20270. else if (parsedMesh.rotation) {
  20271. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20272. }
  20273. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20274. if (parsedMesh.localMatrix) {
  20275. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20276. }
  20277. else if (parsedMesh.pivotMatrix) {
  20278. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20279. }
  20280. mesh.setEnabled(parsedMesh.isEnabled);
  20281. mesh.isVisible = parsedMesh.isVisible;
  20282. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20283. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20284. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20285. if (parsedMesh.applyFog !== undefined) {
  20286. mesh.applyFog = parsedMesh.applyFog;
  20287. }
  20288. if (parsedMesh.pickable !== undefined) {
  20289. mesh.isPickable = parsedMesh.pickable;
  20290. }
  20291. if (parsedMesh.alphaIndex !== undefined) {
  20292. mesh.alphaIndex = parsedMesh.alphaIndex;
  20293. }
  20294. mesh.receiveShadows = parsedMesh.receiveShadows;
  20295. mesh.billboardMode = parsedMesh.billboardMode;
  20296. if (parsedMesh.visibility !== undefined) {
  20297. mesh.visibility = parsedMesh.visibility;
  20298. }
  20299. mesh.checkCollisions = parsedMesh.checkCollisions;
  20300. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20301. // Parent
  20302. if (parsedMesh.parentId) {
  20303. mesh._waitingParentId = parsedMesh.parentId;
  20304. }
  20305. // Actions
  20306. if (parsedMesh.actions !== undefined) {
  20307. mesh._waitingActions = parsedMesh.actions;
  20308. }
  20309. // Geometry
  20310. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20311. if (parsedMesh.delayLoadingFile) {
  20312. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20313. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20314. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20315. if (parsedMesh._binaryInfo) {
  20316. mesh._binaryInfo = parsedMesh._binaryInfo;
  20317. }
  20318. mesh._delayInfo = [];
  20319. if (parsedMesh.hasUVs) {
  20320. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20321. }
  20322. if (parsedMesh.hasUVs2) {
  20323. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20324. }
  20325. if (parsedMesh.hasColors) {
  20326. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20327. }
  20328. if (parsedMesh.hasMatricesIndices) {
  20329. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20330. }
  20331. if (parsedMesh.hasMatricesWeights) {
  20332. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20333. }
  20334. mesh._delayLoadingFunction = importGeometry;
  20335. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20336. mesh._checkDelayState();
  20337. }
  20338. }
  20339. else {
  20340. importGeometry(parsedMesh, mesh);
  20341. }
  20342. // Material
  20343. if (parsedMesh.materialId) {
  20344. mesh.setMaterialByID(parsedMesh.materialId);
  20345. }
  20346. else {
  20347. mesh.material = null;
  20348. }
  20349. // Skeleton
  20350. if (parsedMesh.skeletonId > -1) {
  20351. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20352. }
  20353. // Physics
  20354. if (parsedMesh.physicsImpostor) {
  20355. if (!scene.isPhysicsEnabled()) {
  20356. scene.enablePhysics();
  20357. }
  20358. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20359. }
  20360. // Animations
  20361. if (parsedMesh.animations) {
  20362. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20363. var parsedAnimation = parsedMesh.animations[animationIndex];
  20364. mesh.animations.push(parseAnimation(parsedAnimation));
  20365. }
  20366. }
  20367. if (parsedMesh.autoAnimate) {
  20368. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20369. }
  20370. // Layer Mask
  20371. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20372. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20373. }
  20374. else {
  20375. mesh.layerMask = 0xFFFFFFFF;
  20376. }
  20377. // Instances
  20378. if (parsedMesh.instances) {
  20379. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20380. var parsedInstance = parsedMesh.instances[index];
  20381. var instance = mesh.createInstance(parsedInstance.name);
  20382. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20383. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20384. if (parsedInstance.rotationQuaternion) {
  20385. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20386. }
  20387. else if (parsedInstance.rotation) {
  20388. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20389. }
  20390. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20391. instance.checkCollisions = mesh.checkCollisions;
  20392. if (parsedMesh.animations) {
  20393. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20394. parsedAnimation = parsedMesh.animations[animationIndex];
  20395. instance.animations.push(parseAnimation(parsedAnimation));
  20396. }
  20397. }
  20398. }
  20399. }
  20400. return mesh;
  20401. };
  20402. var parseActions = function (parsedActions, object, scene) {
  20403. var actionManager = new BABYLON.ActionManager(scene);
  20404. if (object === null)
  20405. scene.actionManager = actionManager;
  20406. else
  20407. object.actionManager = actionManager;
  20408. // instanciate a new object
  20409. var instanciate = function (name, params) {
  20410. var newInstance = Object.create(BABYLON[name].prototype);
  20411. newInstance.constructor.apply(newInstance, params);
  20412. return newInstance;
  20413. };
  20414. var parseParameter = function (name, value, target, propertyPath) {
  20415. if (propertyPath === null) {
  20416. // String, boolean or float
  20417. var floatValue = parseFloat(value);
  20418. if (value === "true" || value === "false")
  20419. return value === "true";
  20420. else
  20421. return isNaN(floatValue) ? value : floatValue;
  20422. }
  20423. var effectiveTarget = propertyPath.split(".");
  20424. var values = value.split(",");
  20425. for (var i = 0; i < effectiveTarget.length; i++) {
  20426. target = target[effectiveTarget[i]];
  20427. }
  20428. // Return appropriate value with its type
  20429. if (typeof (target) === "boolean")
  20430. return values[0] === "true";
  20431. if (typeof (target) === "string")
  20432. return values[0];
  20433. // Parameters with multiple values such as Vector3 etc.
  20434. var split = new Array();
  20435. for (var i = 0; i < values.length; i++)
  20436. split.push(parseFloat(values[i]));
  20437. if (target instanceof BABYLON.Vector3)
  20438. return BABYLON.Vector3.FromArray(split);
  20439. if (target instanceof BABYLON.Vector4)
  20440. return BABYLON.Vector4.FromArray(split);
  20441. if (target instanceof BABYLON.Color3)
  20442. return BABYLON.Color3.FromArray(split);
  20443. if (target instanceof BABYLON.Color4)
  20444. return BABYLON.Color4.FromArray(split);
  20445. return parseFloat(values[0]);
  20446. };
  20447. // traverse graph per trigger
  20448. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20449. if (combineArray === void 0) { combineArray = null; }
  20450. if (parsedAction.detached)
  20451. return;
  20452. var parameters = new Array();
  20453. var target = null;
  20454. var propertyPath = null;
  20455. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20456. // Parameters
  20457. if (parsedAction.type === 2)
  20458. parameters.push(actionManager);
  20459. else
  20460. parameters.push(trigger);
  20461. if (combine) {
  20462. var actions = new Array();
  20463. for (var j = 0; j < parsedAction.combine.length; j++) {
  20464. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20465. }
  20466. parameters.push(actions);
  20467. }
  20468. else {
  20469. for (var i = 0; i < parsedAction.properties.length; i++) {
  20470. var value = parsedAction.properties[i].value;
  20471. var name = parsedAction.properties[i].name;
  20472. var targetType = parsedAction.properties[i].targetType;
  20473. if (name === "target")
  20474. if (targetType !== null && targetType === "SceneProperties")
  20475. value = target = scene;
  20476. else
  20477. value = target = scene.getNodeByName(value);
  20478. else if (name === "parent")
  20479. value = scene.getNodeByName(value);
  20480. else if (name === "sound")
  20481. value = scene.getSoundByName(value);
  20482. else if (name !== "propertyPath") {
  20483. if (parsedAction.type === 2 && name === "operator")
  20484. value = BABYLON.ValueCondition[value];
  20485. else
  20486. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20487. }
  20488. else {
  20489. propertyPath = value;
  20490. }
  20491. parameters.push(value);
  20492. }
  20493. }
  20494. if (combineArray === null) {
  20495. parameters.push(condition);
  20496. }
  20497. else {
  20498. parameters.push(null);
  20499. }
  20500. // If interpolate value action
  20501. if (parsedAction.name === "InterpolateValueAction") {
  20502. var param = parameters[parameters.length - 2];
  20503. parameters[parameters.length - 1] = param;
  20504. parameters[parameters.length - 2] = condition;
  20505. }
  20506. // Action or condition(s) and not CombineAction
  20507. var newAction = instanciate(parsedAction.name, parameters);
  20508. if (combineArray === null) {
  20509. if (newAction instanceof BABYLON.Condition) {
  20510. condition = newAction;
  20511. newAction = action;
  20512. }
  20513. else {
  20514. condition = null;
  20515. if (action)
  20516. action.then(newAction);
  20517. else
  20518. actionManager.registerAction(newAction);
  20519. }
  20520. }
  20521. else {
  20522. combineArray.push(newAction);
  20523. }
  20524. for (var i = 0; i < parsedAction.children.length; i++)
  20525. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20526. };
  20527. for (var i = 0; i < parsedActions.children.length; i++) {
  20528. var triggerParams;
  20529. var trigger = parsedActions.children[i];
  20530. if (trigger.properties.length > 0) {
  20531. var param = trigger.properties[0].value;
  20532. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20533. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20534. }
  20535. else
  20536. triggerParams = BABYLON.ActionManager[trigger.name];
  20537. for (var j = 0; j < trigger.children.length; j++) {
  20538. if (!trigger.detached)
  20539. traverse(trigger.children[j], triggerParams, null, null);
  20540. }
  20541. }
  20542. };
  20543. var parseSound = function (parsedSound, scene, rootUrl) {
  20544. var soundName = parsedSound.name;
  20545. var soundUrl = rootUrl + soundName;
  20546. var options = {
  20547. autoplay: parsedSound.autoplay,
  20548. loop: parsedSound.loop,
  20549. volume: parsedSound.volume,
  20550. spatialSound: parsedSound.spatialSound,
  20551. maxDistance: parsedSound.maxDistance,
  20552. rolloffFactor: parsedSound.rolloffFactor,
  20553. refDistance: parsedSound.refDistance,
  20554. distanceModel: parsedSound.distanceModel,
  20555. playbackRate: parsedSound.playbackRate
  20556. };
  20557. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  20558. scene._removePendingData(newSound);
  20559. }, options);
  20560. scene._addPendingData(newSound);
  20561. if (parsedSound.position) {
  20562. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20563. newSound.setPosition(soundPosition);
  20564. }
  20565. if (parsedSound.isDirectional) {
  20566. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20567. if (parsedSound.localDirectionToMesh) {
  20568. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20569. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20570. }
  20571. }
  20572. if (parsedSound.connectedMeshId) {
  20573. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20574. if (connectedMesh) {
  20575. newSound.attachToMesh(connectedMesh);
  20576. }
  20577. }
  20578. };
  20579. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20580. names = (names instanceof Array) ? names : [names];
  20581. for (var i in names) {
  20582. if (mesh.name === names[i]) {
  20583. hierarchyIds.push(mesh.id);
  20584. return true;
  20585. }
  20586. }
  20587. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20588. hierarchyIds.push(mesh.id);
  20589. return true;
  20590. }
  20591. return false;
  20592. };
  20593. var importVertexData = function (parsedVertexData, geometry) {
  20594. var vertexData = new BABYLON.VertexData();
  20595. // positions
  20596. var positions = parsedVertexData.positions;
  20597. if (positions) {
  20598. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20599. }
  20600. // normals
  20601. var normals = parsedVertexData.normals;
  20602. if (normals) {
  20603. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20604. }
  20605. // uvs
  20606. var uvs = parsedVertexData.uvs;
  20607. if (uvs) {
  20608. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20609. }
  20610. // uv2s
  20611. var uv2s = parsedVertexData.uv2s;
  20612. if (uv2s) {
  20613. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20614. }
  20615. // colors
  20616. var colors = parsedVertexData.colors;
  20617. if (colors) {
  20618. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20619. }
  20620. // matricesIndices
  20621. var matricesIndices = parsedVertexData.matricesIndices;
  20622. if (matricesIndices) {
  20623. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20624. }
  20625. // matricesWeights
  20626. var matricesWeights = parsedVertexData.matricesWeights;
  20627. if (matricesWeights) {
  20628. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20629. }
  20630. // indices
  20631. var indices = parsedVertexData.indices;
  20632. if (indices) {
  20633. vertexData.indices = indices;
  20634. }
  20635. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20636. };
  20637. var importGeometry = function (parsedGeometry, mesh) {
  20638. var scene = mesh.getScene();
  20639. // Geometry
  20640. var geometryId = parsedGeometry.geometryId;
  20641. if (geometryId) {
  20642. var geometry = scene.getGeometryByID(geometryId);
  20643. if (geometry) {
  20644. geometry.applyToMesh(mesh);
  20645. }
  20646. }
  20647. else if (parsedGeometry instanceof ArrayBuffer) {
  20648. var binaryInfo = mesh._binaryInfo;
  20649. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20650. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20651. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20652. }
  20653. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20654. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20655. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20656. }
  20657. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20658. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20659. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20660. }
  20661. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20662. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20663. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20664. }
  20665. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20666. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20667. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  20668. }
  20669. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20670. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20671. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20672. }
  20673. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20674. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20675. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20676. }
  20677. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20678. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20679. mesh.setIndices(indicesData);
  20680. }
  20681. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20682. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20683. mesh.subMeshes = [];
  20684. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20685. var materialIndex = subMeshesData[(i * 5) + 0];
  20686. var verticesStart = subMeshesData[(i * 5) + 1];
  20687. var verticesCount = subMeshesData[(i * 5) + 2];
  20688. var indexStart = subMeshesData[(i * 5) + 3];
  20689. var indexCount = subMeshesData[(i * 5) + 4];
  20690. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20691. }
  20692. }
  20693. }
  20694. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20695. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20696. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20697. if (parsedGeometry.uvs) {
  20698. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20699. }
  20700. if (parsedGeometry.uvs2) {
  20701. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20702. }
  20703. if (parsedGeometry.colors) {
  20704. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20705. }
  20706. if (parsedGeometry.matricesIndices) {
  20707. if (!parsedGeometry.matricesIndices._isExpanded) {
  20708. var floatIndices = [];
  20709. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20710. var matricesIndex = parsedGeometry.matricesIndices[i];
  20711. floatIndices.push(matricesIndex & 0x000000FF);
  20712. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20713. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20714. floatIndices.push(matricesIndex >> 24);
  20715. }
  20716. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20717. }
  20718. else {
  20719. delete parsedGeometry.matricesIndices._isExpanded;
  20720. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20721. }
  20722. }
  20723. if (parsedGeometry.matricesWeights) {
  20724. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20725. }
  20726. mesh.setIndices(parsedGeometry.indices);
  20727. // SubMeshes
  20728. if (parsedGeometry.subMeshes) {
  20729. mesh.subMeshes = [];
  20730. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20731. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20732. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20733. }
  20734. }
  20735. }
  20736. // Flat shading
  20737. if (mesh._shouldGenerateFlatShading) {
  20738. mesh.convertToFlatShadedMesh();
  20739. delete mesh._shouldGenerateFlatShading;
  20740. }
  20741. // Update
  20742. mesh.computeWorldMatrix(true);
  20743. // Octree
  20744. if (scene._selectionOctree) {
  20745. scene._selectionOctree.addMesh(mesh);
  20746. }
  20747. };
  20748. BABYLON.SceneLoader.RegisterPlugin({
  20749. extensions: ".babylon",
  20750. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20751. var parsedData = JSON.parse(data);
  20752. var loadedSkeletonsIds = [];
  20753. var loadedMaterialsIds = [];
  20754. var hierarchyIds = [];
  20755. for (var index = 0; index < parsedData.meshes.length; index++) {
  20756. var parsedMesh = parsedData.meshes[index];
  20757. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20758. if (meshesNames instanceof Array) {
  20759. // Remove found mesh name from list.
  20760. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20761. }
  20762. // Material ?
  20763. if (parsedMesh.materialId) {
  20764. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20765. if (!materialFound) {
  20766. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20767. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20768. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20769. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20770. var subMatId = parsedMultiMaterial.materials[matIndex];
  20771. loadedMaterialsIds.push(subMatId);
  20772. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20773. }
  20774. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20775. parseMultiMaterial(parsedMultiMaterial, scene);
  20776. materialFound = true;
  20777. break;
  20778. }
  20779. }
  20780. }
  20781. if (!materialFound) {
  20782. loadedMaterialsIds.push(parsedMesh.materialId);
  20783. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  20784. }
  20785. }
  20786. // Skeleton ?
  20787. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20788. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20789. if (!skeletonAlreadyLoaded) {
  20790. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20791. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20792. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20793. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20794. loadedSkeletonsIds.push(parsedSkeleton.id);
  20795. }
  20796. }
  20797. }
  20798. }
  20799. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20800. meshes.push(mesh);
  20801. }
  20802. }
  20803. for (index = 0; index < scene.meshes.length; index++) {
  20804. var currentMesh = scene.meshes[index];
  20805. if (currentMesh._waitingParentId) {
  20806. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20807. currentMesh._waitingParentId = undefined;
  20808. }
  20809. }
  20810. // Particles
  20811. if (parsedData.particleSystems) {
  20812. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20813. var parsedParticleSystem = parsedData.particleSystems[index];
  20814. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20815. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20816. }
  20817. }
  20818. }
  20819. return true;
  20820. },
  20821. load: function (scene, data, rootUrl) {
  20822. var parsedData = JSON.parse(data);
  20823. // Scene
  20824. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20825. scene.autoClear = parsedData.autoClear;
  20826. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20827. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20828. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20829. // Fog
  20830. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20831. scene.fogMode = parsedData.fogMode;
  20832. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20833. scene.fogStart = parsedData.fogStart;
  20834. scene.fogEnd = parsedData.fogEnd;
  20835. scene.fogDensity = parsedData.fogDensity;
  20836. }
  20837. for (var index = 0; index < parsedData.lights.length; index++) {
  20838. var parsedLight = parsedData.lights[index];
  20839. parseLight(parsedLight, scene);
  20840. }
  20841. // Materials
  20842. if (parsedData.materials) {
  20843. for (index = 0; index < parsedData.materials.length; index++) {
  20844. var parsedMaterial = parsedData.materials[index];
  20845. parseMaterial(parsedMaterial, scene, rootUrl);
  20846. }
  20847. }
  20848. if (parsedData.multiMaterials) {
  20849. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20850. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20851. parseMultiMaterial(parsedMultiMaterial, scene);
  20852. }
  20853. }
  20854. // Skeletons
  20855. if (parsedData.skeletons) {
  20856. for (index = 0; index < parsedData.skeletons.length; index++) {
  20857. var parsedSkeleton = parsedData.skeletons[index];
  20858. parseSkeleton(parsedSkeleton, scene);
  20859. }
  20860. }
  20861. // Geometries
  20862. var geometries = parsedData.geometries;
  20863. if (geometries) {
  20864. // Boxes
  20865. var boxes = geometries.boxes;
  20866. if (boxes) {
  20867. for (index = 0; index < boxes.length; index++) {
  20868. var parsedBox = boxes[index];
  20869. parseBox(parsedBox, scene);
  20870. }
  20871. }
  20872. // Spheres
  20873. var spheres = geometries.spheres;
  20874. if (spheres) {
  20875. for (index = 0; index < spheres.length; index++) {
  20876. var parsedSphere = spheres[index];
  20877. parseSphere(parsedSphere, scene);
  20878. }
  20879. }
  20880. // Cylinders
  20881. var cylinders = geometries.cylinders;
  20882. if (cylinders) {
  20883. for (index = 0; index < cylinders.length; index++) {
  20884. var parsedCylinder = cylinders[index];
  20885. parseCylinder(parsedCylinder, scene);
  20886. }
  20887. }
  20888. // Toruses
  20889. var toruses = geometries.toruses;
  20890. if (toruses) {
  20891. for (index = 0; index < toruses.length; index++) {
  20892. var parsedTorus = toruses[index];
  20893. parseTorus(parsedTorus, scene);
  20894. }
  20895. }
  20896. // Grounds
  20897. var grounds = geometries.grounds;
  20898. if (grounds) {
  20899. for (index = 0; index < grounds.length; index++) {
  20900. var parsedGround = grounds[index];
  20901. parseGround(parsedGround, scene);
  20902. }
  20903. }
  20904. // Planes
  20905. var planes = geometries.planes;
  20906. if (planes) {
  20907. for (index = 0; index < planes.length; index++) {
  20908. var parsedPlane = planes[index];
  20909. parsePlane(parsedPlane, scene);
  20910. }
  20911. }
  20912. // TorusKnots
  20913. var torusKnots = geometries.torusKnots;
  20914. if (torusKnots) {
  20915. for (index = 0; index < torusKnots.length; index++) {
  20916. var parsedTorusKnot = torusKnots[index];
  20917. parseTorusKnot(parsedTorusKnot, scene);
  20918. }
  20919. }
  20920. // VertexData
  20921. var vertexData = geometries.vertexData;
  20922. if (vertexData) {
  20923. for (index = 0; index < vertexData.length; index++) {
  20924. var parsedVertexData = vertexData[index];
  20925. parseVertexData(parsedVertexData, scene, rootUrl);
  20926. }
  20927. }
  20928. }
  20929. for (index = 0; index < parsedData.meshes.length; index++) {
  20930. var parsedMesh = parsedData.meshes[index];
  20931. parseMesh(parsedMesh, scene, rootUrl);
  20932. }
  20933. for (index = 0; index < parsedData.cameras.length; index++) {
  20934. var parsedCamera = parsedData.cameras[index];
  20935. parseCamera(parsedCamera, scene);
  20936. }
  20937. if (parsedData.activeCameraID) {
  20938. scene.setActiveCameraByID(parsedData.activeCameraID);
  20939. }
  20940. for (index = 0; index < scene.cameras.length; index++) {
  20941. var camera = scene.cameras[index];
  20942. if (camera._waitingParentId) {
  20943. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20944. camera._waitingParentId = undefined;
  20945. }
  20946. }
  20947. for (index = 0; index < scene.lights.length; index++) {
  20948. var light = scene.lights[index];
  20949. if (light._waitingParentId) {
  20950. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20951. light._waitingParentId = undefined;
  20952. }
  20953. }
  20954. // Sounds
  20955. if (parsedData.sounds) {
  20956. for (index = 0; index < parsedData.sounds.length; index++) {
  20957. var parsedSound = parsedData.sounds[index];
  20958. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20959. parseSound(parsedSound, scene, rootUrl);
  20960. }
  20961. else {
  20962. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20963. }
  20964. }
  20965. }
  20966. for (index = 0; index < scene.meshes.length; index++) {
  20967. var mesh = scene.meshes[index];
  20968. if (mesh._waitingParentId) {
  20969. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20970. mesh._waitingParentId = undefined;
  20971. }
  20972. if (mesh._waitingActions) {
  20973. parseActions(mesh._waitingActions, mesh, scene);
  20974. mesh._waitingActions = undefined;
  20975. }
  20976. }
  20977. // Particles Systems
  20978. if (parsedData.particleSystems) {
  20979. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20980. var parsedParticleSystem = parsedData.particleSystems[index];
  20981. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20982. }
  20983. }
  20984. // Lens flares
  20985. if (parsedData.lensFlareSystems) {
  20986. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20987. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20988. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20989. }
  20990. }
  20991. // Shadows
  20992. if (parsedData.shadowGenerators) {
  20993. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20994. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20995. parseShadowGenerator(parsedShadowGenerator, scene);
  20996. }
  20997. }
  20998. // Actions (scene)
  20999. if (parsedData.actions) {
  21000. parseActions(parsedData.actions, null, scene);
  21001. }
  21002. // Finish
  21003. return true;
  21004. }
  21005. });
  21006. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21007. })(BABYLON || (BABYLON = {}));
  21008. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  21009. (function (BABYLON) {
  21010. // Unique ID when we import meshes from Babylon to CSG
  21011. var currentCSGMeshId = 0;
  21012. // # class Vertex
  21013. // Represents a vertex of a polygon. Use your own vertex class instead of this
  21014. // one to provide additional features like texture coordinates and vertex
  21015. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  21016. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  21017. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  21018. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  21019. // is not used anywhere else.
  21020. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  21021. var Vertex = (function () {
  21022. function Vertex(pos, normal, uv) {
  21023. this.pos = pos;
  21024. this.normal = normal;
  21025. this.uv = uv;
  21026. }
  21027. Vertex.prototype.clone = function () {
  21028. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  21029. };
  21030. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  21031. // orientation of a polygon is flipped.
  21032. Vertex.prototype.flip = function () {
  21033. this.normal = this.normal.scale(-1);
  21034. };
  21035. // Create a new vertex between this vertex and `other` by linearly
  21036. // interpolating all properties using a parameter of `t`. Subclasses should
  21037. // override this to interpolate additional properties.
  21038. Vertex.prototype.interpolate = function (other, t) {
  21039. 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));
  21040. };
  21041. return Vertex;
  21042. })();
  21043. // # class Plane
  21044. // Represents a plane in 3D space.
  21045. var Plane = (function () {
  21046. function Plane(normal, w) {
  21047. this.normal = normal;
  21048. this.w = w;
  21049. }
  21050. Plane.FromPoints = function (a, b, c) {
  21051. var v0 = c.subtract(a);
  21052. var v1 = b.subtract(a);
  21053. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  21054. return null;
  21055. }
  21056. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  21057. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  21058. };
  21059. Plane.prototype.clone = function () {
  21060. return new Plane(this.normal.clone(), this.w);
  21061. };
  21062. Plane.prototype.flip = function () {
  21063. this.normal.scaleInPlace(-1);
  21064. this.w = -this.w;
  21065. };
  21066. // Split `polygon` by this plane if needed, then put the polygon or polygon
  21067. // fragments in the appropriate lists. Coplanar polygons go into either
  21068. // `coplanarFront` or `coplanarBack` depending on their orientation with
  21069. // respect to this plane. Polygons in front or in back of this plane go into
  21070. // either `front` or `back`.
  21071. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  21072. var COPLANAR = 0;
  21073. var FRONT = 1;
  21074. var BACK = 2;
  21075. var SPANNING = 3;
  21076. // Classify each point as well as the entire polygon into one of the above
  21077. // four classes.
  21078. var polygonType = 0;
  21079. var types = [];
  21080. for (var i = 0; i < polygon.vertices.length; i++) {
  21081. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  21082. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  21083. polygonType |= type;
  21084. types.push(type);
  21085. }
  21086. switch (polygonType) {
  21087. case COPLANAR:
  21088. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  21089. break;
  21090. case FRONT:
  21091. front.push(polygon);
  21092. break;
  21093. case BACK:
  21094. back.push(polygon);
  21095. break;
  21096. case SPANNING:
  21097. var f = [], b = [];
  21098. for (i = 0; i < polygon.vertices.length; i++) {
  21099. var j = (i + 1) % polygon.vertices.length;
  21100. var ti = types[i], tj = types[j];
  21101. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  21102. if (ti != BACK)
  21103. f.push(vi);
  21104. if (ti != FRONT)
  21105. b.push(ti != BACK ? vi.clone() : vi);
  21106. if ((ti | tj) == SPANNING) {
  21107. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  21108. var v = vi.interpolate(vj, t);
  21109. f.push(v);
  21110. b.push(v.clone());
  21111. }
  21112. }
  21113. if (f.length >= 3) {
  21114. var poly = new Polygon(f, polygon.shared);
  21115. if (poly.plane)
  21116. front.push(poly);
  21117. }
  21118. if (b.length >= 3) {
  21119. poly = new Polygon(b, polygon.shared);
  21120. if (poly.plane)
  21121. back.push(poly);
  21122. }
  21123. break;
  21124. }
  21125. };
  21126. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  21127. // point is on the plane.
  21128. Plane.EPSILON = 1e-5;
  21129. return Plane;
  21130. })();
  21131. // # class Polygon
  21132. // Represents a convex polygon. The vertices used to initialize a polygon must
  21133. // be coplanar and form a convex loop.
  21134. //
  21135. // Each convex polygon has a `shared` property, which is shared between all
  21136. // polygons that are clones of each other or were split from the same polygon.
  21137. // This can be used to define per-polygon properties (such as surface color).
  21138. var Polygon = (function () {
  21139. function Polygon(vertices, shared) {
  21140. this.vertices = vertices;
  21141. this.shared = shared;
  21142. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  21143. }
  21144. Polygon.prototype.clone = function () {
  21145. var vertices = this.vertices.map(function (v) { return v.clone(); });
  21146. return new Polygon(vertices, this.shared);
  21147. };
  21148. Polygon.prototype.flip = function () {
  21149. this.vertices.reverse().map(function (v) {
  21150. v.flip();
  21151. });
  21152. this.plane.flip();
  21153. };
  21154. return Polygon;
  21155. })();
  21156. // # class Node
  21157. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  21158. // by picking a polygon to split along. That polygon (and all other coplanar
  21159. // polygons) are added directly to that node and the other polygons are added to
  21160. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  21161. // no distinction between internal and leaf nodes.
  21162. var Node = (function () {
  21163. function Node(polygons) {
  21164. this.plane = null;
  21165. this.front = null;
  21166. this.back = null;
  21167. this.polygons = [];
  21168. if (polygons) {
  21169. this.build(polygons);
  21170. }
  21171. }
  21172. Node.prototype.clone = function () {
  21173. var node = new Node();
  21174. node.plane = this.plane && this.plane.clone();
  21175. node.front = this.front && this.front.clone();
  21176. node.back = this.back && this.back.clone();
  21177. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  21178. return node;
  21179. };
  21180. // Convert solid space to empty space and empty space to solid space.
  21181. Node.prototype.invert = function () {
  21182. for (var i = 0; i < this.polygons.length; i++) {
  21183. this.polygons[i].flip();
  21184. }
  21185. if (this.plane) {
  21186. this.plane.flip();
  21187. }
  21188. if (this.front) {
  21189. this.front.invert();
  21190. }
  21191. if (this.back) {
  21192. this.back.invert();
  21193. }
  21194. var temp = this.front;
  21195. this.front = this.back;
  21196. this.back = temp;
  21197. };
  21198. // Recursively remove all polygons in `polygons` that are inside this BSP
  21199. // tree.
  21200. Node.prototype.clipPolygons = function (polygons) {
  21201. if (!this.plane)
  21202. return polygons.slice();
  21203. var front = [], back = [];
  21204. for (var i = 0; i < polygons.length; i++) {
  21205. this.plane.splitPolygon(polygons[i], front, back, front, back);
  21206. }
  21207. if (this.front) {
  21208. front = this.front.clipPolygons(front);
  21209. }
  21210. if (this.back) {
  21211. back = this.back.clipPolygons(back);
  21212. }
  21213. else {
  21214. back = [];
  21215. }
  21216. return front.concat(back);
  21217. };
  21218. // Remove all polygons in this BSP tree that are inside the other BSP tree
  21219. // `bsp`.
  21220. Node.prototype.clipTo = function (bsp) {
  21221. this.polygons = bsp.clipPolygons(this.polygons);
  21222. if (this.front)
  21223. this.front.clipTo(bsp);
  21224. if (this.back)
  21225. this.back.clipTo(bsp);
  21226. };
  21227. // Return a list of all polygons in this BSP tree.
  21228. Node.prototype.allPolygons = function () {
  21229. var polygons = this.polygons.slice();
  21230. if (this.front)
  21231. polygons = polygons.concat(this.front.allPolygons());
  21232. if (this.back)
  21233. polygons = polygons.concat(this.back.allPolygons());
  21234. return polygons;
  21235. };
  21236. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  21237. // new polygons are filtered down to the bottom of the tree and become new
  21238. // nodes there. Each set of polygons is partitioned using the first polygon
  21239. // (no heuristic is used to pick a good split).
  21240. Node.prototype.build = function (polygons) {
  21241. if (!polygons.length)
  21242. return;
  21243. if (!this.plane)
  21244. this.plane = polygons[0].plane.clone();
  21245. var front = [], back = [];
  21246. for (var i = 0; i < polygons.length; i++) {
  21247. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  21248. }
  21249. if (front.length) {
  21250. if (!this.front)
  21251. this.front = new Node();
  21252. this.front.build(front);
  21253. }
  21254. if (back.length) {
  21255. if (!this.back)
  21256. this.back = new Node();
  21257. this.back.build(back);
  21258. }
  21259. };
  21260. return Node;
  21261. })();
  21262. var CSG = (function () {
  21263. function CSG() {
  21264. this.polygons = new Array();
  21265. }
  21266. // Convert BABYLON.Mesh to BABYLON.CSG
  21267. CSG.FromMesh = function (mesh) {
  21268. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  21269. if (mesh instanceof BABYLON.Mesh) {
  21270. mesh.computeWorldMatrix(true);
  21271. var matrix = mesh.getWorldMatrix();
  21272. var meshPosition = mesh.position.clone();
  21273. var meshRotation = mesh.rotation.clone();
  21274. var meshScaling = mesh.scaling.clone();
  21275. }
  21276. else {
  21277. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  21278. }
  21279. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21280. var subMeshes = mesh.subMeshes;
  21281. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  21282. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  21283. vertices = [];
  21284. for (var j = 0; j < 3; j++) {
  21285. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  21286. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  21287. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  21288. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  21289. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  21290. vertex = new Vertex(position, normal, uv);
  21291. vertices.push(vertex);
  21292. }
  21293. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  21294. // To handle the case of degenerated triangle
  21295. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  21296. if (polygon.plane)
  21297. polygons.push(polygon);
  21298. }
  21299. }
  21300. var csg = CSG.FromPolygons(polygons);
  21301. csg.matrix = matrix;
  21302. csg.position = meshPosition;
  21303. csg.rotation = meshRotation;
  21304. csg.scaling = meshScaling;
  21305. currentCSGMeshId++;
  21306. return csg;
  21307. };
  21308. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  21309. CSG.FromPolygons = function (polygons) {
  21310. var csg = new BABYLON.CSG();
  21311. csg.polygons = polygons;
  21312. return csg;
  21313. };
  21314. CSG.prototype.clone = function () {
  21315. var csg = new BABYLON.CSG();
  21316. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  21317. csg.copyTransformAttributes(this);
  21318. return csg;
  21319. };
  21320. CSG.prototype.toPolygons = function () {
  21321. return this.polygons;
  21322. };
  21323. CSG.prototype.union = function (csg) {
  21324. var a = new Node(this.clone().polygons);
  21325. var b = new Node(csg.clone().polygons);
  21326. a.clipTo(b);
  21327. b.clipTo(a);
  21328. b.invert();
  21329. b.clipTo(a);
  21330. b.invert();
  21331. a.build(b.allPolygons());
  21332. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21333. };
  21334. CSG.prototype.unionInPlace = function (csg) {
  21335. var a = new Node(this.polygons);
  21336. var b = new Node(csg.polygons);
  21337. a.clipTo(b);
  21338. b.clipTo(a);
  21339. b.invert();
  21340. b.clipTo(a);
  21341. b.invert();
  21342. a.build(b.allPolygons());
  21343. this.polygons = a.allPolygons();
  21344. };
  21345. CSG.prototype.subtract = function (csg) {
  21346. var a = new Node(this.clone().polygons);
  21347. var b = new Node(csg.clone().polygons);
  21348. a.invert();
  21349. a.clipTo(b);
  21350. b.clipTo(a);
  21351. b.invert();
  21352. b.clipTo(a);
  21353. b.invert();
  21354. a.build(b.allPolygons());
  21355. a.invert();
  21356. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21357. };
  21358. CSG.prototype.subtractInPlace = function (csg) {
  21359. var a = new Node(this.polygons);
  21360. var b = new Node(csg.polygons);
  21361. a.invert();
  21362. a.clipTo(b);
  21363. b.clipTo(a);
  21364. b.invert();
  21365. b.clipTo(a);
  21366. b.invert();
  21367. a.build(b.allPolygons());
  21368. a.invert();
  21369. this.polygons = a.allPolygons();
  21370. };
  21371. CSG.prototype.intersect = function (csg) {
  21372. var a = new Node(this.clone().polygons);
  21373. var b = new Node(csg.clone().polygons);
  21374. a.invert();
  21375. b.clipTo(a);
  21376. b.invert();
  21377. a.clipTo(b);
  21378. b.clipTo(a);
  21379. a.build(b.allPolygons());
  21380. a.invert();
  21381. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21382. };
  21383. CSG.prototype.intersectInPlace = function (csg) {
  21384. var a = new Node(this.polygons);
  21385. var b = new Node(csg.polygons);
  21386. a.invert();
  21387. b.clipTo(a);
  21388. b.invert();
  21389. a.clipTo(b);
  21390. b.clipTo(a);
  21391. a.build(b.allPolygons());
  21392. a.invert();
  21393. this.polygons = a.allPolygons();
  21394. };
  21395. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  21396. // not modified.
  21397. CSG.prototype.inverse = function () {
  21398. var csg = this.clone();
  21399. csg.inverseInPlace();
  21400. return csg;
  21401. };
  21402. CSG.prototype.inverseInPlace = function () {
  21403. this.polygons.map(function (p) {
  21404. p.flip();
  21405. });
  21406. };
  21407. // This is used to keep meshes transformations so they can be restored
  21408. // when we build back a Babylon Mesh
  21409. // NB : All CSG operations are performed in world coordinates
  21410. CSG.prototype.copyTransformAttributes = function (csg) {
  21411. this.matrix = csg.matrix;
  21412. this.position = csg.position;
  21413. this.rotation = csg.rotation;
  21414. this.scaling = csg.scaling;
  21415. return this;
  21416. };
  21417. // Build Raw mesh from CSG
  21418. // Coordinates here are in world space
  21419. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  21420. var matrix = this.matrix.clone();
  21421. matrix.invert();
  21422. 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;
  21423. if (keepSubMeshes) {
  21424. // Sort Polygons, since subMeshes are indices range
  21425. polygons.sort(function (a, b) {
  21426. if (a.shared.meshId === b.shared.meshId) {
  21427. return a.shared.subMeshId - b.shared.subMeshId;
  21428. }
  21429. else {
  21430. return a.shared.meshId - b.shared.meshId;
  21431. }
  21432. });
  21433. }
  21434. for (var i = 0, il = polygons.length; i < il; i++) {
  21435. polygon = polygons[i];
  21436. // Building SubMeshes
  21437. if (!subMesh_dict[polygon.shared.meshId]) {
  21438. subMesh_dict[polygon.shared.meshId] = {};
  21439. }
  21440. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  21441. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  21442. indexStart: +Infinity,
  21443. indexEnd: -Infinity,
  21444. materialIndex: polygon.shared.materialIndex
  21445. };
  21446. }
  21447. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  21448. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  21449. polygonIndices[0] = 0;
  21450. polygonIndices[1] = j - 1;
  21451. polygonIndices[2] = j;
  21452. for (var k = 0; k < 3; k++) {
  21453. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  21454. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  21455. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  21456. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  21457. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  21458. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  21459. // Check if 2 points can be merged
  21460. 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)) {
  21461. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  21462. uvs.push(uv.x, uv.y);
  21463. normals.push(normal.x, normal.y, normal.z);
  21464. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  21465. }
  21466. indices.push(vertex_idx);
  21467. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  21468. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  21469. currentIndex++;
  21470. }
  21471. }
  21472. }
  21473. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  21474. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21475. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  21476. mesh.setIndices(indices);
  21477. if (keepSubMeshes) {
  21478. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  21479. var materialIndexOffset = 0, materialMaxIndex;
  21480. mesh.subMeshes.length = 0;
  21481. for (var m in subMesh_dict) {
  21482. materialMaxIndex = -1;
  21483. for (var sm in subMesh_dict[m]) {
  21484. subMesh_obj = subMesh_dict[m][sm];
  21485. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  21486. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  21487. }
  21488. materialIndexOffset += ++materialMaxIndex;
  21489. }
  21490. }
  21491. return mesh;
  21492. };
  21493. // Build Mesh from CSG taking material and transforms into account
  21494. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  21495. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  21496. mesh.material = material;
  21497. mesh.position.copyFrom(this.position);
  21498. mesh.rotation.copyFrom(this.rotation);
  21499. mesh.scaling.copyFrom(this.scaling);
  21500. mesh.computeWorldMatrix(true);
  21501. return mesh;
  21502. };
  21503. return CSG;
  21504. })();
  21505. BABYLON.CSG = CSG;
  21506. })(BABYLON || (BABYLON = {}));
  21507. //# sourceMappingURL=babylon.csg.js.map
  21508. var BABYLON;
  21509. (function (BABYLON) {
  21510. var OculusDistortionCorrectionPostProcess = (function (_super) {
  21511. __extends(OculusDistortionCorrectionPostProcess, _super);
  21512. //ANY
  21513. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  21514. var _this = this;
  21515. _super.call(this, name, "oculusDistortionCorrection", [
  21516. 'LensCenter',
  21517. 'Scale',
  21518. 'ScaleIn',
  21519. 'HmdWarpParam'
  21520. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  21521. this._isRightEye = isRightEye;
  21522. this._distortionFactors = cameraSettings.DistortionK;
  21523. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  21524. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  21525. this.onSizeChanged = function () {
  21526. _this.aspectRatio = _this.width * .5 / _this.height;
  21527. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  21528. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  21529. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  21530. };
  21531. this.onApply = function (effect) {
  21532. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  21533. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  21534. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  21535. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  21536. };
  21537. }
  21538. return OculusDistortionCorrectionPostProcess;
  21539. })(BABYLON.PostProcess);
  21540. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  21541. })(BABYLON || (BABYLON = {}));
  21542. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  21543. // 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
  21544. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  21545. var BABYLON;
  21546. (function (BABYLON) {
  21547. (function (JoystickAxis) {
  21548. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  21549. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  21550. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  21551. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  21552. var JoystickAxis = BABYLON.JoystickAxis;
  21553. var VirtualJoystick = (function () {
  21554. function VirtualJoystick(leftJoystick) {
  21555. var _this = this;
  21556. if (leftJoystick) {
  21557. this._leftJoystick = true;
  21558. }
  21559. else {
  21560. this._leftJoystick = false;
  21561. }
  21562. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  21563. VirtualJoystick._globalJoystickIndex++;
  21564. // By default left & right arrow keys are moving the X
  21565. // and up & down keys are moving the Y
  21566. this._axisTargetedByLeftAndRight = 0 /* X */;
  21567. this._axisTargetedByUpAndDown = 1 /* Y */;
  21568. this.reverseLeftRight = false;
  21569. this.reverseUpDown = false;
  21570. // collections of pointers
  21571. this._touches = new BABYLON.SmartCollection();
  21572. this.deltaPosition = BABYLON.Vector3.Zero();
  21573. this._joystickSensibility = 25;
  21574. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21575. this._rotationSpeed = 25;
  21576. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  21577. this._rotateOnAxisRelativeToMesh = false;
  21578. // injecting a canvas element on top of the canvas 3D game
  21579. if (!VirtualJoystick.vjCanvas) {
  21580. window.addEventListener("resize", function () {
  21581. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21582. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21583. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  21584. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  21585. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  21586. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  21587. }, false);
  21588. VirtualJoystick.vjCanvas = document.createElement("canvas");
  21589. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21590. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21591. VirtualJoystick.vjCanvas.width = window.innerWidth;
  21592. VirtualJoystick.vjCanvas.height = window.innerHeight;
  21593. VirtualJoystick.vjCanvas.style.width = "100%";
  21594. VirtualJoystick.vjCanvas.style.height = "100%";
  21595. VirtualJoystick.vjCanvas.style.position = "absolute";
  21596. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  21597. VirtualJoystick.vjCanvas.style.top = "0px";
  21598. VirtualJoystick.vjCanvas.style.left = "0px";
  21599. VirtualJoystick.vjCanvas.style.zIndex = "5";
  21600. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  21601. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  21602. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  21603. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21604. document.body.appendChild(VirtualJoystick.vjCanvas);
  21605. }
  21606. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  21607. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  21608. this.pressed = false;
  21609. // default joystick color
  21610. this._joystickColor = "cyan";
  21611. this._joystickPointerID = -1;
  21612. // current joystick position
  21613. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  21614. // origin joystick position
  21615. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  21616. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  21617. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  21618. _this._onPointerDown(evt);
  21619. }, false);
  21620. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  21621. _this._onPointerMove(evt);
  21622. }, false);
  21623. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  21624. _this._onPointerUp(evt);
  21625. }, false);
  21626. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  21627. _this._onPointerUp(evt);
  21628. }, false);
  21629. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  21630. evt.preventDefault(); // Disables system menu
  21631. }, false);
  21632. requestAnimationFrame(function () {
  21633. _this._drawVirtualJoystick();
  21634. });
  21635. }
  21636. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  21637. this._joystickSensibility = newJoystickSensibility;
  21638. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21639. };
  21640. VirtualJoystick.prototype._onPointerDown = function (e) {
  21641. var positionOnScreenCondition;
  21642. e.preventDefault();
  21643. if (this._leftJoystick === true) {
  21644. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  21645. }
  21646. else {
  21647. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  21648. }
  21649. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  21650. // First contact will be dedicated to the virtual joystick
  21651. this._joystickPointerID = e.pointerId;
  21652. this._joystickPointerStartPos.x = e.clientX;
  21653. this._joystickPointerStartPos.y = e.clientY;
  21654. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  21655. this._deltaJoystickVector.x = 0;
  21656. this._deltaJoystickVector.y = 0;
  21657. this.pressed = true;
  21658. this._touches.add(e.pointerId.toString(), e);
  21659. }
  21660. else {
  21661. // You can only trigger the action buttons with a joystick declared
  21662. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  21663. this._action();
  21664. this._touches.add(e.pointerId.toString(), e);
  21665. }
  21666. }
  21667. };
  21668. VirtualJoystick.prototype._onPointerMove = function (e) {
  21669. // If the current pointer is the one associated to the joystick (first touch contact)
  21670. if (this._joystickPointerID == e.pointerId) {
  21671. this._joystickPointerPos.x = e.clientX;
  21672. this._joystickPointerPos.y = e.clientY;
  21673. this._deltaJoystickVector = this._joystickPointerPos.clone();
  21674. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  21675. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  21676. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  21677. switch (this._axisTargetedByLeftAndRight) {
  21678. case 0 /* X */:
  21679. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  21680. break;
  21681. case 1 /* Y */:
  21682. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  21683. break;
  21684. case 2 /* Z */:
  21685. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  21686. break;
  21687. }
  21688. var directionUpDown = this.reverseUpDown ? 1 : -1;
  21689. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  21690. switch (this._axisTargetedByUpAndDown) {
  21691. case 0 /* X */:
  21692. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  21693. break;
  21694. case 1 /* Y */:
  21695. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  21696. break;
  21697. case 2 /* Z */:
  21698. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  21699. break;
  21700. }
  21701. }
  21702. else {
  21703. if (this._touches.item(e.pointerId.toString())) {
  21704. this._touches.item(e.pointerId.toString()).x = e.clientX;
  21705. this._touches.item(e.pointerId.toString()).y = e.clientY;
  21706. }
  21707. }
  21708. };
  21709. VirtualJoystick.prototype._onPointerUp = function (e) {
  21710. this._clearCanvas();
  21711. if (this._joystickPointerID == e.pointerId) {
  21712. this._joystickPointerID = -1;
  21713. this.pressed = false;
  21714. }
  21715. this._deltaJoystickVector.x = 0;
  21716. this._deltaJoystickVector.y = 0;
  21717. this._touches.remove(e.pointerId.toString());
  21718. };
  21719. /**
  21720. * Change the color of the virtual joystick
  21721. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  21722. */
  21723. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  21724. this._joystickColor = newColor;
  21725. };
  21726. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  21727. this._action = action;
  21728. };
  21729. // Define which axis you'd like to control for left & right
  21730. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  21731. switch (axis) {
  21732. case 0 /* X */:
  21733. case 1 /* Y */:
  21734. case 2 /* Z */:
  21735. this._axisTargetedByLeftAndRight = axis;
  21736. break;
  21737. default:
  21738. this._axisTargetedByLeftAndRight = 0 /* X */;
  21739. break;
  21740. }
  21741. };
  21742. // Define which axis you'd like to control for up & down
  21743. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  21744. switch (axis) {
  21745. case 0 /* X */:
  21746. case 1 /* Y */:
  21747. case 2 /* Z */:
  21748. this._axisTargetedByUpAndDown = axis;
  21749. break;
  21750. default:
  21751. this._axisTargetedByUpAndDown = 1 /* Y */;
  21752. break;
  21753. }
  21754. };
  21755. VirtualJoystick.prototype._clearCanvas = function () {
  21756. if (this._leftJoystick) {
  21757. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  21758. }
  21759. else {
  21760. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  21761. }
  21762. };
  21763. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  21764. var _this = this;
  21765. if (this.pressed) {
  21766. this._clearCanvas();
  21767. this._touches.forEach(function (touch) {
  21768. if (touch.pointerId === _this._joystickPointerID) {
  21769. VirtualJoystick.vjCanvasContext.beginPath();
  21770. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21771. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21772. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  21773. VirtualJoystick.vjCanvasContext.stroke();
  21774. VirtualJoystick.vjCanvasContext.beginPath();
  21775. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21776. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21777. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  21778. VirtualJoystick.vjCanvasContext.stroke();
  21779. VirtualJoystick.vjCanvasContext.beginPath();
  21780. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21781. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  21782. VirtualJoystick.vjCanvasContext.stroke();
  21783. }
  21784. else {
  21785. VirtualJoystick.vjCanvasContext.beginPath();
  21786. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  21787. VirtualJoystick.vjCanvasContext.beginPath();
  21788. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  21789. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21790. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  21791. VirtualJoystick.vjCanvasContext.stroke();
  21792. }
  21793. ;
  21794. });
  21795. }
  21796. requestAnimationFrame(function () {
  21797. _this._drawVirtualJoystick();
  21798. });
  21799. };
  21800. VirtualJoystick.prototype.releaseCanvas = function () {
  21801. if (VirtualJoystick.vjCanvas) {
  21802. document.body.removeChild(VirtualJoystick.vjCanvas);
  21803. VirtualJoystick.vjCanvas = null;
  21804. }
  21805. };
  21806. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  21807. VirtualJoystick._globalJoystickIndex = 0;
  21808. return VirtualJoystick;
  21809. })();
  21810. BABYLON.VirtualJoystick = VirtualJoystick;
  21811. })(BABYLON || (BABYLON = {}));
  21812. //# sourceMappingURL=babylon.virtualJoystick.js.map
  21813. var BABYLON;
  21814. (function (BABYLON) {
  21815. var OculusRiftDevKit2013_Metric = {
  21816. HResolution: 1280,
  21817. VResolution: 800,
  21818. HScreenSize: 0.149759993,
  21819. VScreenSize: 0.0935999975,
  21820. VScreenCenter: 0.0467999987,
  21821. EyeToScreenDistance: 0.0410000011,
  21822. LensSeparationDistance: 0.0635000020,
  21823. InterpupillaryDistance: 0.0640000030,
  21824. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21825. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21826. PostProcessScaleFactor: 1.714605507808412,
  21827. LensCenterOffset: 0.151976421
  21828. };
  21829. var _OculusInnerCamera = (function (_super) {
  21830. __extends(_OculusInnerCamera, _super);
  21831. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  21832. _super.call(this, name, position, scene);
  21833. this._workMatrix = new BABYLON.Matrix();
  21834. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21835. // Constants
  21836. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21837. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21838. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21839. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21840. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21841. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21842. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21843. // Postprocess
  21844. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21845. }
  21846. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  21847. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21848. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21849. return this._projectionMatrix;
  21850. };
  21851. _OculusInnerCamera.prototype._getViewMatrix = function () {
  21852. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21853. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21854. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21855. // Computing target and final matrix
  21856. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21857. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21858. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21859. return this._viewMatrix;
  21860. };
  21861. return _OculusInnerCamera;
  21862. })(BABYLON.FreeCamera);
  21863. var OculusCamera = (function (_super) {
  21864. __extends(OculusCamera, _super);
  21865. function OculusCamera(name, position, scene) {
  21866. _super.call(this, name, position, scene);
  21867. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  21868. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  21869. this.subCameras.push(this._leftCamera);
  21870. this.subCameras.push(this._rightCamera);
  21871. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21872. }
  21873. OculusCamera.prototype._update = function () {
  21874. this._leftCamera.position.copyFrom(this.position);
  21875. this._rightCamera.position.copyFrom(this.position);
  21876. this._updateCamera(this._leftCamera);
  21877. this._updateCamera(this._rightCamera);
  21878. _super.prototype._update.call(this);
  21879. };
  21880. OculusCamera.prototype._updateCamera = function (camera) {
  21881. camera.minZ = this.minZ;
  21882. camera.maxZ = this.maxZ;
  21883. camera.rotation.x = this.rotation.x;
  21884. camera.rotation.y = this.rotation.y;
  21885. camera.rotation.z = this.rotation.z;
  21886. };
  21887. // Oculus events
  21888. OculusCamera.prototype._onOrientationEvent = function (evt) {
  21889. var yaw = evt.alpha / 180 * Math.PI;
  21890. var pitch = evt.beta / 180 * Math.PI;
  21891. var roll = evt.gamma / 180 * Math.PI;
  21892. if (!this._offsetOrientation) {
  21893. this._offsetOrientation = {
  21894. yaw: yaw,
  21895. pitch: pitch,
  21896. roll: roll
  21897. };
  21898. return;
  21899. }
  21900. else {
  21901. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21902. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21903. this.rotation.z += this._offsetOrientation.roll - roll;
  21904. this._offsetOrientation.yaw = yaw;
  21905. this._offsetOrientation.pitch = pitch;
  21906. this._offsetOrientation.roll = roll;
  21907. }
  21908. };
  21909. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  21910. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21911. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21912. };
  21913. OculusCamera.prototype.detachControl = function (element) {
  21914. _super.prototype.detachControl.call(this, element);
  21915. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21916. };
  21917. return OculusCamera;
  21918. })(BABYLON.FreeCamera);
  21919. BABYLON.OculusCamera = OculusCamera;
  21920. })(BABYLON || (BABYLON = {}));
  21921. //# sourceMappingURL=babylon.oculusCamera.js.map
  21922. var BABYLON;
  21923. (function (BABYLON) {
  21924. var OculusRiftDevKit2013_Metric = {
  21925. HResolution: 1280,
  21926. VResolution: 800,
  21927. HScreenSize: 0.149759993,
  21928. VScreenSize: 0.0935999975,
  21929. VScreenCenter: 0.0467999987,
  21930. EyeToScreenDistance: 0.0410000011,
  21931. LensSeparationDistance: 0.0635000020,
  21932. InterpupillaryDistance: 0.0640000030,
  21933. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21934. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21935. PostProcessScaleFactor: 1.714605507808412,
  21936. LensCenterOffset: 0.151976421
  21937. };
  21938. var _OculusInnerGamepadCamera = (function (_super) {
  21939. __extends(_OculusInnerGamepadCamera, _super);
  21940. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21941. _super.call(this, name, position, scene);
  21942. this._workMatrix = new BABYLON.Matrix();
  21943. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21944. // Constants
  21945. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21946. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21947. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21948. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21949. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21950. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21951. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21952. // Postprocess
  21953. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21954. }
  21955. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21956. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21957. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21958. return this._projectionMatrix;
  21959. };
  21960. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21961. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21962. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21963. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21964. // Computing target and final matrix
  21965. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21966. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21967. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21968. return this._viewMatrix;
  21969. };
  21970. return _OculusInnerGamepadCamera;
  21971. })(BABYLON.FreeCamera);
  21972. var OculusGamepadCamera = (function (_super) {
  21973. __extends(OculusGamepadCamera, _super);
  21974. function OculusGamepadCamera(name, position, scene) {
  21975. var _this = this;
  21976. _super.call(this, name, position, scene);
  21977. this.angularSensibility = 200;
  21978. this.moveSensibility = 75;
  21979. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21980. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21981. this.subCameras.push(this._leftCamera);
  21982. this.subCameras.push(this._rightCamera);
  21983. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21984. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21985. _this._onNewGameConnected(gamepad);
  21986. });
  21987. }
  21988. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21989. // Only the first gamepad can control the camera
  21990. if (gamepad.index === 0) {
  21991. this._gamepad = gamepad;
  21992. }
  21993. };
  21994. OculusGamepadCamera.prototype._update = function () {
  21995. this._leftCamera.position.copyFrom(this.position);
  21996. this._rightCamera.position.copyFrom(this.position);
  21997. this._updateCamera(this._leftCamera);
  21998. this._updateCamera(this._rightCamera);
  21999. _super.prototype._update.call(this);
  22000. };
  22001. OculusGamepadCamera.prototype._checkInputs = function () {
  22002. if (!this._gamepad) {
  22003. return;
  22004. }
  22005. var LSValues = this._gamepad.leftStick;
  22006. var normalizedLX = LSValues.x / this.moveSensibility;
  22007. var normalizedLY = LSValues.y / this.moveSensibility;
  22008. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  22009. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  22010. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  22011. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  22012. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  22013. };
  22014. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  22015. camera.minZ = this.minZ;
  22016. camera.maxZ = this.maxZ;
  22017. camera.rotation.x = this.rotation.x;
  22018. camera.rotation.y = this.rotation.y;
  22019. camera.rotation.z = this.rotation.z;
  22020. };
  22021. // Oculus events
  22022. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  22023. var yaw = evt.alpha / 180 * Math.PI;
  22024. var pitch = evt.beta / 180 * Math.PI;
  22025. var roll = evt.gamma / 180 * Math.PI;
  22026. if (!this._offsetOrientation) {
  22027. this._offsetOrientation = {
  22028. yaw: yaw,
  22029. pitch: pitch,
  22030. roll: roll
  22031. };
  22032. return;
  22033. }
  22034. else {
  22035. this.rotation.y += yaw - this._offsetOrientation.yaw;
  22036. this.rotation.x += pitch - this._offsetOrientation.pitch;
  22037. this.rotation.z += this._offsetOrientation.roll - roll;
  22038. this._offsetOrientation.yaw = yaw;
  22039. this._offsetOrientation.pitch = pitch;
  22040. this._offsetOrientation.roll = roll;
  22041. }
  22042. };
  22043. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  22044. _super.prototype.attachControl.call(this, element, noPreventDefault);
  22045. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  22046. };
  22047. OculusGamepadCamera.prototype.detachControl = function (element) {
  22048. _super.prototype.detachControl.call(this, element);
  22049. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  22050. };
  22051. OculusGamepadCamera.prototype.dispose = function () {
  22052. this._gamepads.dispose();
  22053. _super.prototype.dispose.call(this);
  22054. };
  22055. return OculusGamepadCamera;
  22056. })(BABYLON.FreeCamera);
  22057. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  22058. })(BABYLON || (BABYLON = {}));
  22059. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  22060. var BABYLON;
  22061. (function (BABYLON) {
  22062. // We're mainly based on the logic defined into the FreeCamera code
  22063. var VirtualJoysticksCamera = (function (_super) {
  22064. __extends(VirtualJoysticksCamera, _super);
  22065. function VirtualJoysticksCamera(name, position, scene) {
  22066. _super.call(this, name, position, scene);
  22067. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  22068. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  22069. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  22070. this._leftjoystick.setJoystickSensibility(0.15);
  22071. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  22072. this._rightjoystick.setAxisForUpDown(0 /* X */);
  22073. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  22074. this._rightjoystick.reverseUpDown = true;
  22075. this._rightjoystick.setJoystickSensibility(0.05);
  22076. this._rightjoystick.setJoystickColor("yellow");
  22077. }
  22078. VirtualJoysticksCamera.prototype._checkInputs = function () {
  22079. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  22080. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  22081. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  22082. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  22083. if (!this._leftjoystick.pressed) {
  22084. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  22085. }
  22086. if (!this._rightjoystick.pressed) {
  22087. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  22088. }
  22089. };
  22090. VirtualJoysticksCamera.prototype.dispose = function () {
  22091. this._leftjoystick.releaseCanvas();
  22092. _super.prototype.dispose.call(this);
  22093. };
  22094. return VirtualJoysticksCamera;
  22095. })(BABYLON.FreeCamera);
  22096. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  22097. })(BABYLON || (BABYLON = {}));
  22098. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  22099. var BABYLON;
  22100. (function (BABYLON) {
  22101. var ShaderMaterial = (function (_super) {
  22102. __extends(ShaderMaterial, _super);
  22103. function ShaderMaterial(name, scene, shaderPath, options) {
  22104. _super.call(this, name, scene);
  22105. this._textures = new Array();
  22106. this._floats = new Array();
  22107. this._floatsArrays = {};
  22108. this._colors3 = new Array();
  22109. this._colors4 = new Array();
  22110. this._vectors2 = new Array();
  22111. this._vectors3 = new Array();
  22112. this._matrices = new Array();
  22113. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  22114. this._shaderPath = shaderPath;
  22115. options.needAlphaBlending = options.needAlphaBlending || false;
  22116. options.needAlphaTesting = options.needAlphaTesting || false;
  22117. options.attributes = options.attributes || ["position", "normal", "uv"];
  22118. options.uniforms = options.uniforms || ["worldViewProjection"];
  22119. options.samplers = options.samplers || [];
  22120. this._options = options;
  22121. }
  22122. ShaderMaterial.prototype.needAlphaBlending = function () {
  22123. return this._options.needAlphaBlending;
  22124. };
  22125. ShaderMaterial.prototype.needAlphaTesting = function () {
  22126. return this._options.needAlphaTesting;
  22127. };
  22128. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  22129. if (this._options.uniforms.indexOf(uniformName) === -1) {
  22130. this._options.uniforms.push(uniformName);
  22131. }
  22132. };
  22133. ShaderMaterial.prototype.setTexture = function (name, texture) {
  22134. if (this._options.samplers.indexOf(name) === -1) {
  22135. this._options.samplers.push(name);
  22136. }
  22137. this._textures[name] = texture;
  22138. return this;
  22139. };
  22140. ShaderMaterial.prototype.setFloat = function (name, value) {
  22141. this._checkUniform(name);
  22142. this._floats[name] = value;
  22143. return this;
  22144. };
  22145. ShaderMaterial.prototype.setFloats = function (name, value) {
  22146. this._checkUniform(name);
  22147. this._floatsArrays[name] = value;
  22148. return this;
  22149. };
  22150. ShaderMaterial.prototype.setColor3 = function (name, value) {
  22151. this._checkUniform(name);
  22152. this._colors3[name] = value;
  22153. return this;
  22154. };
  22155. ShaderMaterial.prototype.setColor4 = function (name, value) {
  22156. this._checkUniform(name);
  22157. this._colors4[name] = value;
  22158. return this;
  22159. };
  22160. ShaderMaterial.prototype.setVector2 = function (name, value) {
  22161. this._checkUniform(name);
  22162. this._vectors2[name] = value;
  22163. return this;
  22164. };
  22165. ShaderMaterial.prototype.setVector3 = function (name, value) {
  22166. this._checkUniform(name);
  22167. this._vectors3[name] = value;
  22168. return this;
  22169. };
  22170. ShaderMaterial.prototype.setMatrix = function (name, value) {
  22171. this._checkUniform(name);
  22172. this._matrices[name] = value;
  22173. return this;
  22174. };
  22175. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  22176. var scene = this.getScene();
  22177. var engine = scene.getEngine();
  22178. if (!this.checkReadyOnEveryCall) {
  22179. if (this._renderId === scene.getRenderId()) {
  22180. return true;
  22181. }
  22182. }
  22183. // Instances
  22184. var defines = [];
  22185. var fallbacks = new BABYLON.EffectFallbacks();
  22186. if (useInstances) {
  22187. defines.push("#define INSTANCES");
  22188. }
  22189. // Bones
  22190. if (mesh && mesh.useBones) {
  22191. defines.push("#define BONES");
  22192. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  22193. defines.push("#define BONES4");
  22194. fallbacks.addFallback(0, "BONES4");
  22195. }
  22196. // Alpha test
  22197. if (engine.getAlphaTesting()) {
  22198. defines.push("#define ALPHATEST");
  22199. }
  22200. var previousEffect = this._effect;
  22201. var join = defines.join("\n");
  22202. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  22203. if (!this._effect.isReady()) {
  22204. return false;
  22205. }
  22206. if (previousEffect !== this._effect) {
  22207. scene.resetCachedMaterial();
  22208. }
  22209. this._renderId = scene.getRenderId();
  22210. return true;
  22211. };
  22212. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  22213. var scene = this.getScene();
  22214. if (this._options.uniforms.indexOf("world") !== -1) {
  22215. this._effect.setMatrix("world", world);
  22216. }
  22217. if (this._options.uniforms.indexOf("worldView") !== -1) {
  22218. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  22219. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  22220. }
  22221. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  22222. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  22223. }
  22224. };
  22225. ShaderMaterial.prototype.bind = function (world, mesh) {
  22226. // Std values
  22227. this.bindOnlyWorldMatrix(world);
  22228. if (this.getScene().getCachedMaterial() !== this) {
  22229. if (this._options.uniforms.indexOf("view") !== -1) {
  22230. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  22231. }
  22232. if (this._options.uniforms.indexOf("projection") !== -1) {
  22233. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  22234. }
  22235. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  22236. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  22237. }
  22238. // Bones
  22239. if (mesh && mesh.useBones) {
  22240. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  22241. }
  22242. for (var name in this._textures) {
  22243. this._effect.setTexture(name, this._textures[name]);
  22244. }
  22245. for (name in this._floats) {
  22246. this._effect.setFloat(name, this._floats[name]);
  22247. }
  22248. for (name in this._floatsArrays) {
  22249. this._effect.setArray(name, this._floatsArrays[name]);
  22250. }
  22251. for (name in this._colors3) {
  22252. this._effect.setColor3(name, this._colors3[name]);
  22253. }
  22254. for (name in this._colors4) {
  22255. var color = this._colors4[name];
  22256. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  22257. }
  22258. for (name in this._vectors2) {
  22259. this._effect.setVector2(name, this._vectors2[name]);
  22260. }
  22261. for (name in this._vectors3) {
  22262. this._effect.setVector3(name, this._vectors3[name]);
  22263. }
  22264. for (name in this._matrices) {
  22265. this._effect.setMatrix(name, this._matrices[name]);
  22266. }
  22267. }
  22268. _super.prototype.bind.call(this, world, mesh);
  22269. };
  22270. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  22271. for (var name in this._textures) {
  22272. this._textures[name].dispose();
  22273. }
  22274. this._textures = [];
  22275. _super.prototype.dispose.call(this, forceDisposeEffect);
  22276. };
  22277. return ShaderMaterial;
  22278. })(BABYLON.Material);
  22279. BABYLON.ShaderMaterial = ShaderMaterial;
  22280. })(BABYLON || (BABYLON = {}));
  22281. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  22282. (function (BABYLON) {
  22283. var VertexData = (function () {
  22284. function VertexData() {
  22285. }
  22286. VertexData.prototype.set = function (data, kind) {
  22287. switch (kind) {
  22288. case BABYLON.VertexBuffer.PositionKind:
  22289. this.positions = data;
  22290. break;
  22291. case BABYLON.VertexBuffer.NormalKind:
  22292. this.normals = data;
  22293. break;
  22294. case BABYLON.VertexBuffer.UVKind:
  22295. this.uvs = data;
  22296. break;
  22297. case BABYLON.VertexBuffer.UV2Kind:
  22298. this.uv2s = data;
  22299. break;
  22300. case BABYLON.VertexBuffer.ColorKind:
  22301. this.colors = data;
  22302. break;
  22303. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22304. this.matricesIndices = data;
  22305. break;
  22306. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22307. this.matricesWeights = data;
  22308. break;
  22309. }
  22310. };
  22311. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22312. this._applyTo(mesh, updatable);
  22313. };
  22314. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22315. this._applyTo(geometry, updatable);
  22316. };
  22317. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22318. this._update(mesh);
  22319. };
  22320. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22321. this._update(geometry);
  22322. };
  22323. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22324. if (this.positions) {
  22325. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22326. }
  22327. if (this.normals) {
  22328. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22329. }
  22330. if (this.uvs) {
  22331. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22332. }
  22333. if (this.uv2s) {
  22334. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  22335. }
  22336. if (this.colors) {
  22337. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22338. }
  22339. if (this.matricesIndices) {
  22340. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22341. }
  22342. if (this.matricesWeights) {
  22343. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22344. }
  22345. if (this.indices) {
  22346. meshOrGeometry.setIndices(this.indices);
  22347. }
  22348. };
  22349. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22350. if (this.positions) {
  22351. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22352. }
  22353. if (this.normals) {
  22354. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22355. }
  22356. if (this.uvs) {
  22357. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22358. }
  22359. if (this.uv2s) {
  22360. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  22361. }
  22362. if (this.colors) {
  22363. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22364. }
  22365. if (this.matricesIndices) {
  22366. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22367. }
  22368. if (this.matricesWeights) {
  22369. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22370. }
  22371. if (this.indices) {
  22372. meshOrGeometry.setIndices(this.indices);
  22373. }
  22374. };
  22375. VertexData.prototype.transform = function (matrix) {
  22376. var transformed = BABYLON.Vector3.Zero();
  22377. if (this.positions) {
  22378. var position = BABYLON.Vector3.Zero();
  22379. for (var index = 0; index < this.positions.length; index += 3) {
  22380. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22381. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22382. this.positions[index] = transformed.x;
  22383. this.positions[index + 1] = transformed.y;
  22384. this.positions[index + 2] = transformed.z;
  22385. }
  22386. }
  22387. if (this.normals) {
  22388. var normal = BABYLON.Vector3.Zero();
  22389. for (index = 0; index < this.normals.length; index += 3) {
  22390. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22391. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22392. this.normals[index] = transformed.x;
  22393. this.normals[index + 1] = transformed.y;
  22394. this.normals[index + 2] = transformed.z;
  22395. }
  22396. }
  22397. };
  22398. VertexData.prototype.merge = function (other) {
  22399. if (other.indices) {
  22400. if (!this.indices) {
  22401. this.indices = [];
  22402. }
  22403. var offset = this.positions ? this.positions.length / 3 : 0;
  22404. for (var index = 0; index < other.indices.length; index++) {
  22405. this.indices.push(other.indices[index] + offset);
  22406. }
  22407. }
  22408. if (other.positions) {
  22409. if (!this.positions) {
  22410. this.positions = [];
  22411. }
  22412. for (index = 0; index < other.positions.length; index++) {
  22413. this.positions.push(other.positions[index]);
  22414. }
  22415. }
  22416. if (other.normals) {
  22417. if (!this.normals) {
  22418. this.normals = [];
  22419. }
  22420. for (index = 0; index < other.normals.length; index++) {
  22421. this.normals.push(other.normals[index]);
  22422. }
  22423. }
  22424. if (other.uvs) {
  22425. if (!this.uvs) {
  22426. this.uvs = [];
  22427. }
  22428. for (index = 0; index < other.uvs.length; index++) {
  22429. this.uvs.push(other.uvs[index]);
  22430. }
  22431. }
  22432. if (other.uv2s) {
  22433. if (!this.uv2s) {
  22434. this.uv2s = [];
  22435. }
  22436. for (index = 0; index < other.uv2s.length; index++) {
  22437. this.uv2s.push(other.uv2s[index]);
  22438. }
  22439. }
  22440. if (other.matricesIndices) {
  22441. if (!this.matricesIndices) {
  22442. this.matricesIndices = [];
  22443. }
  22444. for (index = 0; index < other.matricesIndices.length; index++) {
  22445. this.matricesIndices.push(other.matricesIndices[index]);
  22446. }
  22447. }
  22448. if (other.matricesWeights) {
  22449. if (!this.matricesWeights) {
  22450. this.matricesWeights = [];
  22451. }
  22452. for (index = 0; index < other.matricesWeights.length; index++) {
  22453. this.matricesWeights.push(other.matricesWeights[index]);
  22454. }
  22455. }
  22456. if (other.colors) {
  22457. if (!this.colors) {
  22458. this.colors = [];
  22459. }
  22460. for (index = 0; index < other.colors.length; index++) {
  22461. this.colors.push(other.colors[index]);
  22462. }
  22463. }
  22464. };
  22465. // Statics
  22466. VertexData.ExtractFromMesh = function (mesh) {
  22467. return VertexData._ExtractFrom(mesh);
  22468. };
  22469. VertexData.ExtractFromGeometry = function (geometry) {
  22470. return VertexData._ExtractFrom(geometry);
  22471. };
  22472. VertexData._ExtractFrom = function (meshOrGeometry) {
  22473. var result = new VertexData();
  22474. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22475. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22476. }
  22477. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22478. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22479. }
  22480. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22481. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22482. }
  22483. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22484. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  22485. }
  22486. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22487. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  22488. }
  22489. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22490. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22491. }
  22492. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22493. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22494. }
  22495. result.indices = meshOrGeometry.getIndices();
  22496. return result;
  22497. };
  22498. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  22499. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22500. closeArray = closeArray || false;
  22501. closePath = closePath || false;
  22502. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22503. offset = offset || defaultOffset;
  22504. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22505. var positions = [];
  22506. var indices = [];
  22507. var normals = [];
  22508. var uvs = [];
  22509. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  22510. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  22511. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  22512. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  22513. var minlg; // minimal length among all paths from pathArray
  22514. var lg = []; // array of path lengths : nb of vertex per path
  22515. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  22516. var p; // path iterator
  22517. var i; // point iterator
  22518. var j; // point iterator
  22519. // if single path in pathArray
  22520. if (pathArray.length < 2) {
  22521. var ar1 = [];
  22522. var ar2 = [];
  22523. for (i = 0; i < pathArray[0].length - offset; i++) {
  22524. ar1.push(pathArray[0][i]);
  22525. ar2.push(pathArray[0][i + offset]);
  22526. }
  22527. pathArray = [ar1, ar2];
  22528. }
  22529. // positions and horizontal distances (u)
  22530. var idc = 0;
  22531. minlg = pathArray[0].length;
  22532. for (p = 0; p < pathArray.length; p++) {
  22533. uTotalDistance[p] = 0;
  22534. us[p] = [0];
  22535. var path = pathArray[p];
  22536. var l = path.length;
  22537. minlg = (minlg < l) ? minlg : l;
  22538. lg[p] = l;
  22539. idx[p] = idc;
  22540. j = 0;
  22541. while (j < l) {
  22542. positions.push(path[j].x, path[j].y, path[j].z);
  22543. if (j > 0) {
  22544. var vectlg = path[j].subtract(path[j - 1]).length();
  22545. var dist = vectlg + uTotalDistance[p];
  22546. us[p].push(dist);
  22547. uTotalDistance[p] = dist;
  22548. }
  22549. j++;
  22550. }
  22551. if (closePath) {
  22552. vectlg = path[0].subtract(path[j - 1]).length();
  22553. dist = vectlg + uTotalDistance[p];
  22554. uTotalDistance[p] = dist;
  22555. }
  22556. idc += l;
  22557. }
  22558. for (i = 0; i < minlg; i++) {
  22559. vTotalDistance[i] = 0;
  22560. vs[i] = [0];
  22561. var path1;
  22562. var path2;
  22563. for (p = 0; p < pathArray.length - 1; p++) {
  22564. path1 = pathArray[p];
  22565. path2 = pathArray[p + 1];
  22566. vectlg = path2[i].subtract(path1[i]).length();
  22567. dist = vectlg + vTotalDistance[i];
  22568. vs[i].push(dist);
  22569. vTotalDistance[i] = dist;
  22570. }
  22571. if (closeArray) {
  22572. path1 = pathArray[p];
  22573. path2 = pathArray[0];
  22574. vectlg = path2[i].subtract(path1[i]).length();
  22575. dist = vectlg + vTotalDistance[i];
  22576. vTotalDistance[i] = dist;
  22577. }
  22578. }
  22579. // uvs
  22580. var u;
  22581. var v;
  22582. for (p = 0; p < pathArray.length; p++) {
  22583. for (i = 0; i < minlg; i++) {
  22584. u = us[p][i] / uTotalDistance[p];
  22585. v = vs[i][p] / vTotalDistance[i];
  22586. uvs.push(u, v);
  22587. }
  22588. }
  22589. // indices
  22590. p = 0; // path index
  22591. var pi = 0; // positions array index
  22592. var l1 = lg[p] - 1; // path1 length
  22593. var l2 = lg[p + 1] - 1; // path2 length
  22594. var min = (l1 < l2) ? l1 : l2; // current path stop index
  22595. var shft = idx[1] - idx[0]; // shift
  22596. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  22597. var t1; // two consecutive triangles, so 4 points : point1
  22598. var t2; // point2
  22599. var t3; // point3
  22600. var t4; // point4
  22601. while (pi <= min && p < path1nb) {
  22602. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  22603. t1 = pi;
  22604. t2 = pi + shft;
  22605. t3 = pi + 1;
  22606. t4 = pi + shft + 1;
  22607. indices.push(pi, pi + shft, pi + 1);
  22608. indices.push(pi + shft + 1, pi + 1, pi + shft);
  22609. pi += 1;
  22610. if (pi === min) {
  22611. if (closePath) {
  22612. indices.push(pi, pi + shft, idx[p]);
  22613. indices.push(idx[p] + shft, idx[p], pi + shft);
  22614. t3 = idx[p];
  22615. t4 = idx[p] + shft;
  22616. }
  22617. p++;
  22618. if (p === lg.length - 1) {
  22619. shft = idx[0] - idx[p];
  22620. l1 = lg[p] - 1;
  22621. l2 = lg[0] - 1;
  22622. }
  22623. else {
  22624. shft = idx[p + 1] - idx[p];
  22625. l1 = lg[p] - 1;
  22626. l2 = lg[p + 1] - 1;
  22627. }
  22628. pi = idx[p];
  22629. min = (l1 < l2) ? l1 + pi : l2 + pi;
  22630. }
  22631. }
  22632. // normals
  22633. VertexData.ComputeNormals(positions, indices, normals);
  22634. // sides
  22635. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22636. // Result
  22637. var vertexData = new VertexData();
  22638. vertexData.indices = indices;
  22639. vertexData.positions = positions;
  22640. vertexData.normals = normals;
  22641. vertexData.uvs = uvs;
  22642. return vertexData;
  22643. };
  22644. VertexData.CreateBox = function (size, sideOrientation) {
  22645. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22646. var normalsSource = [
  22647. new BABYLON.Vector3(0, 0, 1),
  22648. new BABYLON.Vector3(0, 0, -1),
  22649. new BABYLON.Vector3(1, 0, 0),
  22650. new BABYLON.Vector3(-1, 0, 0),
  22651. new BABYLON.Vector3(0, 1, 0),
  22652. new BABYLON.Vector3(0, -1, 0)
  22653. ];
  22654. var indices = [];
  22655. var positions = [];
  22656. var normals = [];
  22657. var uvs = [];
  22658. size = size || 1;
  22659. for (var index = 0; index < normalsSource.length; index++) {
  22660. var normal = normalsSource[index];
  22661. // Get two vectors perpendicular to the face normal and to each other.
  22662. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  22663. var side2 = BABYLON.Vector3.Cross(normal, side1);
  22664. // Six indices (two triangles) per face.
  22665. var verticesLength = positions.length / 3;
  22666. indices.push(verticesLength);
  22667. indices.push(verticesLength + 1);
  22668. indices.push(verticesLength + 2);
  22669. indices.push(verticesLength);
  22670. indices.push(verticesLength + 2);
  22671. indices.push(verticesLength + 3);
  22672. // Four vertices per face.
  22673. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  22674. positions.push(vertex.x, vertex.y, vertex.z);
  22675. normals.push(normal.x, normal.y, normal.z);
  22676. uvs.push(1.0, 1.0);
  22677. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  22678. positions.push(vertex.x, vertex.y, vertex.z);
  22679. normals.push(normal.x, normal.y, normal.z);
  22680. uvs.push(0.0, 1.0);
  22681. vertex = normal.add(side1).add(side2).scale(size / 2);
  22682. positions.push(vertex.x, vertex.y, vertex.z);
  22683. normals.push(normal.x, normal.y, normal.z);
  22684. uvs.push(0.0, 0.0);
  22685. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  22686. positions.push(vertex.x, vertex.y, vertex.z);
  22687. normals.push(normal.x, normal.y, normal.z);
  22688. uvs.push(1.0, 0.0);
  22689. }
  22690. // sides
  22691. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22692. // Result
  22693. var vertexData = new VertexData();
  22694. vertexData.indices = indices;
  22695. vertexData.positions = positions;
  22696. vertexData.normals = normals;
  22697. vertexData.uvs = uvs;
  22698. return vertexData;
  22699. };
  22700. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  22701. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22702. segments = segments || 32;
  22703. diameter = diameter || 1;
  22704. var radius = diameter / 2;
  22705. var totalZRotationSteps = 2 + segments;
  22706. var totalYRotationSteps = 2 * totalZRotationSteps;
  22707. var indices = [];
  22708. var positions = [];
  22709. var normals = [];
  22710. var uvs = [];
  22711. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  22712. var normalizedZ = zRotationStep / totalZRotationSteps;
  22713. var angleZ = (normalizedZ * Math.PI);
  22714. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  22715. var normalizedY = yRotationStep / totalYRotationSteps;
  22716. var angleY = normalizedY * Math.PI * 2;
  22717. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  22718. var rotationY = BABYLON.Matrix.RotationY(angleY);
  22719. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  22720. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  22721. var vertex = complete.scale(radius);
  22722. var normal = BABYLON.Vector3.Normalize(vertex);
  22723. positions.push(vertex.x, vertex.y, vertex.z);
  22724. normals.push(normal.x, normal.y, normal.z);
  22725. uvs.push(normalizedZ, normalizedY);
  22726. }
  22727. if (zRotationStep > 0) {
  22728. var verticesCount = positions.length / 3;
  22729. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  22730. indices.push((firstIndex));
  22731. indices.push((firstIndex + 1));
  22732. indices.push(firstIndex + totalYRotationSteps + 1);
  22733. indices.push((firstIndex + totalYRotationSteps + 1));
  22734. indices.push((firstIndex + 1));
  22735. indices.push((firstIndex + totalYRotationSteps + 2));
  22736. }
  22737. }
  22738. }
  22739. // Sides
  22740. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22741. // Result
  22742. var vertexData = new VertexData();
  22743. vertexData.indices = indices;
  22744. vertexData.positions = positions;
  22745. vertexData.normals = normals;
  22746. vertexData.uvs = uvs;
  22747. return vertexData;
  22748. };
  22749. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  22750. if (subdivisions === void 0) { subdivisions = 1; }
  22751. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22752. var radiusTop = diameterTop / 2;
  22753. var radiusBottom = diameterBottom / 2;
  22754. var indices = [];
  22755. var positions = [];
  22756. var normals = [];
  22757. var uvs = [];
  22758. height = height || 1;
  22759. diameterTop = diameterTop || 0.5;
  22760. diameterBottom = diameterBottom || 1;
  22761. tessellation = tessellation || 16;
  22762. subdivisions = subdivisions || 1;
  22763. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  22764. var getCircleVector = function (i) {
  22765. var angle = (i * 2.0 * Math.PI / tessellation);
  22766. var dx = Math.cos(angle);
  22767. var dz = Math.sin(angle);
  22768. return new BABYLON.Vector3(dx, 0, dz);
  22769. };
  22770. var createCylinderCap = function (isTop) {
  22771. var radius = isTop ? radiusTop : radiusBottom;
  22772. if (radius === 0) {
  22773. return;
  22774. }
  22775. var vbase = positions.length / 3;
  22776. var offset = new BABYLON.Vector3(0, height / 2, 0);
  22777. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  22778. if (!isTop) {
  22779. offset.scaleInPlace(-1);
  22780. textureScale.x = -textureScale.x;
  22781. }
  22782. for (var i = 0; i < tessellation; i++) {
  22783. var circleVector = getCircleVector(i);
  22784. var position = circleVector.scale(radius).add(offset);
  22785. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  22786. positions.push(position.x, position.y, position.z);
  22787. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22788. }
  22789. for (i = 0; i < tessellation - 2; i++) {
  22790. if (!isTop) {
  22791. indices.push(vbase);
  22792. indices.push(vbase + (i + 2) % tessellation);
  22793. indices.push(vbase + (i + 1) % tessellation);
  22794. }
  22795. else {
  22796. indices.push(vbase);
  22797. indices.push(vbase + (i + 1) % tessellation);
  22798. indices.push(vbase + (i + 2) % tessellation);
  22799. }
  22800. }
  22801. };
  22802. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  22803. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  22804. var stride = tessellation + 1;
  22805. for (var i = 0; i <= tessellation; i++) {
  22806. var circleVector = getCircleVector(i);
  22807. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  22808. var position, radius = radiusBottom;
  22809. for (var s = 0; s <= subdivisions; s++) {
  22810. // Update variables
  22811. position = circleVector.scale(radius);
  22812. position.addInPlace(base.add(offset.scale(s)));
  22813. textureCoordinate.y += 1 / subdivisions;
  22814. radius += (radiusTop - radiusBottom) / subdivisions;
  22815. // Push in arrays
  22816. positions.push(position.x, position.y, position.z);
  22817. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22818. }
  22819. }
  22820. subdivisions += 1;
  22821. for (s = 0; s < subdivisions - 1; s++) {
  22822. for (i = 0; i <= tessellation; i++) {
  22823. indices.push(i * subdivisions + s);
  22824. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22825. indices.push(i * subdivisions + (s + 1));
  22826. indices.push(i * subdivisions + (s + 1));
  22827. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22828. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  22829. }
  22830. }
  22831. // Create flat triangle fan caps to seal the top and bottom.
  22832. createCylinderCap(true);
  22833. createCylinderCap(false);
  22834. // Normals
  22835. VertexData.ComputeNormals(positions, indices, normals);
  22836. // Sides
  22837. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22838. // Result
  22839. var vertexData = new VertexData();
  22840. vertexData.indices = indices;
  22841. vertexData.positions = positions;
  22842. vertexData.normals = normals;
  22843. vertexData.uvs = uvs;
  22844. return vertexData;
  22845. };
  22846. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  22847. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22848. var indices = [];
  22849. var positions = [];
  22850. var normals = [];
  22851. var uvs = [];
  22852. diameter = diameter || 1;
  22853. thickness = thickness || 0.5;
  22854. tessellation = tessellation || 16;
  22855. var stride = tessellation + 1;
  22856. for (var i = 0; i <= tessellation; i++) {
  22857. var u = i / tessellation;
  22858. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  22859. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  22860. for (var j = 0; j <= tessellation; j++) {
  22861. var v = 1 - j / tessellation;
  22862. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  22863. var dx = Math.cos(innerAngle);
  22864. var dy = Math.sin(innerAngle);
  22865. // Create a vertex.
  22866. var normal = new BABYLON.Vector3(dx, dy, 0);
  22867. var position = normal.scale(thickness / 2);
  22868. var textureCoordinate = new BABYLON.Vector2(u, v);
  22869. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  22870. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  22871. positions.push(position.x, position.y, position.z);
  22872. normals.push(normal.x, normal.y, normal.z);
  22873. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22874. // And create indices for two triangles.
  22875. var nextI = (i + 1) % stride;
  22876. var nextJ = (j + 1) % stride;
  22877. indices.push(i * stride + j);
  22878. indices.push(i * stride + nextJ);
  22879. indices.push(nextI * stride + j);
  22880. indices.push(i * stride + nextJ);
  22881. indices.push(nextI * stride + nextJ);
  22882. indices.push(nextI * stride + j);
  22883. }
  22884. }
  22885. // Sides
  22886. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22887. // Result
  22888. var vertexData = new VertexData();
  22889. vertexData.indices = indices;
  22890. vertexData.positions = positions;
  22891. vertexData.normals = normals;
  22892. vertexData.uvs = uvs;
  22893. return vertexData;
  22894. };
  22895. VertexData.CreateLines = function (points) {
  22896. var indices = [];
  22897. var positions = [];
  22898. for (var index = 0; index < points.length; index++) {
  22899. positions.push(points[index].x, points[index].y, points[index].z);
  22900. if (index > 0) {
  22901. indices.push(index - 1);
  22902. indices.push(index);
  22903. }
  22904. }
  22905. // Result
  22906. var vertexData = new VertexData();
  22907. vertexData.indices = indices;
  22908. vertexData.positions = positions;
  22909. return vertexData;
  22910. };
  22911. VertexData.CreateGround = function (width, height, subdivisions) {
  22912. var indices = [];
  22913. var positions = [];
  22914. var normals = [];
  22915. var uvs = [];
  22916. var row, col;
  22917. width = width || 1;
  22918. height = height || 1;
  22919. subdivisions = subdivisions || 1;
  22920. for (row = 0; row <= subdivisions; row++) {
  22921. for (col = 0; col <= subdivisions; col++) {
  22922. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22923. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22924. positions.push(position.x, position.y, position.z);
  22925. normals.push(normal.x, normal.y, normal.z);
  22926. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22927. }
  22928. }
  22929. for (row = 0; row < subdivisions; row++) {
  22930. for (col = 0; col < subdivisions; col++) {
  22931. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22932. indices.push(col + 1 + row * (subdivisions + 1));
  22933. indices.push(col + row * (subdivisions + 1));
  22934. indices.push(col + (row + 1) * (subdivisions + 1));
  22935. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22936. indices.push(col + row * (subdivisions + 1));
  22937. }
  22938. }
  22939. // Result
  22940. var vertexData = new VertexData();
  22941. vertexData.indices = indices;
  22942. vertexData.positions = positions;
  22943. vertexData.normals = normals;
  22944. vertexData.uvs = uvs;
  22945. return vertexData;
  22946. };
  22947. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22948. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22949. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22950. var indices = [];
  22951. var positions = [];
  22952. var normals = [];
  22953. var uvs = [];
  22954. var row, col, tileRow, tileCol;
  22955. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22956. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22957. precision.w = (precision.w < 1) ? 1 : precision.w;
  22958. precision.h = (precision.h < 1) ? 1 : precision.h;
  22959. var tileSize = {
  22960. 'w': (xmax - xmin) / subdivisions.w,
  22961. 'h': (zmax - zmin) / subdivisions.h
  22962. };
  22963. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22964. // Indices
  22965. var base = positions.length / 3;
  22966. var rowLength = precision.w + 1;
  22967. for (row = 0; row < precision.h; row++) {
  22968. for (col = 0; col < precision.w; col++) {
  22969. var square = [
  22970. base + col + row * rowLength,
  22971. base + (col + 1) + row * rowLength,
  22972. base + (col + 1) + (row + 1) * rowLength,
  22973. base + col + (row + 1) * rowLength
  22974. ];
  22975. indices.push(square[1]);
  22976. indices.push(square[2]);
  22977. indices.push(square[3]);
  22978. indices.push(square[0]);
  22979. indices.push(square[1]);
  22980. indices.push(square[3]);
  22981. }
  22982. }
  22983. // Position, normals and uvs
  22984. var position = BABYLON.Vector3.Zero();
  22985. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22986. for (row = 0; row <= precision.h; row++) {
  22987. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22988. for (col = 0; col <= precision.w; col++) {
  22989. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22990. position.y = 0;
  22991. positions.push(position.x, position.y, position.z);
  22992. normals.push(normal.x, normal.y, normal.z);
  22993. uvs.push(col / precision.w, row / precision.h);
  22994. }
  22995. }
  22996. }
  22997. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22998. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22999. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23000. }
  23001. }
  23002. // Result
  23003. var vertexData = new VertexData();
  23004. vertexData.indices = indices;
  23005. vertexData.positions = positions;
  23006. vertexData.normals = normals;
  23007. vertexData.uvs = uvs;
  23008. return vertexData;
  23009. };
  23010. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  23011. var indices = [];
  23012. var positions = [];
  23013. var normals = [];
  23014. var uvs = [];
  23015. var row, col;
  23016. for (row = 0; row <= subdivisions; row++) {
  23017. for (col = 0; col <= subdivisions; col++) {
  23018. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23019. // Compute height
  23020. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  23021. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  23022. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  23023. var r = buffer[pos] / 255.0;
  23024. var g = buffer[pos + 1] / 255.0;
  23025. var b = buffer[pos + 2] / 255.0;
  23026. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23027. position.y = minHeight + (maxHeight - minHeight) * gradient;
  23028. // Add vertex
  23029. positions.push(position.x, position.y, position.z);
  23030. normals.push(0, 0, 0);
  23031. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23032. }
  23033. }
  23034. for (row = 0; row < subdivisions; row++) {
  23035. for (col = 0; col < subdivisions; col++) {
  23036. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23037. indices.push(col + 1 + row * (subdivisions + 1));
  23038. indices.push(col + row * (subdivisions + 1));
  23039. indices.push(col + (row + 1) * (subdivisions + 1));
  23040. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23041. indices.push(col + row * (subdivisions + 1));
  23042. }
  23043. }
  23044. // Normals
  23045. VertexData.ComputeNormals(positions, indices, normals);
  23046. // Result
  23047. var vertexData = new VertexData();
  23048. vertexData.indices = indices;
  23049. vertexData.positions = positions;
  23050. vertexData.normals = normals;
  23051. vertexData.uvs = uvs;
  23052. return vertexData;
  23053. };
  23054. VertexData.CreatePlane = function (size, sideOrientation) {
  23055. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  23056. var indices = [];
  23057. var positions = [];
  23058. var normals = [];
  23059. var uvs = [];
  23060. size = size || 1;
  23061. // Vertices
  23062. var halfSize = size / 2.0;
  23063. positions.push(-halfSize, -halfSize, 0);
  23064. normals.push(0, 0, -1.0);
  23065. uvs.push(0.0, 0.0);
  23066. positions.push(halfSize, -halfSize, 0);
  23067. normals.push(0, 0, -1.0);
  23068. uvs.push(1.0, 0.0);
  23069. positions.push(halfSize, halfSize, 0);
  23070. normals.push(0, 0, -1.0);
  23071. uvs.push(1.0, 1.0);
  23072. positions.push(-halfSize, halfSize, 0);
  23073. normals.push(0, 0, -1.0);
  23074. uvs.push(0.0, 1.0);
  23075. // Indices
  23076. indices.push(0);
  23077. indices.push(1);
  23078. indices.push(2);
  23079. indices.push(0);
  23080. indices.push(2);
  23081. indices.push(3);
  23082. // Sides
  23083. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23084. // Result
  23085. var vertexData = new VertexData();
  23086. vertexData.indices = indices;
  23087. vertexData.positions = positions;
  23088. vertexData.normals = normals;
  23089. vertexData.uvs = uvs;
  23090. return vertexData;
  23091. };
  23092. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  23093. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  23094. var positions = [];
  23095. var indices = [];
  23096. var normals = [];
  23097. var uvs = [];
  23098. // positions and uvs
  23099. positions.push(0, 0, 0); // disc center first
  23100. uvs.push(0.5, 0.5);
  23101. var step = Math.PI * 2 / tessellation;
  23102. for (var a = 0; a < Math.PI * 2; a += step) {
  23103. var x = Math.cos(a);
  23104. var y = Math.sin(a);
  23105. var u = (x + 1) / 2;
  23106. var v = (1 - y) / 2;
  23107. positions.push(radius * x, radius * y, 0);
  23108. uvs.push(u, v);
  23109. }
  23110. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23111. uvs.push(uvs[2], uvs[3]);
  23112. //indices
  23113. var vertexNb = positions.length / 3;
  23114. for (var i = 1; i < vertexNb - 1; i++) {
  23115. indices.push(i + 1, 0, i);
  23116. }
  23117. // result
  23118. VertexData.ComputeNormals(positions, indices, normals);
  23119. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23120. var vertexData = new VertexData();
  23121. vertexData.indices = indices;
  23122. vertexData.positions = positions;
  23123. vertexData.normals = normals;
  23124. vertexData.uvs = uvs;
  23125. return vertexData;
  23126. };
  23127. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  23128. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  23129. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  23130. var indices = [];
  23131. var positions = [];
  23132. var normals = [];
  23133. var uvs = [];
  23134. radius = radius || 2;
  23135. tube = tube || 0.5;
  23136. radialSegments = radialSegments || 32;
  23137. tubularSegments = tubularSegments || 32;
  23138. p = p || 2;
  23139. q = q || 3;
  23140. // Helper
  23141. var getPos = function (angle) {
  23142. var cu = Math.cos(angle);
  23143. var su = Math.sin(angle);
  23144. var quOverP = q / p * angle;
  23145. var cs = Math.cos(quOverP);
  23146. var tx = radius * (2 + cs) * 0.5 * cu;
  23147. var ty = radius * (2 + cs) * su * 0.5;
  23148. var tz = radius * Math.sin(quOverP) * 0.5;
  23149. return new BABYLON.Vector3(tx, ty, tz);
  23150. };
  23151. for (var i = 0; i <= radialSegments; i++) {
  23152. var modI = i % radialSegments;
  23153. var u = modI / radialSegments * 2 * p * Math.PI;
  23154. var p1 = getPos(u);
  23155. var p2 = getPos(u + 0.01);
  23156. var tang = p2.subtract(p1);
  23157. var n = p2.add(p1);
  23158. var bitan = BABYLON.Vector3.Cross(tang, n);
  23159. n = BABYLON.Vector3.Cross(bitan, tang);
  23160. bitan.normalize();
  23161. n.normalize();
  23162. for (var j = 0; j < tubularSegments; j++) {
  23163. var modJ = j % tubularSegments;
  23164. var v = modJ / tubularSegments * 2 * Math.PI;
  23165. var cx = -tube * Math.cos(v);
  23166. var cy = tube * Math.sin(v);
  23167. positions.push(p1.x + cx * n.x + cy * bitan.x);
  23168. positions.push(p1.y + cx * n.y + cy * bitan.y);
  23169. positions.push(p1.z + cx * n.z + cy * bitan.z);
  23170. uvs.push(i / radialSegments);
  23171. uvs.push(j / tubularSegments);
  23172. }
  23173. }
  23174. for (i = 0; i < radialSegments; i++) {
  23175. for (j = 0; j < tubularSegments; j++) {
  23176. var jNext = (j + 1) % tubularSegments;
  23177. var a = i * tubularSegments + j;
  23178. var b = (i + 1) * tubularSegments + j;
  23179. var c = (i + 1) * tubularSegments + jNext;
  23180. var d = i * tubularSegments + jNext;
  23181. indices.push(d);
  23182. indices.push(b);
  23183. indices.push(a);
  23184. indices.push(d);
  23185. indices.push(c);
  23186. indices.push(b);
  23187. }
  23188. }
  23189. // Normals
  23190. VertexData.ComputeNormals(positions, indices, normals);
  23191. // Sides
  23192. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23193. // Result
  23194. var vertexData = new VertexData();
  23195. vertexData.indices = indices;
  23196. vertexData.positions = positions;
  23197. vertexData.normals = normals;
  23198. vertexData.uvs = uvs;
  23199. return vertexData;
  23200. };
  23201. // Tools
  23202. /**
  23203. * @param {any} - positions (number[] or Float32Array)
  23204. * @param {any} - indices (number[] or Uint16Array)
  23205. * @param {any} - normals (number[] or Float32Array)
  23206. */
  23207. VertexData.ComputeNormals = function (positions, indices, normals) {
  23208. var positionVectors = [];
  23209. var facesOfVertices = [];
  23210. var index;
  23211. for (index = 0; index < positions.length; index += 3) {
  23212. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  23213. positionVectors.push(vector3);
  23214. facesOfVertices.push([]);
  23215. }
  23216. // Compute normals
  23217. var facesNormals = [];
  23218. for (index = 0; index < indices.length / 3; index++) {
  23219. var i1 = indices[index * 3];
  23220. var i2 = indices[index * 3 + 1];
  23221. var i3 = indices[index * 3 + 2];
  23222. var p1 = positionVectors[i1];
  23223. var p2 = positionVectors[i2];
  23224. var p3 = positionVectors[i3];
  23225. var p1p2 = p1.subtract(p2);
  23226. var p3p2 = p3.subtract(p2);
  23227. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23228. facesOfVertices[i1].push(index);
  23229. facesOfVertices[i2].push(index);
  23230. facesOfVertices[i3].push(index);
  23231. }
  23232. for (index = 0; index < positionVectors.length; index++) {
  23233. var faces = facesOfVertices[index];
  23234. var normal = BABYLON.Vector3.Zero();
  23235. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  23236. normal.addInPlace(facesNormals[faces[faceIndex]]);
  23237. }
  23238. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  23239. normals[index * 3] = normal.x;
  23240. normals[index * 3 + 1] = normal.y;
  23241. normals[index * 3 + 2] = normal.z;
  23242. }
  23243. };
  23244. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  23245. var li = indices.length;
  23246. var ln = normals.length;
  23247. var i;
  23248. var n;
  23249. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23250. switch (sideOrientation) {
  23251. case BABYLON.Mesh.FRONTSIDE:
  23252. break;
  23253. case BABYLON.Mesh.BACKSIDE:
  23254. var tmp;
  23255. for (i = 0; i < li; i += 3) {
  23256. tmp = indices[i];
  23257. indices[i] = indices[i + 2];
  23258. indices[i + 2] = tmp;
  23259. }
  23260. for (n = 0; n < ln; n++) {
  23261. normals[n] = -normals[n];
  23262. }
  23263. break;
  23264. case BABYLON.Mesh.DOUBLESIDE:
  23265. // positions
  23266. var lp = positions.length;
  23267. var l = lp / 3;
  23268. for (var p = 0; p < lp; p++) {
  23269. positions[lp + p] = positions[p];
  23270. }
  23271. for (i = 0; i < li; i += 3) {
  23272. indices[i + li] = indices[i + 2] + l;
  23273. indices[i + 1 + li] = indices[i + 1] + l;
  23274. indices[i + 2 + li] = indices[i] + l;
  23275. }
  23276. for (n = 0; n < ln; n++) {
  23277. normals[ln + n] = -normals[n];
  23278. }
  23279. // uvs
  23280. var lu = uvs.length;
  23281. for (var u = 0; u < lu; u++) {
  23282. uvs[u + lu] = uvs[u];
  23283. }
  23284. break;
  23285. }
  23286. };
  23287. return VertexData;
  23288. })();
  23289. BABYLON.VertexData = VertexData;
  23290. })(BABYLON || (BABYLON = {}));
  23291. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  23292. var BABYLON;
  23293. (function (BABYLON) {
  23294. var buildCamera = function (that, name) {
  23295. that._leftCamera.isIntermediate = true;
  23296. that.subCameras.push(that._leftCamera);
  23297. that.subCameras.push(that._rightCamera);
  23298. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  23299. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  23300. that._anaglyphPostProcess.onApply = function (effect) {
  23301. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  23302. };
  23303. that._update();
  23304. };
  23305. var AnaglyphArcRotateCamera = (function (_super) {
  23306. __extends(AnaglyphArcRotateCamera, _super);
  23307. // ANY
  23308. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  23309. _super.call(this, name, alpha, beta, radius, target, scene);
  23310. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23311. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  23312. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  23313. buildCamera(this, name);
  23314. }
  23315. AnaglyphArcRotateCamera.prototype._update = function () {
  23316. this._updateCamera(this._leftCamera);
  23317. this._updateCamera(this._rightCamera);
  23318. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  23319. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  23320. _super.prototype._update.call(this);
  23321. };
  23322. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  23323. camera.beta = this.beta;
  23324. camera.radius = this.radius;
  23325. camera.minZ = this.minZ;
  23326. camera.maxZ = this.maxZ;
  23327. camera.fov = this.fov;
  23328. camera.target = this.target;
  23329. };
  23330. return AnaglyphArcRotateCamera;
  23331. })(BABYLON.ArcRotateCamera);
  23332. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  23333. var AnaglyphFreeCamera = (function (_super) {
  23334. __extends(AnaglyphFreeCamera, _super);
  23335. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  23336. _super.call(this, name, position, scene);
  23337. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23338. this._transformMatrix = new BABYLON.Matrix();
  23339. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  23340. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  23341. buildCamera(this, name);
  23342. }
  23343. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  23344. var target = this.getTarget();
  23345. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  23346. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  23347. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  23348. };
  23349. AnaglyphFreeCamera.prototype._update = function () {
  23350. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  23351. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  23352. this._updateCamera(this._leftCamera);
  23353. this._updateCamera(this._rightCamera);
  23354. _super.prototype._update.call(this);
  23355. };
  23356. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  23357. camera.minZ = this.minZ;
  23358. camera.maxZ = this.maxZ;
  23359. camera.fov = this.fov;
  23360. camera.viewport = this.viewport;
  23361. camera.setTarget(this.getTarget());
  23362. };
  23363. return AnaglyphFreeCamera;
  23364. })(BABYLON.FreeCamera);
  23365. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  23366. })(BABYLON || (BABYLON = {}));
  23367. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  23368. var BABYLON;
  23369. (function (BABYLON) {
  23370. var AnaglyphPostProcess = (function (_super) {
  23371. __extends(AnaglyphPostProcess, _super);
  23372. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23373. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  23374. }
  23375. return AnaglyphPostProcess;
  23376. })(BABYLON.PostProcess);
  23377. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  23378. })(BABYLON || (BABYLON = {}));
  23379. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  23380. (function (BABYLON) {
  23381. var Tags = (function () {
  23382. function Tags() {
  23383. }
  23384. Tags.EnableFor = function (obj) {
  23385. obj._tags = obj._tags || {};
  23386. obj.hasTags = function () {
  23387. return Tags.HasTags(obj);
  23388. };
  23389. obj.addTags = function (tagsString) {
  23390. return Tags.AddTagsTo(obj, tagsString);
  23391. };
  23392. obj.removeTags = function (tagsString) {
  23393. return Tags.RemoveTagsFrom(obj, tagsString);
  23394. };
  23395. obj.matchesTagsQuery = function (tagsQuery) {
  23396. return Tags.MatchesQuery(obj, tagsQuery);
  23397. };
  23398. };
  23399. Tags.DisableFor = function (obj) {
  23400. delete obj._tags;
  23401. delete obj.hasTags;
  23402. delete obj.addTags;
  23403. delete obj.removeTags;
  23404. delete obj.matchesTagsQuery;
  23405. };
  23406. Tags.HasTags = function (obj) {
  23407. if (!obj._tags) {
  23408. return false;
  23409. }
  23410. return !BABYLON.Tools.IsEmpty(obj._tags);
  23411. };
  23412. Tags.GetTags = function (obj) {
  23413. if (!obj._tags) {
  23414. return null;
  23415. }
  23416. return obj._tags;
  23417. };
  23418. // the tags 'true' and 'false' are reserved and cannot be used as tags
  23419. // a tag cannot start with '||', '&&', and '!'
  23420. // it cannot contain whitespaces
  23421. Tags.AddTagsTo = function (obj, tagsString) {
  23422. if (!tagsString) {
  23423. return;
  23424. }
  23425. var tags = tagsString.split(" ");
  23426. for (var t in tags) {
  23427. Tags._AddTagTo(obj, tags[t]);
  23428. }
  23429. };
  23430. Tags._AddTagTo = function (obj, tag) {
  23431. tag = tag.trim();
  23432. if (tag === "" || tag === "true" || tag === "false") {
  23433. return;
  23434. }
  23435. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  23436. return;
  23437. }
  23438. Tags.EnableFor(obj);
  23439. obj._tags[tag] = true;
  23440. };
  23441. Tags.RemoveTagsFrom = function (obj, tagsString) {
  23442. if (!Tags.HasTags(obj)) {
  23443. return;
  23444. }
  23445. var tags = tagsString.split(" ");
  23446. for (var t in tags) {
  23447. Tags._RemoveTagFrom(obj, tags[t]);
  23448. }
  23449. };
  23450. Tags._RemoveTagFrom = function (obj, tag) {
  23451. delete obj._tags[tag];
  23452. };
  23453. Tags.MatchesQuery = function (obj, tagsQuery) {
  23454. if (tagsQuery === undefined) {
  23455. return true;
  23456. }
  23457. if (tagsQuery === "") {
  23458. return Tags.HasTags(obj);
  23459. }
  23460. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  23461. };
  23462. return Tags;
  23463. })();
  23464. BABYLON.Tags = Tags;
  23465. })(BABYLON || (BABYLON = {}));
  23466. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  23467. (function (BABYLON) {
  23468. var Internals;
  23469. (function (Internals) {
  23470. var AndOrNotEvaluator = (function () {
  23471. function AndOrNotEvaluator() {
  23472. }
  23473. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  23474. if (!query.match(/\([^\(\)]*\)/g)) {
  23475. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  23476. }
  23477. else {
  23478. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  23479. // remove parenthesis
  23480. r = r.slice(1, r.length - 1);
  23481. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  23482. });
  23483. }
  23484. if (query === "true") {
  23485. return true;
  23486. }
  23487. if (query === "false") {
  23488. return false;
  23489. }
  23490. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  23491. };
  23492. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  23493. evaluateCallback = evaluateCallback || (function (r) {
  23494. return r === "true" ? true : false;
  23495. });
  23496. var result;
  23497. var or = parenthesisContent.split("||");
  23498. for (var i in or) {
  23499. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  23500. var and = ori.split("&&");
  23501. if (and.length > 1) {
  23502. for (var j = 0; j < and.length; ++j) {
  23503. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  23504. if (andj !== "true" && andj !== "false") {
  23505. if (andj[0] === "!") {
  23506. result = !evaluateCallback(andj.substring(1));
  23507. }
  23508. else {
  23509. result = evaluateCallback(andj);
  23510. }
  23511. }
  23512. else {
  23513. result = andj === "true" ? true : false;
  23514. }
  23515. if (!result) {
  23516. ori = "false";
  23517. break;
  23518. }
  23519. }
  23520. }
  23521. if (result || ori === "true") {
  23522. result = true;
  23523. break;
  23524. }
  23525. // result equals false (or undefined)
  23526. if (ori !== "true" && ori !== "false") {
  23527. if (ori[0] === "!") {
  23528. result = !evaluateCallback(ori.substring(1));
  23529. }
  23530. else {
  23531. result = evaluateCallback(ori);
  23532. }
  23533. }
  23534. else {
  23535. result = ori === "true" ? true : false;
  23536. }
  23537. }
  23538. // the whole parenthesis scope is replaced by 'true' or 'false'
  23539. return result ? "true" : "false";
  23540. };
  23541. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  23542. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  23543. // remove whitespaces
  23544. r = r.replace(/[\s]/g, function () { return ""; });
  23545. return r.length % 2 ? "!" : "";
  23546. });
  23547. booleanString = booleanString.trim();
  23548. if (booleanString === "!true") {
  23549. booleanString = "false";
  23550. }
  23551. else if (booleanString === "!false") {
  23552. booleanString = "true";
  23553. }
  23554. return booleanString;
  23555. };
  23556. return AndOrNotEvaluator;
  23557. })();
  23558. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  23559. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23560. })(BABYLON || (BABYLON = {}));
  23561. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  23562. (function (BABYLON) {
  23563. var PostProcessRenderPass = (function () {
  23564. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  23565. this._enabled = true;
  23566. this._refCount = 0;
  23567. this._name = name;
  23568. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  23569. this.setRenderList(renderList);
  23570. this._renderTexture.onBeforeRender = beforeRender;
  23571. this._renderTexture.onAfterRender = afterRender;
  23572. this._scene = scene;
  23573. this._renderList = renderList;
  23574. }
  23575. // private
  23576. PostProcessRenderPass.prototype._incRefCount = function () {
  23577. if (this._refCount === 0) {
  23578. this._scene.customRenderTargets.push(this._renderTexture);
  23579. }
  23580. return ++this._refCount;
  23581. };
  23582. PostProcessRenderPass.prototype._decRefCount = function () {
  23583. this._refCount--;
  23584. if (this._refCount <= 0) {
  23585. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  23586. }
  23587. return this._refCount;
  23588. };
  23589. PostProcessRenderPass.prototype._update = function () {
  23590. this.setRenderList(this._renderList);
  23591. };
  23592. // public
  23593. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  23594. this._renderTexture.renderList = renderList;
  23595. };
  23596. PostProcessRenderPass.prototype.getRenderTexture = function () {
  23597. return this._renderTexture;
  23598. };
  23599. return PostProcessRenderPass;
  23600. })();
  23601. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  23602. })(BABYLON || (BABYLON = {}));
  23603. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  23604. (function (BABYLON) {
  23605. var PostProcessRenderEffect = (function () {
  23606. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  23607. this._engine = engine;
  23608. this._name = name;
  23609. this._singleInstance = singleInstance || true;
  23610. this._getPostProcess = getPostProcess;
  23611. this._cameras = [];
  23612. this._indicesForCamera = [];
  23613. this._postProcesses = {};
  23614. this._renderPasses = {};
  23615. this._renderEffectAsPasses = {};
  23616. }
  23617. PostProcessRenderEffect.prototype._update = function () {
  23618. for (var renderPassName in this._renderPasses) {
  23619. this._renderPasses[renderPassName]._update();
  23620. }
  23621. };
  23622. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  23623. this._renderPasses[renderPass._name] = renderPass;
  23624. this._linkParameters();
  23625. };
  23626. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  23627. delete this._renderPasses[renderPass._name];
  23628. this._linkParameters();
  23629. };
  23630. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  23631. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  23632. this._linkParameters();
  23633. };
  23634. PostProcessRenderEffect.prototype.getPass = function (passName) {
  23635. for (var renderPassName in this._renderPasses) {
  23636. if (renderPassName === passName) {
  23637. return this._renderPasses[passName];
  23638. }
  23639. }
  23640. };
  23641. PostProcessRenderEffect.prototype.emptyPasses = function () {
  23642. this._renderPasses = {};
  23643. this._linkParameters();
  23644. };
  23645. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  23646. var cameraKey;
  23647. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23648. for (var i = 0; i < _cam.length; i++) {
  23649. var camera = _cam[i];
  23650. var cameraName = camera.name;
  23651. if (this._singleInstance) {
  23652. cameraKey = 0;
  23653. }
  23654. else {
  23655. cameraKey = cameraName;
  23656. }
  23657. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  23658. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  23659. if (!this._indicesForCamera[cameraName]) {
  23660. this._indicesForCamera[cameraName] = [];
  23661. }
  23662. this._indicesForCamera[cameraName].push(index);
  23663. if (this._cameras.indexOf(camera) === -1) {
  23664. this._cameras[cameraName] = camera;
  23665. }
  23666. for (var passName in this._renderPasses) {
  23667. this._renderPasses[passName]._incRefCount();
  23668. }
  23669. }
  23670. this._linkParameters();
  23671. };
  23672. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  23673. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23674. for (var i = 0; i < _cam.length; i++) {
  23675. var camera = _cam[i];
  23676. var cameraName = camera.name;
  23677. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23678. var index = this._cameras.indexOf(cameraName);
  23679. this._indicesForCamera.splice(index, 1);
  23680. this._cameras.splice(index, 1);
  23681. for (var passName in this._renderPasses) {
  23682. this._renderPasses[passName]._decRefCount();
  23683. }
  23684. }
  23685. };
  23686. PostProcessRenderEffect.prototype._enable = function (cameras) {
  23687. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23688. for (var i = 0; i < _cam.length; i++) {
  23689. var camera = _cam[i];
  23690. var cameraName = camera.name;
  23691. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  23692. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  23693. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  23694. }
  23695. }
  23696. for (var passName in this._renderPasses) {
  23697. this._renderPasses[passName]._incRefCount();
  23698. }
  23699. }
  23700. };
  23701. PostProcessRenderEffect.prototype._disable = function (cameras) {
  23702. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23703. for (var i = 0; i < _cam.length; i++) {
  23704. var camera = _cam[i];
  23705. var cameraName = camera.Name;
  23706. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23707. for (var passName in this._renderPasses) {
  23708. this._renderPasses[passName]._decRefCount();
  23709. }
  23710. }
  23711. };
  23712. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  23713. if (this._singleInstance) {
  23714. return this._postProcesses[0];
  23715. }
  23716. else {
  23717. return this._postProcesses[camera.name];
  23718. }
  23719. };
  23720. PostProcessRenderEffect.prototype._linkParameters = function () {
  23721. var _this = this;
  23722. for (var index in this._postProcesses) {
  23723. if (this.applyParameters) {
  23724. this.applyParameters(this._postProcesses[index]);
  23725. }
  23726. this._postProcesses[index].onBeforeRender = function (effect) {
  23727. _this._linkTextures(effect);
  23728. };
  23729. }
  23730. };
  23731. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  23732. for (var renderPassName in this._renderPasses) {
  23733. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  23734. }
  23735. for (var renderEffectName in this._renderEffectAsPasses) {
  23736. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  23737. }
  23738. };
  23739. return PostProcessRenderEffect;
  23740. })();
  23741. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  23742. })(BABYLON || (BABYLON = {}));
  23743. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  23744. (function (BABYLON) {
  23745. var PostProcessRenderPipeline = (function () {
  23746. function PostProcessRenderPipeline(engine, name) {
  23747. this._engine = engine;
  23748. this._name = name;
  23749. this._renderEffects = {};
  23750. this._renderEffectsForIsolatedPass = {};
  23751. this._cameras = [];
  23752. }
  23753. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  23754. this._renderEffects[renderEffect._name] = renderEffect;
  23755. };
  23756. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  23757. var renderEffects = this._renderEffects[renderEffectName];
  23758. if (!renderEffects) {
  23759. return;
  23760. }
  23761. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23762. };
  23763. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  23764. var renderEffects = this._renderEffects[renderEffectName];
  23765. if (!renderEffects) {
  23766. return;
  23767. }
  23768. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23769. };
  23770. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  23771. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23772. var indicesToDelete = [];
  23773. for (var i = 0; i < _cam.length; i++) {
  23774. var camera = _cam[i];
  23775. var cameraName = camera.name;
  23776. if (this._cameras.indexOf(camera) === -1) {
  23777. this._cameras[cameraName] = camera;
  23778. }
  23779. else if (unique) {
  23780. indicesToDelete.push(i);
  23781. }
  23782. }
  23783. for (var i = 0; i < indicesToDelete.length; i++) {
  23784. cameras.splice(indicesToDelete[i], 1);
  23785. }
  23786. for (var renderEffectName in this._renderEffects) {
  23787. this._renderEffects[renderEffectName]._attachCameras(_cam);
  23788. }
  23789. };
  23790. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  23791. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23792. for (var renderEffectName in this._renderEffects) {
  23793. this._renderEffects[renderEffectName]._detachCameras(_cam);
  23794. }
  23795. for (var i = 0; i < _cam.length; i++) {
  23796. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  23797. }
  23798. };
  23799. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  23800. var _this = this;
  23801. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23802. var pass = null;
  23803. for (var renderEffectName in this._renderEffects) {
  23804. pass = this._renderEffects[renderEffectName].getPass(passName);
  23805. if (pass != null) {
  23806. break;
  23807. }
  23808. }
  23809. if (pass === null) {
  23810. return;
  23811. }
  23812. for (var renderEffectName in this._renderEffects) {
  23813. this._renderEffects[renderEffectName]._disable(_cam);
  23814. }
  23815. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  23816. for (var i = 0; i < _cam.length; i++) {
  23817. var camera = _cam[i];
  23818. var cameraName = camera.name;
  23819. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23820. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23821. });
  23822. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  23823. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  23824. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  23825. }
  23826. };
  23827. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  23828. var _this = this;
  23829. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23830. for (var i = 0; i < _cam.length; i++) {
  23831. var camera = _cam[i];
  23832. var cameraName = camera.name;
  23833. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23834. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23835. });
  23836. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  23837. }
  23838. for (var renderEffectName in this._renderEffects) {
  23839. this._renderEffects[renderEffectName]._enable(_cam);
  23840. }
  23841. };
  23842. PostProcessRenderPipeline.prototype._update = function () {
  23843. for (var renderEffectName in this._renderEffects) {
  23844. this._renderEffects[renderEffectName]._update();
  23845. }
  23846. for (var i = 0; i < this._cameras.length; i++) {
  23847. var cameraName = this._cameras[i].name;
  23848. if (this._renderEffectsForIsolatedPass[cameraName]) {
  23849. this._renderEffectsForIsolatedPass[cameraName]._update();
  23850. }
  23851. }
  23852. };
  23853. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  23854. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  23855. return PostProcessRenderPipeline;
  23856. })();
  23857. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  23858. })(BABYLON || (BABYLON = {}));
  23859. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  23860. (function (BABYLON) {
  23861. var PostProcessRenderPipelineManager = (function () {
  23862. function PostProcessRenderPipelineManager() {
  23863. this._renderPipelines = {};
  23864. }
  23865. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  23866. this._renderPipelines[renderPipeline._name] = renderPipeline;
  23867. };
  23868. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  23869. var renderPipeline = this._renderPipelines[renderPipelineName];
  23870. if (!renderPipeline) {
  23871. return;
  23872. }
  23873. renderPipeline._attachCameras(cameras, unique);
  23874. };
  23875. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  23876. var renderPipeline = this._renderPipelines[renderPipelineName];
  23877. if (!renderPipeline) {
  23878. return;
  23879. }
  23880. renderPipeline._detachCameras(cameras);
  23881. };
  23882. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23883. var renderPipeline = this._renderPipelines[renderPipelineName];
  23884. if (!renderPipeline) {
  23885. return;
  23886. }
  23887. renderPipeline._enableEffect(renderEffectName, cameras);
  23888. };
  23889. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23890. var renderPipeline = this._renderPipelines[renderPipelineName];
  23891. if (!renderPipeline) {
  23892. return;
  23893. }
  23894. renderPipeline._disableEffect(renderEffectName, cameras);
  23895. };
  23896. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  23897. var renderPipeline = this._renderPipelines[renderPipelineName];
  23898. if (!renderPipeline) {
  23899. return;
  23900. }
  23901. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  23902. };
  23903. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  23904. var renderPipeline = this._renderPipelines[renderPipelineName];
  23905. if (!renderPipeline) {
  23906. return;
  23907. }
  23908. renderPipeline._disableDisplayOnlyPass(cameras);
  23909. };
  23910. PostProcessRenderPipelineManager.prototype.update = function () {
  23911. for (var renderPipelineName in this._renderPipelines) {
  23912. this._renderPipelines[renderPipelineName]._update();
  23913. }
  23914. };
  23915. return PostProcessRenderPipelineManager;
  23916. })();
  23917. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  23918. })(BABYLON || (BABYLON = {}));
  23919. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  23920. var BABYLON;
  23921. (function (BABYLON) {
  23922. var DisplayPassPostProcess = (function (_super) {
  23923. __extends(DisplayPassPostProcess, _super);
  23924. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23925. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  23926. }
  23927. return DisplayPassPostProcess;
  23928. })(BABYLON.PostProcess);
  23929. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  23930. })(BABYLON || (BABYLON = {}));
  23931. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  23932. (function (BABYLON) {
  23933. var BoundingBoxRenderer = (function () {
  23934. function BoundingBoxRenderer(scene) {
  23935. this.frontColor = new BABYLON.Color3(1, 1, 1);
  23936. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  23937. this.showBackLines = true;
  23938. this.renderList = new BABYLON.SmartArray(32);
  23939. this._scene = scene;
  23940. }
  23941. BoundingBoxRenderer.prototype._prepareRessources = function () {
  23942. if (this._colorShader) {
  23943. return;
  23944. }
  23945. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  23946. attributes: ["position"],
  23947. uniforms: ["worldViewProjection", "color"]
  23948. });
  23949. var engine = this._scene.getEngine();
  23950. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  23951. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  23952. 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]);
  23953. };
  23954. BoundingBoxRenderer.prototype.reset = function () {
  23955. this.renderList.reset();
  23956. };
  23957. BoundingBoxRenderer.prototype.render = function () {
  23958. if (this.renderList.length === 0) {
  23959. return;
  23960. }
  23961. this._prepareRessources();
  23962. if (!this._colorShader.isReady()) {
  23963. return;
  23964. }
  23965. var engine = this._scene.getEngine();
  23966. engine.setDepthWrite(false);
  23967. this._colorShader._preBind();
  23968. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  23969. var boundingBox = this.renderList.data[boundingBoxIndex];
  23970. var min = boundingBox.minimum;
  23971. var max = boundingBox.maximum;
  23972. var diff = max.subtract(min);
  23973. var median = min.add(diff.scale(0.5));
  23974. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  23975. // VBOs
  23976. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  23977. if (this.showBackLines) {
  23978. // Back
  23979. engine.setDepthFunctionToGreaterOrEqual();
  23980. this._scene.resetCachedMaterial();
  23981. this._colorShader.setColor4("color", this.backColor.toColor4());
  23982. this._colorShader.bind(worldMatrix);
  23983. // Draw order
  23984. engine.draw(false, 0, 24);
  23985. }
  23986. // Front
  23987. engine.setDepthFunctionToLess();
  23988. this._scene.resetCachedMaterial();
  23989. this._colorShader.setColor4("color", this.frontColor.toColor4());
  23990. this._colorShader.bind(worldMatrix);
  23991. // Draw order
  23992. engine.draw(false, 0, 24);
  23993. }
  23994. this._colorShader.unbind();
  23995. engine.setDepthFunctionToLessOrEqual();
  23996. engine.setDepthWrite(true);
  23997. };
  23998. BoundingBoxRenderer.prototype.dispose = function () {
  23999. if (!this._colorShader) {
  24000. return;
  24001. }
  24002. this._colorShader.dispose();
  24003. this._vb.dispose();
  24004. this._scene.getEngine()._releaseBuffer(this._ib);
  24005. };
  24006. return BoundingBoxRenderer;
  24007. })();
  24008. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  24009. })(BABYLON || (BABYLON = {}));
  24010. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  24011. (function (BABYLON) {
  24012. var Internals;
  24013. (function (Internals) {
  24014. /*
  24015. * Based on jsTGALoader - Javascript loader for TGA file
  24016. * By Vincent Thibault
  24017. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  24018. */
  24019. var TGATools = (function () {
  24020. function TGATools() {
  24021. }
  24022. TGATools.GetTGAHeader = function (data) {
  24023. var offset = 0;
  24024. var header = {
  24025. id_length: data[offset++],
  24026. colormap_type: data[offset++],
  24027. image_type: data[offset++],
  24028. colormap_index: data[offset++] | data[offset++] << 8,
  24029. colormap_length: data[offset++] | data[offset++] << 8,
  24030. colormap_size: data[offset++],
  24031. origin: [
  24032. data[offset++] | data[offset++] << 8,
  24033. data[offset++] | data[offset++] << 8
  24034. ],
  24035. width: data[offset++] | data[offset++] << 8,
  24036. height: data[offset++] | data[offset++] << 8,
  24037. pixel_size: data[offset++],
  24038. flags: data[offset++]
  24039. };
  24040. return header;
  24041. };
  24042. TGATools.UploadContent = function (gl, data) {
  24043. // Not enough data to contain header ?
  24044. if (data.length < 19) {
  24045. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  24046. return;
  24047. }
  24048. // Read Header
  24049. var offset = 18;
  24050. var header = TGATools.GetTGAHeader(data);
  24051. // Assume it's a valid Targa file.
  24052. if (header.id_length + offset > data.length) {
  24053. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  24054. return;
  24055. }
  24056. // Skip not needed data
  24057. offset += header.id_length;
  24058. var use_rle = false;
  24059. var use_pal = false;
  24060. var use_rgb = false;
  24061. var use_grey = false;
  24062. switch (header.image_type) {
  24063. case TGATools._TYPE_RLE_INDEXED:
  24064. use_rle = true;
  24065. case TGATools._TYPE_INDEXED:
  24066. use_pal = true;
  24067. break;
  24068. case TGATools._TYPE_RLE_RGB:
  24069. use_rle = true;
  24070. case TGATools._TYPE_RGB:
  24071. use_rgb = true;
  24072. break;
  24073. case TGATools._TYPE_RLE_GREY:
  24074. use_rle = true;
  24075. case TGATools._TYPE_GREY:
  24076. use_grey = true;
  24077. break;
  24078. }
  24079. var pixel_data;
  24080. var numAlphaBits = header.flags & 0xf;
  24081. var pixel_size = header.pixel_size >> 3;
  24082. var pixel_total = header.width * header.height * pixel_size;
  24083. // Read palettes
  24084. var palettes;
  24085. if (use_pal) {
  24086. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  24087. }
  24088. // Read LRE
  24089. if (use_rle) {
  24090. pixel_data = new Uint8Array(pixel_total);
  24091. var c, count, i;
  24092. var localOffset = 0;
  24093. var pixels = new Uint8Array(pixel_size);
  24094. while (offset < pixel_total && localOffset < pixel_total) {
  24095. c = data[offset++];
  24096. count = (c & 0x7f) + 1;
  24097. // RLE pixels
  24098. if (c & 0x80) {
  24099. for (i = 0; i < pixel_size; ++i) {
  24100. pixels[i] = data[offset++];
  24101. }
  24102. for (i = 0; i < count; ++i) {
  24103. pixel_data.set(pixels, localOffset + i * pixel_size);
  24104. }
  24105. localOffset += pixel_size * count;
  24106. }
  24107. else {
  24108. count *= pixel_size;
  24109. for (i = 0; i < count; ++i) {
  24110. pixel_data[localOffset + i] = data[offset++];
  24111. }
  24112. localOffset += count;
  24113. }
  24114. }
  24115. }
  24116. else {
  24117. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  24118. }
  24119. // Load to texture
  24120. var x_start, y_start, x_step, y_step, y_end, x_end;
  24121. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  24122. default:
  24123. case TGATools._ORIGIN_UL:
  24124. x_start = 0;
  24125. x_step = 1;
  24126. x_end = header.width;
  24127. y_start = 0;
  24128. y_step = 1;
  24129. y_end = header.height;
  24130. break;
  24131. case TGATools._ORIGIN_BL:
  24132. x_start = 0;
  24133. x_step = 1;
  24134. x_end = header.width;
  24135. y_start = header.height - 1;
  24136. y_step = -1;
  24137. y_end = -1;
  24138. break;
  24139. case TGATools._ORIGIN_UR:
  24140. x_start = header.width - 1;
  24141. x_step = -1;
  24142. x_end = -1;
  24143. y_start = 0;
  24144. y_step = 1;
  24145. y_end = header.height;
  24146. break;
  24147. case TGATools._ORIGIN_BR:
  24148. x_start = header.width - 1;
  24149. x_step = -1;
  24150. x_end = -1;
  24151. y_start = header.height - 1;
  24152. y_step = -1;
  24153. y_end = -1;
  24154. break;
  24155. }
  24156. // Load the specify method
  24157. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  24158. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  24159. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  24160. };
  24161. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24162. var image = pixel_data, colormap = palettes;
  24163. var width = header.width, height = header.height;
  24164. var color, i = 0, x, y;
  24165. var imageData = new Uint8Array(width * height * 4);
  24166. for (y = y_start; y !== y_end; y += y_step) {
  24167. for (x = x_start; x !== x_end; x += x_step, i++) {
  24168. color = image[i];
  24169. imageData[(x + width * y) * 4 + 3] = 255;
  24170. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  24171. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  24172. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  24173. }
  24174. }
  24175. return imageData;
  24176. };
  24177. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24178. var image = pixel_data;
  24179. var width = header.width, height = header.height;
  24180. var color, i = 0, x, y;
  24181. var imageData = new Uint8Array(width * height * 4);
  24182. for (y = y_start; y !== y_end; y += y_step) {
  24183. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  24184. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  24185. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  24186. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  24187. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  24188. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  24189. }
  24190. }
  24191. return imageData;
  24192. };
  24193. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24194. var image = pixel_data;
  24195. var width = header.width, height = header.height;
  24196. var i = 0, x, y;
  24197. var imageData = new Uint8Array(width * height * 4);
  24198. for (y = y_start; y !== y_end; y += y_step) {
  24199. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  24200. imageData[(x + width * y) * 4 + 3] = 255;
  24201. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24202. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  24203. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  24204. }
  24205. }
  24206. return imageData;
  24207. };
  24208. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24209. var image = pixel_data;
  24210. var width = header.width, height = header.height;
  24211. var i = 0, x, y;
  24212. var imageData = new Uint8Array(width * height * 4);
  24213. for (y = y_start; y !== y_end; y += y_step) {
  24214. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  24215. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24216. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  24217. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  24218. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  24219. }
  24220. }
  24221. return imageData;
  24222. };
  24223. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24224. var image = pixel_data;
  24225. var width = header.width, height = header.height;
  24226. var color, i = 0, x, y;
  24227. var imageData = new Uint8Array(width * height * 4);
  24228. for (y = y_start; y !== y_end; y += y_step) {
  24229. for (x = x_start; x !== x_end; x += x_step, i++) {
  24230. color = image[i];
  24231. imageData[(x + width * y) * 4 + 0] = color;
  24232. imageData[(x + width * y) * 4 + 1] = color;
  24233. imageData[(x + width * y) * 4 + 2] = color;
  24234. imageData[(x + width * y) * 4 + 3] = 255;
  24235. }
  24236. }
  24237. return imageData;
  24238. };
  24239. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24240. var image = pixel_data;
  24241. var width = header.width, height = header.height;
  24242. var i = 0, x, y;
  24243. var imageData = new Uint8Array(width * height * 4);
  24244. for (y = y_start; y !== y_end; y += y_step) {
  24245. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  24246. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  24247. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  24248. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24249. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  24250. }
  24251. }
  24252. return imageData;
  24253. };
  24254. TGATools._TYPE_NO_DATA = 0;
  24255. TGATools._TYPE_INDEXED = 1;
  24256. TGATools._TYPE_RGB = 2;
  24257. TGATools._TYPE_GREY = 3;
  24258. TGATools._TYPE_RLE_INDEXED = 9;
  24259. TGATools._TYPE_RLE_RGB = 10;
  24260. TGATools._TYPE_RLE_GREY = 11;
  24261. TGATools._ORIGIN_MASK = 0x30;
  24262. TGATools._ORIGIN_SHIFT = 0x04;
  24263. TGATools._ORIGIN_BL = 0x00;
  24264. TGATools._ORIGIN_BR = 0x01;
  24265. TGATools._ORIGIN_UL = 0x02;
  24266. TGATools._ORIGIN_UR = 0x03;
  24267. return TGATools;
  24268. })();
  24269. Internals.TGATools = TGATools;
  24270. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24271. })(BABYLON || (BABYLON = {}));
  24272. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  24273. (function (BABYLON) {
  24274. var Internals;
  24275. (function (Internals) {
  24276. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  24277. // All values and structures referenced from:
  24278. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  24279. var DDS_MAGIC = 0x20534444;
  24280. 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;
  24281. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  24282. 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;
  24283. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  24284. function FourCCToInt32(value) {
  24285. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  24286. }
  24287. function Int32ToFourCC(value) {
  24288. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  24289. }
  24290. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  24291. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  24292. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  24293. var headerLengthInt = 31; // The header length in 32 bit ints
  24294. // Offsets into the header array
  24295. var off_magic = 0;
  24296. var off_size = 1;
  24297. var off_flags = 2;
  24298. var off_height = 3;
  24299. var off_width = 4;
  24300. var off_mipmapCount = 7;
  24301. var off_pfFlags = 20;
  24302. var off_pfFourCC = 21;
  24303. var off_RGBbpp = 22;
  24304. var off_RMask = 23;
  24305. var off_GMask = 24;
  24306. var off_BMask = 25;
  24307. var off_AMask = 26;
  24308. var off_caps1 = 27;
  24309. var off_caps2 = 28;
  24310. ;
  24311. var DDSTools = (function () {
  24312. function DDSTools() {
  24313. }
  24314. DDSTools.GetDDSInfo = function (arrayBuffer) {
  24315. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  24316. var mipmapCount = 1;
  24317. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  24318. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24319. }
  24320. return {
  24321. width: header[off_width],
  24322. height: header[off_height],
  24323. mipmapCount: mipmapCount,
  24324. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  24325. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  24326. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  24327. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  24328. };
  24329. };
  24330. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24331. var byteArray = new Uint8Array(dataLength);
  24332. var srcData = new Uint8Array(arrayBuffer);
  24333. var index = 0;
  24334. for (var y = height - 1; y >= 0; y--) {
  24335. for (var x = 0; x < width; x++) {
  24336. var srcPos = dataOffset + (x + y * width) * 4;
  24337. byteArray[index + 2] = srcData[srcPos];
  24338. byteArray[index + 1] = srcData[srcPos + 1];
  24339. byteArray[index] = srcData[srcPos + 2];
  24340. byteArray[index + 3] = srcData[srcPos + 3];
  24341. index += 4;
  24342. }
  24343. }
  24344. return byteArray;
  24345. };
  24346. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24347. var byteArray = new Uint8Array(dataLength);
  24348. var srcData = new Uint8Array(arrayBuffer);
  24349. var index = 0;
  24350. for (var y = height - 1; y >= 0; y--) {
  24351. for (var x = 0; x < width; x++) {
  24352. var srcPos = dataOffset + (x + y * width) * 3;
  24353. byteArray[index + 2] = srcData[srcPos];
  24354. byteArray[index + 1] = srcData[srcPos + 1];
  24355. byteArray[index] = srcData[srcPos + 2];
  24356. index += 3;
  24357. }
  24358. }
  24359. return byteArray;
  24360. };
  24361. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24362. var byteArray = new Uint8Array(dataLength);
  24363. var srcData = new Uint8Array(arrayBuffer);
  24364. var index = 0;
  24365. for (var y = height - 1; y >= 0; y--) {
  24366. for (var x = 0; x < width; x++) {
  24367. var srcPos = dataOffset + (x + y * width);
  24368. byteArray[index] = srcData[srcPos];
  24369. index++;
  24370. }
  24371. }
  24372. return byteArray;
  24373. };
  24374. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  24375. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  24376. if (header[off_magic] != DDS_MAGIC) {
  24377. BABYLON.Tools.Error("Invalid magic number in DDS header");
  24378. return;
  24379. }
  24380. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  24381. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  24382. return;
  24383. }
  24384. if (info.isFourCC) {
  24385. fourCC = header[off_pfFourCC];
  24386. switch (fourCC) {
  24387. case FOURCC_DXT1:
  24388. blockBytes = 8;
  24389. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  24390. break;
  24391. case FOURCC_DXT3:
  24392. blockBytes = 16;
  24393. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  24394. break;
  24395. case FOURCC_DXT5:
  24396. blockBytes = 16;
  24397. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  24398. break;
  24399. default:
  24400. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  24401. return;
  24402. }
  24403. }
  24404. mipmapCount = 1;
  24405. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  24406. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24407. }
  24408. var bpp = header[off_RGBbpp];
  24409. for (var face = 0; face < faces; face++) {
  24410. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  24411. width = header[off_width];
  24412. height = header[off_height];
  24413. dataOffset = header[off_size] + 4;
  24414. for (i = 0; i < mipmapCount; ++i) {
  24415. if (info.isRGB) {
  24416. if (bpp == 24) {
  24417. dataLength = width * height * 3;
  24418. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24419. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  24420. }
  24421. else {
  24422. dataLength = width * height * 4;
  24423. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24424. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  24425. }
  24426. }
  24427. else if (info.isLuminance) {
  24428. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  24429. var unpaddedRowSize = width;
  24430. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  24431. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  24432. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24433. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  24434. }
  24435. else {
  24436. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  24437. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  24438. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  24439. }
  24440. dataOffset += dataLength;
  24441. width *= 0.5;
  24442. height *= 0.5;
  24443. width = Math.max(1.0, width);
  24444. height = Math.max(1.0, height);
  24445. }
  24446. }
  24447. };
  24448. return DDSTools;
  24449. })();
  24450. Internals.DDSTools = DDSTools;
  24451. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24452. })(BABYLON || (BABYLON = {}));
  24453. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  24454. (function (BABYLON) {
  24455. var SmartArray = (function () {
  24456. function SmartArray(capacity) {
  24457. this.length = 0;
  24458. this._duplicateId = 0;
  24459. this.data = new Array(capacity);
  24460. this._id = SmartArray._GlobalId++;
  24461. }
  24462. SmartArray.prototype.push = function (value) {
  24463. this.data[this.length++] = value;
  24464. if (this.length > this.data.length) {
  24465. this.data.length *= 2;
  24466. }
  24467. if (!value.__smartArrayFlags) {
  24468. value.__smartArrayFlags = {};
  24469. }
  24470. value.__smartArrayFlags[this._id] = this._duplicateId;
  24471. };
  24472. SmartArray.prototype.pushNoDuplicate = function (value) {
  24473. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  24474. return;
  24475. }
  24476. this.push(value);
  24477. };
  24478. SmartArray.prototype.sort = function (compareFn) {
  24479. this.data.sort(compareFn);
  24480. };
  24481. SmartArray.prototype.reset = function () {
  24482. this.length = 0;
  24483. this._duplicateId++;
  24484. };
  24485. SmartArray.prototype.concat = function (array) {
  24486. if (array.length === 0) {
  24487. return;
  24488. }
  24489. if (this.length + array.length > this.data.length) {
  24490. this.data.length = (this.length + array.length) * 2;
  24491. }
  24492. for (var index = 0; index < array.length; index++) {
  24493. this.data[this.length++] = (array.data || array)[index];
  24494. }
  24495. };
  24496. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  24497. if (array.length === 0) {
  24498. return;
  24499. }
  24500. if (this.length + array.length > this.data.length) {
  24501. this.data.length = (this.length + array.length) * 2;
  24502. }
  24503. for (var index = 0; index < array.length; index++) {
  24504. var item = (array.data || array)[index];
  24505. this.pushNoDuplicate(item);
  24506. }
  24507. };
  24508. SmartArray.prototype.indexOf = function (value) {
  24509. var position = this.data.indexOf(value);
  24510. if (position >= this.length) {
  24511. return -1;
  24512. }
  24513. return position;
  24514. };
  24515. // Statics
  24516. SmartArray._GlobalId = 0;
  24517. return SmartArray;
  24518. })();
  24519. BABYLON.SmartArray = SmartArray;
  24520. })(BABYLON || (BABYLON = {}));
  24521. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  24522. (function (BABYLON) {
  24523. var CannonJSPlugin = (function () {
  24524. function CannonJSPlugin() {
  24525. this._registeredMeshes = [];
  24526. this._physicsMaterials = [];
  24527. this.updateBodyPosition = function (mesh) {
  24528. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24529. var registeredMesh = this._registeredMeshes[index];
  24530. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24531. var body = registeredMesh.body;
  24532. var center = mesh.getBoundingInfo().boundingBox.center;
  24533. body.position.set(center.x, center.z, center.y);
  24534. body.quaternion.x = mesh.rotationQuaternion.x;
  24535. body.quaternion.z = mesh.rotationQuaternion.y;
  24536. body.quaternion.y = mesh.rotationQuaternion.z;
  24537. body.quaternion.w = -mesh.rotationQuaternion.w;
  24538. return;
  24539. }
  24540. }
  24541. };
  24542. }
  24543. CannonJSPlugin.prototype.initialize = function (iterations) {
  24544. if (iterations === void 0) { iterations = 10; }
  24545. this._world = new CANNON.World();
  24546. this._world.broadphase = new CANNON.NaiveBroadphase();
  24547. this._world.solver.iterations = iterations;
  24548. };
  24549. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  24550. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  24551. };
  24552. CannonJSPlugin.prototype.runOneStep = function (delta) {
  24553. this._world.step(delta);
  24554. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24555. var registeredMesh = this._registeredMeshes[index];
  24556. if (registeredMesh.isChild) {
  24557. continue;
  24558. }
  24559. // Body position
  24560. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  24561. var deltaPos = registeredMesh.delta;
  24562. if (deltaPos) {
  24563. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  24564. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  24565. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  24566. }
  24567. else {
  24568. registeredMesh.mesh.position.x = bodyX;
  24569. registeredMesh.mesh.position.y = bodyZ;
  24570. registeredMesh.mesh.position.z = bodyY;
  24571. }
  24572. if (!registeredMesh.mesh.rotationQuaternion) {
  24573. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24574. }
  24575. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  24576. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  24577. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  24578. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  24579. }
  24580. };
  24581. CannonJSPlugin.prototype.setGravity = function (gravity) {
  24582. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  24583. };
  24584. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  24585. this.unregisterMesh(mesh);
  24586. mesh.computeWorldMatrix(true);
  24587. switch (impostor) {
  24588. case BABYLON.PhysicsEngine.SphereImpostor:
  24589. var bbox = mesh.getBoundingInfo().boundingBox;
  24590. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24591. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24592. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24593. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  24594. case BABYLON.PhysicsEngine.BoxImpostor:
  24595. bbox = mesh.getBoundingInfo().boundingBox;
  24596. var min = bbox.minimumWorld;
  24597. var max = bbox.maximumWorld;
  24598. var box = max.subtract(min).scale(0.5);
  24599. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  24600. case BABYLON.PhysicsEngine.PlaneImpostor:
  24601. return this._createPlane(mesh, options);
  24602. case BABYLON.PhysicsEngine.MeshImpostor:
  24603. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24604. var rawFaces = mesh.getIndices();
  24605. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  24606. }
  24607. return null;
  24608. };
  24609. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  24610. var shape = new CANNON.Sphere(radius);
  24611. if (!options) {
  24612. return shape;
  24613. }
  24614. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24615. };
  24616. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  24617. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  24618. if (!options) {
  24619. return shape;
  24620. }
  24621. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24622. };
  24623. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  24624. var shape = new CANNON.Plane();
  24625. if (!options) {
  24626. return shape;
  24627. }
  24628. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24629. };
  24630. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  24631. var verts = [], faces = [];
  24632. mesh.computeWorldMatrix(true);
  24633. for (var i = 0; i < rawVerts.length; i += 3) {
  24634. var transformed = BABYLON.Vector3.Zero();
  24635. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  24636. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  24637. }
  24638. for (var j = 0; j < rawFaces.length; j += 3) {
  24639. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  24640. }
  24641. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  24642. if (!options) {
  24643. return shape;
  24644. }
  24645. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24646. };
  24647. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  24648. var index;
  24649. var mat;
  24650. for (index = 0; index < this._physicsMaterials.length; index++) {
  24651. mat = this._physicsMaterials[index];
  24652. if (mat.friction === friction && mat.restitution === restitution) {
  24653. return mat;
  24654. }
  24655. }
  24656. var currentMat = new CANNON.Material();
  24657. currentMat.friction = friction;
  24658. currentMat.restitution = restitution;
  24659. this._physicsMaterials.push(currentMat);
  24660. for (index = 0; index < this._physicsMaterials.length; index++) {
  24661. mat = this._physicsMaterials[index];
  24662. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  24663. contactMaterial.contactEquationStiffness = 1e10;
  24664. contactMaterial.contactEquationRegularizationTime = 10;
  24665. this._world.addContactMaterial(contactMaterial);
  24666. }
  24667. return currentMat;
  24668. };
  24669. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  24670. var initialRotation = null;
  24671. if (mesh.rotationQuaternion) {
  24672. initialRotation = mesh.rotationQuaternion.clone();
  24673. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24674. }
  24675. // The delta between the mesh position and the mesh bounding box center
  24676. var bbox = mesh.getBoundingInfo().boundingBox;
  24677. var deltaPosition = mesh.position.subtract(bbox.center);
  24678. var material = this._addMaterial(friction, restitution);
  24679. var body = new CANNON.RigidBody(mass, shape, material);
  24680. if (initialRotation) {
  24681. body.quaternion.x = initialRotation.x;
  24682. body.quaternion.z = initialRotation.y;
  24683. body.quaternion.y = initialRotation.z;
  24684. body.quaternion.w = -initialRotation.w;
  24685. }
  24686. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  24687. this._world.add(body);
  24688. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  24689. return body;
  24690. };
  24691. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24692. var compoundShape = new CANNON.Compound();
  24693. for (var index = 0; index < parts.length; index++) {
  24694. var mesh = parts[index].mesh;
  24695. var shape = this.registerMesh(mesh, parts[index].impostor);
  24696. if (index == 0) {
  24697. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  24698. }
  24699. else {
  24700. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  24701. }
  24702. }
  24703. var initialMesh = parts[0].mesh;
  24704. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  24705. body.parts = parts;
  24706. return body;
  24707. };
  24708. CannonJSPlugin.prototype._unbindBody = function (body) {
  24709. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24710. var registeredMesh = this._registeredMeshes[index];
  24711. if (registeredMesh.body === body) {
  24712. registeredMesh.body = null;
  24713. registeredMesh.delta = 0;
  24714. }
  24715. }
  24716. };
  24717. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  24718. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24719. var registeredMesh = this._registeredMeshes[index];
  24720. if (registeredMesh.mesh === mesh) {
  24721. // Remove body
  24722. if (registeredMesh.body) {
  24723. this._world.remove(registeredMesh.body);
  24724. this._unbindBody(registeredMesh.body);
  24725. }
  24726. this._registeredMeshes.splice(index, 1);
  24727. return;
  24728. }
  24729. }
  24730. };
  24731. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24732. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  24733. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  24734. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24735. var registeredMesh = this._registeredMeshes[index];
  24736. if (registeredMesh.mesh === mesh) {
  24737. registeredMesh.body.applyImpulse(impulse, worldPoint);
  24738. return;
  24739. }
  24740. }
  24741. };
  24742. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  24743. var body1 = null, body2 = null;
  24744. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24745. var registeredMesh = this._registeredMeshes[index];
  24746. if (registeredMesh.mesh === mesh1) {
  24747. body1 = registeredMesh.body;
  24748. }
  24749. else if (registeredMesh.mesh === mesh2) {
  24750. body2 = registeredMesh.body;
  24751. }
  24752. }
  24753. if (!body1 || !body2) {
  24754. return false;
  24755. }
  24756. 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));
  24757. this._world.addConstraint(constraint);
  24758. return true;
  24759. };
  24760. CannonJSPlugin.prototype.dispose = function () {
  24761. while (this._registeredMeshes.length) {
  24762. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24763. }
  24764. };
  24765. CannonJSPlugin.prototype.isSupported = function () {
  24766. return window.CANNON !== undefined;
  24767. };
  24768. return CannonJSPlugin;
  24769. })();
  24770. BABYLON.CannonJSPlugin = CannonJSPlugin;
  24771. })(BABYLON || (BABYLON = {}));
  24772. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  24773. var BABYLON;
  24774. (function (BABYLON) {
  24775. var Condition = (function () {
  24776. function Condition(actionManager) {
  24777. this._actionManager = actionManager;
  24778. }
  24779. Condition.prototype.isValid = function () {
  24780. return true;
  24781. };
  24782. Condition.prototype._getProperty = function (propertyPath) {
  24783. return this._actionManager._getProperty(propertyPath);
  24784. };
  24785. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  24786. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24787. };
  24788. return Condition;
  24789. })();
  24790. BABYLON.Condition = Condition;
  24791. var ValueCondition = (function (_super) {
  24792. __extends(ValueCondition, _super);
  24793. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  24794. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  24795. _super.call(this, actionManager);
  24796. this.propertyPath = propertyPath;
  24797. this.value = value;
  24798. this.operator = operator;
  24799. this._target = this._getEffectiveTarget(target, this.propertyPath);
  24800. this._property = this._getProperty(this.propertyPath);
  24801. }
  24802. Object.defineProperty(ValueCondition, "IsEqual", {
  24803. get: function () {
  24804. return ValueCondition._IsEqual;
  24805. },
  24806. enumerable: true,
  24807. configurable: true
  24808. });
  24809. Object.defineProperty(ValueCondition, "IsDifferent", {
  24810. get: function () {
  24811. return ValueCondition._IsDifferent;
  24812. },
  24813. enumerable: true,
  24814. configurable: true
  24815. });
  24816. Object.defineProperty(ValueCondition, "IsGreater", {
  24817. get: function () {
  24818. return ValueCondition._IsGreater;
  24819. },
  24820. enumerable: true,
  24821. configurable: true
  24822. });
  24823. Object.defineProperty(ValueCondition, "IsLesser", {
  24824. get: function () {
  24825. return ValueCondition._IsLesser;
  24826. },
  24827. enumerable: true,
  24828. configurable: true
  24829. });
  24830. // Methods
  24831. ValueCondition.prototype.isValid = function () {
  24832. switch (this.operator) {
  24833. case ValueCondition.IsGreater:
  24834. return this._target[this._property] > this.value;
  24835. case ValueCondition.IsLesser:
  24836. return this._target[this._property] < this.value;
  24837. case ValueCondition.IsEqual:
  24838. case ValueCondition.IsDifferent:
  24839. var check;
  24840. if (this.value.equals) {
  24841. check = this.value.equals(this._target[this._property]);
  24842. }
  24843. else {
  24844. check = this.value === this._target[this._property];
  24845. }
  24846. return this.operator === ValueCondition.IsEqual ? check : !check;
  24847. }
  24848. return false;
  24849. };
  24850. // Statics
  24851. ValueCondition._IsEqual = 0;
  24852. ValueCondition._IsDifferent = 1;
  24853. ValueCondition._IsGreater = 2;
  24854. ValueCondition._IsLesser = 3;
  24855. return ValueCondition;
  24856. })(Condition);
  24857. BABYLON.ValueCondition = ValueCondition;
  24858. var PredicateCondition = (function (_super) {
  24859. __extends(PredicateCondition, _super);
  24860. function PredicateCondition(actionManager, predicate) {
  24861. _super.call(this, actionManager);
  24862. this.predicate = predicate;
  24863. }
  24864. PredicateCondition.prototype.isValid = function () {
  24865. return this.predicate();
  24866. };
  24867. return PredicateCondition;
  24868. })(Condition);
  24869. BABYLON.PredicateCondition = PredicateCondition;
  24870. var StateCondition = (function (_super) {
  24871. __extends(StateCondition, _super);
  24872. function StateCondition(actionManager, target, value) {
  24873. _super.call(this, actionManager);
  24874. this.value = value;
  24875. this._target = target;
  24876. }
  24877. // Methods
  24878. StateCondition.prototype.isValid = function () {
  24879. return this._target.state === this.value;
  24880. };
  24881. return StateCondition;
  24882. })(Condition);
  24883. BABYLON.StateCondition = StateCondition;
  24884. })(BABYLON || (BABYLON = {}));
  24885. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  24886. (function (BABYLON) {
  24887. var Action = (function () {
  24888. function Action(triggerOptions, condition) {
  24889. this.triggerOptions = triggerOptions;
  24890. if (triggerOptions.parameter) {
  24891. this.trigger = triggerOptions.trigger;
  24892. this._triggerParameter = triggerOptions.parameter;
  24893. }
  24894. else {
  24895. this.trigger = triggerOptions;
  24896. }
  24897. this._nextActiveAction = this;
  24898. this._condition = condition;
  24899. }
  24900. // Methods
  24901. Action.prototype._prepare = function () {
  24902. };
  24903. Action.prototype.getTriggerParameter = function () {
  24904. return this._triggerParameter;
  24905. };
  24906. Action.prototype._executeCurrent = function (evt) {
  24907. if (this._nextActiveAction._condition) {
  24908. var condition = this._nextActiveAction._condition;
  24909. var currentRenderId = this._actionManager.getScene().getRenderId();
  24910. // We cache the current evaluation for the current frame
  24911. if (condition._evaluationId === currentRenderId) {
  24912. if (!condition._currentResult) {
  24913. return;
  24914. }
  24915. }
  24916. else {
  24917. condition._evaluationId = currentRenderId;
  24918. if (!condition.isValid()) {
  24919. condition._currentResult = false;
  24920. return;
  24921. }
  24922. condition._currentResult = true;
  24923. }
  24924. }
  24925. this._nextActiveAction.execute(evt);
  24926. if (this._nextActiveAction._child) {
  24927. if (!this._nextActiveAction._child._actionManager) {
  24928. this._nextActiveAction._child._actionManager = this._actionManager;
  24929. }
  24930. this._nextActiveAction = this._nextActiveAction._child;
  24931. }
  24932. else {
  24933. this._nextActiveAction = this;
  24934. }
  24935. };
  24936. Action.prototype.execute = function (evt) {
  24937. };
  24938. Action.prototype.then = function (action) {
  24939. this._child = action;
  24940. action._actionManager = this._actionManager;
  24941. action._prepare();
  24942. return action;
  24943. };
  24944. Action.prototype._getProperty = function (propertyPath) {
  24945. return this._actionManager._getProperty(propertyPath);
  24946. };
  24947. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24948. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24949. };
  24950. return Action;
  24951. })();
  24952. BABYLON.Action = Action;
  24953. })(BABYLON || (BABYLON = {}));
  24954. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  24955. (function (BABYLON) {
  24956. /**
  24957. * ActionEvent is the event beint sent when an action is triggered.
  24958. */
  24959. var ActionEvent = (function () {
  24960. /**
  24961. * @constructor
  24962. * @param source The mesh that triggered the action.
  24963. * @param pointerX the X mouse cursor position at the time of the event
  24964. * @param pointerY the Y mouse cursor position at the time of the event
  24965. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24966. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24967. */
  24968. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  24969. this.source = source;
  24970. this.pointerX = pointerX;
  24971. this.pointerY = pointerY;
  24972. this.meshUnderPointer = meshUnderPointer;
  24973. this.sourceEvent = sourceEvent;
  24974. }
  24975. /**
  24976. * Helper function to auto-create an ActionEvent from a source mesh.
  24977. * @param source the source mesh that triggered the event
  24978. * @param evt {Event} The original (browser) event
  24979. */
  24980. ActionEvent.CreateNew = function (source, evt) {
  24981. var scene = source.getScene();
  24982. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24983. };
  24984. /**
  24985. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24986. * @param scene the scene where the event occurred
  24987. * @param evt {Event} The original (browser) event
  24988. */
  24989. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24990. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24991. };
  24992. return ActionEvent;
  24993. })();
  24994. BABYLON.ActionEvent = ActionEvent;
  24995. /**
  24996. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24997. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24998. */
  24999. var ActionManager = (function () {
  25000. function ActionManager(scene) {
  25001. // Members
  25002. this.actions = new Array();
  25003. this._scene = scene;
  25004. scene._actionManagers.push(this);
  25005. }
  25006. Object.defineProperty(ActionManager, "NothingTrigger", {
  25007. get: function () {
  25008. return ActionManager._NothingTrigger;
  25009. },
  25010. enumerable: true,
  25011. configurable: true
  25012. });
  25013. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25014. get: function () {
  25015. return ActionManager._OnPickTrigger;
  25016. },
  25017. enumerable: true,
  25018. configurable: true
  25019. });
  25020. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25021. get: function () {
  25022. return ActionManager._OnLeftPickTrigger;
  25023. },
  25024. enumerable: true,
  25025. configurable: true
  25026. });
  25027. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25028. get: function () {
  25029. return ActionManager._OnRightPickTrigger;
  25030. },
  25031. enumerable: true,
  25032. configurable: true
  25033. });
  25034. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25035. get: function () {
  25036. return ActionManager._OnCenterPickTrigger;
  25037. },
  25038. enumerable: true,
  25039. configurable: true
  25040. });
  25041. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25042. get: function () {
  25043. return ActionManager._OnPointerOverTrigger;
  25044. },
  25045. enumerable: true,
  25046. configurable: true
  25047. });
  25048. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25049. get: function () {
  25050. return ActionManager._OnPointerOutTrigger;
  25051. },
  25052. enumerable: true,
  25053. configurable: true
  25054. });
  25055. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25056. get: function () {
  25057. return ActionManager._OnEveryFrameTrigger;
  25058. },
  25059. enumerable: true,
  25060. configurable: true
  25061. });
  25062. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25063. get: function () {
  25064. return ActionManager._OnIntersectionEnterTrigger;
  25065. },
  25066. enumerable: true,
  25067. configurable: true
  25068. });
  25069. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25070. get: function () {
  25071. return ActionManager._OnIntersectionExitTrigger;
  25072. },
  25073. enumerable: true,
  25074. configurable: true
  25075. });
  25076. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25077. get: function () {
  25078. return ActionManager._OnKeyDownTrigger;
  25079. },
  25080. enumerable: true,
  25081. configurable: true
  25082. });
  25083. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25084. get: function () {
  25085. return ActionManager._OnKeyUpTrigger;
  25086. },
  25087. enumerable: true,
  25088. configurable: true
  25089. });
  25090. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25091. get: function () {
  25092. return ActionManager._OnPickUpTrigger;
  25093. },
  25094. enumerable: true,
  25095. configurable: true
  25096. });
  25097. // Methods
  25098. ActionManager.prototype.dispose = function () {
  25099. var index = this._scene._actionManagers.indexOf(this);
  25100. if (index > -1) {
  25101. this._scene._actionManagers.splice(index, 1);
  25102. }
  25103. };
  25104. ActionManager.prototype.getScene = function () {
  25105. return this._scene;
  25106. };
  25107. /**
  25108. * Does this action manager handles actions of any of the given triggers
  25109. * @param {number[]} triggers - the triggers to be tested
  25110. * @return {boolean} whether one (or more) of the triggers is handeled
  25111. */
  25112. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25113. for (var index = 0; index < this.actions.length; index++) {
  25114. var action = this.actions[index];
  25115. if (triggers.indexOf(action.trigger) > -1) {
  25116. return true;
  25117. }
  25118. }
  25119. return false;
  25120. };
  25121. /**
  25122. * Does this action manager handles actions of a given trigger
  25123. * @param {number} trigger - the trigger to be tested
  25124. * @return {boolean} whether the trigger is handeled
  25125. */
  25126. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25127. for (var index = 0; index < this.actions.length; index++) {
  25128. var action = this.actions[index];
  25129. if (action.trigger === trigger) {
  25130. return true;
  25131. }
  25132. }
  25133. return false;
  25134. };
  25135. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25136. /**
  25137. * Does this action manager has pointer triggers
  25138. * @return {boolean} whether or not it has pointer triggers
  25139. */
  25140. get: function () {
  25141. for (var index = 0; index < this.actions.length; index++) {
  25142. var action = this.actions[index];
  25143. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25144. return true;
  25145. }
  25146. if (action.trigger == ActionManager._OnPickUpTrigger) {
  25147. return true;
  25148. }
  25149. }
  25150. return false;
  25151. },
  25152. enumerable: true,
  25153. configurable: true
  25154. });
  25155. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25156. /**
  25157. * Does this action manager has pick triggers
  25158. * @return {boolean} whether or not it has pick triggers
  25159. */
  25160. get: function () {
  25161. for (var index = 0; index < this.actions.length; index++) {
  25162. var action = this.actions[index];
  25163. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25164. return true;
  25165. }
  25166. }
  25167. return false;
  25168. },
  25169. enumerable: true,
  25170. configurable: true
  25171. });
  25172. /**
  25173. * Registers an action to this action manager
  25174. * @param {BABYLON.Action} action - the action to be registered
  25175. * @return {BABYLON.Action} the action amended (prepared) after registration
  25176. */
  25177. ActionManager.prototype.registerAction = function (action) {
  25178. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25179. if (this.getScene().actionManager !== this) {
  25180. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25181. return null;
  25182. }
  25183. }
  25184. this.actions.push(action);
  25185. action._actionManager = this;
  25186. action._prepare();
  25187. return action;
  25188. };
  25189. /**
  25190. * Process a specific trigger
  25191. * @param {number} trigger - the trigger to process
  25192. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25193. */
  25194. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25195. for (var index = 0; index < this.actions.length; index++) {
  25196. var action = this.actions[index];
  25197. if (action.trigger === trigger) {
  25198. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  25199. var parameter = action.getTriggerParameter();
  25200. if (parameter) {
  25201. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25202. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25203. if (actualkey !== parameter.toLowerCase()) {
  25204. continue;
  25205. }
  25206. }
  25207. }
  25208. action._executeCurrent(evt);
  25209. }
  25210. }
  25211. };
  25212. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25213. var properties = propertyPath.split(".");
  25214. for (var index = 0; index < properties.length - 1; index++) {
  25215. target = target[properties[index]];
  25216. }
  25217. return target;
  25218. };
  25219. ActionManager.prototype._getProperty = function (propertyPath) {
  25220. var properties = propertyPath.split(".");
  25221. return properties[properties.length - 1];
  25222. };
  25223. // Statics
  25224. ActionManager._NothingTrigger = 0;
  25225. ActionManager._OnPickTrigger = 1;
  25226. ActionManager._OnLeftPickTrigger = 2;
  25227. ActionManager._OnRightPickTrigger = 3;
  25228. ActionManager._OnCenterPickTrigger = 4;
  25229. ActionManager._OnPointerOverTrigger = 5;
  25230. ActionManager._OnPointerOutTrigger = 6;
  25231. ActionManager._OnEveryFrameTrigger = 7;
  25232. ActionManager._OnIntersectionEnterTrigger = 8;
  25233. ActionManager._OnIntersectionExitTrigger = 9;
  25234. ActionManager._OnKeyDownTrigger = 10;
  25235. ActionManager._OnKeyUpTrigger = 11;
  25236. ActionManager._OnPickUpTrigger = 12;
  25237. return ActionManager;
  25238. })();
  25239. BABYLON.ActionManager = ActionManager;
  25240. })(BABYLON || (BABYLON = {}));
  25241. //# sourceMappingURL=babylon.actionManager.js.map
  25242. var BABYLON;
  25243. (function (BABYLON) {
  25244. var InterpolateValueAction = (function (_super) {
  25245. __extends(InterpolateValueAction, _super);
  25246. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  25247. if (duration === void 0) { duration = 1000; }
  25248. _super.call(this, triggerOptions, condition);
  25249. this.propertyPath = propertyPath;
  25250. this.value = value;
  25251. this.duration = duration;
  25252. this.stopOtherAnimations = stopOtherAnimations;
  25253. this._target = target;
  25254. }
  25255. InterpolateValueAction.prototype._prepare = function () {
  25256. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25257. this._property = this._getProperty(this.propertyPath);
  25258. };
  25259. InterpolateValueAction.prototype.execute = function () {
  25260. var scene = this._actionManager.getScene();
  25261. var keys = [
  25262. {
  25263. frame: 0,
  25264. value: this._target[this._property]
  25265. },
  25266. {
  25267. frame: 100,
  25268. value: this.value
  25269. }
  25270. ];
  25271. var dataType;
  25272. if (typeof this.value === "number") {
  25273. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25274. }
  25275. else if (this.value instanceof BABYLON.Color3) {
  25276. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25277. }
  25278. else if (this.value instanceof BABYLON.Vector3) {
  25279. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25280. }
  25281. else if (this.value instanceof BABYLON.Matrix) {
  25282. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25283. }
  25284. else if (this.value instanceof BABYLON.Quaternion) {
  25285. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25286. }
  25287. else {
  25288. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25289. return;
  25290. }
  25291. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25292. animation.setKeys(keys);
  25293. if (this.stopOtherAnimations) {
  25294. scene.stopAnimation(this._target);
  25295. }
  25296. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  25297. };
  25298. return InterpolateValueAction;
  25299. })(BABYLON.Action);
  25300. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25301. })(BABYLON || (BABYLON = {}));
  25302. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  25303. var BABYLON;
  25304. (function (BABYLON) {
  25305. var SwitchBooleanAction = (function (_super) {
  25306. __extends(SwitchBooleanAction, _super);
  25307. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25308. _super.call(this, triggerOptions, condition);
  25309. this.propertyPath = propertyPath;
  25310. this._target = target;
  25311. }
  25312. SwitchBooleanAction.prototype._prepare = function () {
  25313. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25314. this._property = this._getProperty(this.propertyPath);
  25315. };
  25316. SwitchBooleanAction.prototype.execute = function () {
  25317. this._target[this._property] = !this._target[this._property];
  25318. };
  25319. return SwitchBooleanAction;
  25320. })(BABYLON.Action);
  25321. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25322. var SetStateAction = (function (_super) {
  25323. __extends(SetStateAction, _super);
  25324. function SetStateAction(triggerOptions, target, value, condition) {
  25325. _super.call(this, triggerOptions, condition);
  25326. this.value = value;
  25327. this._target = target;
  25328. }
  25329. SetStateAction.prototype.execute = function () {
  25330. this._target.state = this.value;
  25331. };
  25332. return SetStateAction;
  25333. })(BABYLON.Action);
  25334. BABYLON.SetStateAction = SetStateAction;
  25335. var SetValueAction = (function (_super) {
  25336. __extends(SetValueAction, _super);
  25337. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25338. _super.call(this, triggerOptions, condition);
  25339. this.propertyPath = propertyPath;
  25340. this.value = value;
  25341. this._target = target;
  25342. }
  25343. SetValueAction.prototype._prepare = function () {
  25344. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25345. this._property = this._getProperty(this.propertyPath);
  25346. };
  25347. SetValueAction.prototype.execute = function () {
  25348. this._target[this._property] = this.value;
  25349. };
  25350. return SetValueAction;
  25351. })(BABYLON.Action);
  25352. BABYLON.SetValueAction = SetValueAction;
  25353. var IncrementValueAction = (function (_super) {
  25354. __extends(IncrementValueAction, _super);
  25355. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25356. _super.call(this, triggerOptions, condition);
  25357. this.propertyPath = propertyPath;
  25358. this.value = value;
  25359. this._target = target;
  25360. }
  25361. IncrementValueAction.prototype._prepare = function () {
  25362. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25363. this._property = this._getProperty(this.propertyPath);
  25364. if (typeof this._target[this._property] !== "number") {
  25365. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25366. }
  25367. };
  25368. IncrementValueAction.prototype.execute = function () {
  25369. this._target[this._property] += this.value;
  25370. };
  25371. return IncrementValueAction;
  25372. })(BABYLON.Action);
  25373. BABYLON.IncrementValueAction = IncrementValueAction;
  25374. var PlayAnimationAction = (function (_super) {
  25375. __extends(PlayAnimationAction, _super);
  25376. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25377. _super.call(this, triggerOptions, condition);
  25378. this.from = from;
  25379. this.to = to;
  25380. this.loop = loop;
  25381. this._target = target;
  25382. }
  25383. PlayAnimationAction.prototype._prepare = function () {
  25384. };
  25385. PlayAnimationAction.prototype.execute = function () {
  25386. var scene = this._actionManager.getScene();
  25387. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25388. };
  25389. return PlayAnimationAction;
  25390. })(BABYLON.Action);
  25391. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25392. var StopAnimationAction = (function (_super) {
  25393. __extends(StopAnimationAction, _super);
  25394. function StopAnimationAction(triggerOptions, target, condition) {
  25395. _super.call(this, triggerOptions, condition);
  25396. this._target = target;
  25397. }
  25398. StopAnimationAction.prototype._prepare = function () {
  25399. };
  25400. StopAnimationAction.prototype.execute = function () {
  25401. var scene = this._actionManager.getScene();
  25402. scene.stopAnimation(this._target);
  25403. };
  25404. return StopAnimationAction;
  25405. })(BABYLON.Action);
  25406. BABYLON.StopAnimationAction = StopAnimationAction;
  25407. var DoNothingAction = (function (_super) {
  25408. __extends(DoNothingAction, _super);
  25409. function DoNothingAction(triggerOptions, condition) {
  25410. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25411. _super.call(this, triggerOptions, condition);
  25412. }
  25413. DoNothingAction.prototype.execute = function () {
  25414. };
  25415. return DoNothingAction;
  25416. })(BABYLON.Action);
  25417. BABYLON.DoNothingAction = DoNothingAction;
  25418. var CombineAction = (function (_super) {
  25419. __extends(CombineAction, _super);
  25420. function CombineAction(triggerOptions, children, condition) {
  25421. _super.call(this, triggerOptions, condition);
  25422. this.children = children;
  25423. }
  25424. CombineAction.prototype._prepare = function () {
  25425. for (var index = 0; index < this.children.length; index++) {
  25426. this.children[index]._actionManager = this._actionManager;
  25427. this.children[index]._prepare();
  25428. }
  25429. };
  25430. CombineAction.prototype.execute = function (evt) {
  25431. for (var index = 0; index < this.children.length; index++) {
  25432. this.children[index].execute(evt);
  25433. }
  25434. };
  25435. return CombineAction;
  25436. })(BABYLON.Action);
  25437. BABYLON.CombineAction = CombineAction;
  25438. var ExecuteCodeAction = (function (_super) {
  25439. __extends(ExecuteCodeAction, _super);
  25440. function ExecuteCodeAction(triggerOptions, func, condition) {
  25441. _super.call(this, triggerOptions, condition);
  25442. this.func = func;
  25443. }
  25444. ExecuteCodeAction.prototype.execute = function (evt) {
  25445. this.func(evt);
  25446. };
  25447. return ExecuteCodeAction;
  25448. })(BABYLON.Action);
  25449. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25450. var SetParentAction = (function (_super) {
  25451. __extends(SetParentAction, _super);
  25452. function SetParentAction(triggerOptions, target, parent, condition) {
  25453. _super.call(this, triggerOptions, condition);
  25454. this._target = target;
  25455. this._parent = parent;
  25456. }
  25457. SetParentAction.prototype._prepare = function () {
  25458. };
  25459. SetParentAction.prototype.execute = function () {
  25460. if (this._target.parent === this._parent) {
  25461. return;
  25462. }
  25463. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25464. invertParentWorldMatrix.invert();
  25465. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25466. this._target.parent = this._parent;
  25467. };
  25468. return SetParentAction;
  25469. })(BABYLON.Action);
  25470. BABYLON.SetParentAction = SetParentAction;
  25471. var PlaySoundAction = (function (_super) {
  25472. __extends(PlaySoundAction, _super);
  25473. function PlaySoundAction(triggerOptions, sound, condition) {
  25474. _super.call(this, triggerOptions, condition);
  25475. this._sound = sound;
  25476. }
  25477. PlaySoundAction.prototype._prepare = function () {
  25478. };
  25479. PlaySoundAction.prototype.execute = function () {
  25480. if (this._sound !== undefined)
  25481. this._sound.play();
  25482. };
  25483. return PlaySoundAction;
  25484. })(BABYLON.Action);
  25485. BABYLON.PlaySoundAction = PlaySoundAction;
  25486. var StopSoundAction = (function (_super) {
  25487. __extends(StopSoundAction, _super);
  25488. function StopSoundAction(triggerOptions, sound, condition) {
  25489. _super.call(this, triggerOptions, condition);
  25490. this._sound = sound;
  25491. }
  25492. StopSoundAction.prototype._prepare = function () {
  25493. };
  25494. StopSoundAction.prototype.execute = function () {
  25495. if (this._sound !== undefined)
  25496. this._sound.stop();
  25497. };
  25498. return StopSoundAction;
  25499. })(BABYLON.Action);
  25500. BABYLON.StopSoundAction = StopSoundAction;
  25501. })(BABYLON || (BABYLON = {}));
  25502. //# sourceMappingURL=babylon.directActions.js.map
  25503. var BABYLON;
  25504. (function (BABYLON) {
  25505. var Geometry = (function () {
  25506. function Geometry(id, scene, vertexData, updatable, mesh) {
  25507. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25508. this._totalVertices = 0;
  25509. this._indices = [];
  25510. this._isDisposed = false;
  25511. this.id = id;
  25512. this._engine = scene.getEngine();
  25513. this._meshes = [];
  25514. this._scene = scene;
  25515. // vertexData
  25516. if (vertexData) {
  25517. this.setAllVerticesData(vertexData, updatable);
  25518. }
  25519. else {
  25520. this._totalVertices = 0;
  25521. this._indices = [];
  25522. }
  25523. // applyToMesh
  25524. if (mesh) {
  25525. this.applyToMesh(mesh);
  25526. mesh.computeWorldMatrix(true);
  25527. }
  25528. }
  25529. Geometry.prototype.getScene = function () {
  25530. return this._scene;
  25531. };
  25532. Geometry.prototype.getEngine = function () {
  25533. return this._engine;
  25534. };
  25535. Geometry.prototype.isReady = function () {
  25536. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25537. };
  25538. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25539. vertexData.applyToGeometry(this, updatable);
  25540. this.notifyUpdate();
  25541. };
  25542. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25543. this._vertexBuffers = this._vertexBuffers || {};
  25544. if (this._vertexBuffers[kind]) {
  25545. this._vertexBuffers[kind].dispose();
  25546. }
  25547. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25548. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25549. stride = this._vertexBuffers[kind].getStrideSize();
  25550. this._totalVertices = data.length / stride;
  25551. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25552. var meshes = this._meshes;
  25553. var numOfMeshes = meshes.length;
  25554. for (var index = 0; index < numOfMeshes; index++) {
  25555. var mesh = meshes[index];
  25556. mesh._resetPointsArrayCache();
  25557. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25558. mesh._createGlobalSubMesh();
  25559. mesh.computeWorldMatrix(true);
  25560. }
  25561. }
  25562. this.notifyUpdate(kind);
  25563. };
  25564. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25565. var vertexBuffer = this.getVertexBuffer(kind);
  25566. if (!vertexBuffer) {
  25567. return;
  25568. }
  25569. vertexBuffer.updateDirectly(data, offset);
  25570. this.notifyUpdate(kind);
  25571. };
  25572. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25573. var vertexBuffer = this.getVertexBuffer(kind);
  25574. if (!vertexBuffer) {
  25575. return;
  25576. }
  25577. vertexBuffer.update(data);
  25578. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25579. var extend;
  25580. var stride = vertexBuffer.getStrideSize();
  25581. this._totalVertices = data.length / stride;
  25582. if (updateExtends) {
  25583. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25584. }
  25585. var meshes = this._meshes;
  25586. var numOfMeshes = meshes.length;
  25587. for (var index = 0; index < numOfMeshes; index++) {
  25588. var mesh = meshes[index];
  25589. mesh._resetPointsArrayCache();
  25590. if (updateExtends) {
  25591. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25592. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25593. var subMesh = mesh.subMeshes[subIndex];
  25594. subMesh.refreshBoundingInfo();
  25595. }
  25596. }
  25597. }
  25598. }
  25599. this.notifyUpdate(kind);
  25600. };
  25601. Geometry.prototype.getTotalVertices = function () {
  25602. if (!this.isReady()) {
  25603. return 0;
  25604. }
  25605. return this._totalVertices;
  25606. };
  25607. Geometry.prototype.getVerticesData = function (kind) {
  25608. var vertexBuffer = this.getVertexBuffer(kind);
  25609. if (!vertexBuffer) {
  25610. return null;
  25611. }
  25612. return vertexBuffer.getData();
  25613. };
  25614. Geometry.prototype.getVertexBuffer = function (kind) {
  25615. if (!this.isReady()) {
  25616. return null;
  25617. }
  25618. return this._vertexBuffers[kind];
  25619. };
  25620. Geometry.prototype.getVertexBuffers = function () {
  25621. if (!this.isReady()) {
  25622. return null;
  25623. }
  25624. return this._vertexBuffers;
  25625. };
  25626. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25627. if (!this._vertexBuffers) {
  25628. if (this._delayInfo) {
  25629. return this._delayInfo.indexOf(kind) !== -1;
  25630. }
  25631. return false;
  25632. }
  25633. return this._vertexBuffers[kind] !== undefined;
  25634. };
  25635. Geometry.prototype.getVerticesDataKinds = function () {
  25636. var result = [];
  25637. if (!this._vertexBuffers && this._delayInfo) {
  25638. for (var kind in this._delayInfo) {
  25639. result.push(kind);
  25640. }
  25641. }
  25642. else {
  25643. for (kind in this._vertexBuffers) {
  25644. result.push(kind);
  25645. }
  25646. }
  25647. return result;
  25648. };
  25649. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25650. if (this._indexBuffer) {
  25651. this._engine._releaseBuffer(this._indexBuffer);
  25652. }
  25653. this._indices = indices;
  25654. if (this._meshes.length !== 0 && this._indices) {
  25655. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25656. }
  25657. if (totalVertices !== undefined) {
  25658. this._totalVertices = totalVertices;
  25659. }
  25660. var meshes = this._meshes;
  25661. var numOfMeshes = meshes.length;
  25662. for (var index = 0; index < numOfMeshes; index++) {
  25663. meshes[index]._createGlobalSubMesh();
  25664. }
  25665. this.notifyUpdate();
  25666. };
  25667. Geometry.prototype.getTotalIndices = function () {
  25668. if (!this.isReady()) {
  25669. return 0;
  25670. }
  25671. return this._indices.length;
  25672. };
  25673. Geometry.prototype.getIndices = function () {
  25674. if (!this.isReady()) {
  25675. return null;
  25676. }
  25677. return this._indices;
  25678. };
  25679. Geometry.prototype.getIndexBuffer = function () {
  25680. if (!this.isReady()) {
  25681. return null;
  25682. }
  25683. return this._indexBuffer;
  25684. };
  25685. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25686. var meshes = this._meshes;
  25687. var index = meshes.indexOf(mesh);
  25688. if (index === -1) {
  25689. return;
  25690. }
  25691. for (var kind in this._vertexBuffers) {
  25692. this._vertexBuffers[kind].dispose();
  25693. }
  25694. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25695. this._indexBuffer = null;
  25696. }
  25697. meshes.splice(index, 1);
  25698. mesh._geometry = null;
  25699. if (meshes.length === 0 && shouldDispose) {
  25700. this.dispose();
  25701. }
  25702. };
  25703. Geometry.prototype.applyToMesh = function (mesh) {
  25704. if (mesh._geometry === this) {
  25705. return;
  25706. }
  25707. var previousGeometry = mesh._geometry;
  25708. if (previousGeometry) {
  25709. previousGeometry.releaseForMesh(mesh);
  25710. }
  25711. var meshes = this._meshes;
  25712. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25713. mesh._geometry = this;
  25714. this._scene.pushGeometry(this);
  25715. meshes.push(mesh);
  25716. if (this.isReady()) {
  25717. this._applyToMesh(mesh);
  25718. }
  25719. else {
  25720. mesh._boundingInfo = this._boundingInfo;
  25721. }
  25722. };
  25723. Geometry.prototype._applyToMesh = function (mesh) {
  25724. var numOfMeshes = this._meshes.length;
  25725. for (var kind in this._vertexBuffers) {
  25726. if (numOfMeshes === 1) {
  25727. this._vertexBuffers[kind].create();
  25728. }
  25729. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  25730. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25731. mesh._resetPointsArrayCache();
  25732. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  25733. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25734. mesh._createGlobalSubMesh();
  25735. //bounding info was just created again, world matrix should be applied again.
  25736. mesh._updateBoundingInfo();
  25737. }
  25738. }
  25739. // indexBuffer
  25740. if (numOfMeshes === 1 && this._indices) {
  25741. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25742. }
  25743. if (this._indexBuffer) {
  25744. this._indexBuffer.references = numOfMeshes;
  25745. }
  25746. };
  25747. Geometry.prototype.notifyUpdate = function (kind) {
  25748. if (this.onGeometryUpdated) {
  25749. this.onGeometryUpdated(this, kind);
  25750. }
  25751. };
  25752. Geometry.prototype.load = function (scene, onLoaded) {
  25753. var _this = this;
  25754. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25755. return;
  25756. }
  25757. if (this.isReady()) {
  25758. if (onLoaded) {
  25759. onLoaded();
  25760. }
  25761. return;
  25762. }
  25763. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25764. scene._addPendingData(this);
  25765. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25766. _this._delayLoadingFunction(JSON.parse(data), _this);
  25767. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25768. _this._delayInfo = [];
  25769. scene._removePendingData(_this);
  25770. var meshes = _this._meshes;
  25771. var numOfMeshes = meshes.length;
  25772. for (var index = 0; index < numOfMeshes; index++) {
  25773. _this._applyToMesh(meshes[index]);
  25774. }
  25775. if (onLoaded) {
  25776. onLoaded();
  25777. }
  25778. }, function () {
  25779. }, scene.database);
  25780. };
  25781. Geometry.prototype.isDisposed = function () {
  25782. return this._isDisposed;
  25783. };
  25784. Geometry.prototype.dispose = function () {
  25785. var meshes = this._meshes;
  25786. var numOfMeshes = meshes.length;
  25787. var index;
  25788. for (index = 0; index < numOfMeshes; index++) {
  25789. this.releaseForMesh(meshes[index]);
  25790. }
  25791. this._meshes = [];
  25792. for (var kind in this._vertexBuffers) {
  25793. this._vertexBuffers[kind].dispose();
  25794. }
  25795. this._vertexBuffers = [];
  25796. this._totalVertices = 0;
  25797. if (this._indexBuffer) {
  25798. this._engine._releaseBuffer(this._indexBuffer);
  25799. }
  25800. this._indexBuffer = null;
  25801. this._indices = [];
  25802. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25803. this.delayLoadingFile = null;
  25804. this._delayLoadingFunction = null;
  25805. this._delayInfo = [];
  25806. this._boundingInfo = null; // todo: .dispose()
  25807. this._scene.removeGeometry(this);
  25808. this._isDisposed = true;
  25809. };
  25810. Geometry.prototype.copy = function (id) {
  25811. var vertexData = new BABYLON.VertexData();
  25812. vertexData.indices = [];
  25813. var indices = this.getIndices();
  25814. for (var index = 0; index < indices.length; index++) {
  25815. vertexData.indices.push(indices[index]);
  25816. }
  25817. var updatable = false;
  25818. var stopChecking = false;
  25819. for (var kind in this._vertexBuffers) {
  25820. // using slice() to make a copy of the array and not just reference it
  25821. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  25822. if (!stopChecking) {
  25823. updatable = this.getVertexBuffer(kind).isUpdatable();
  25824. stopChecking = !updatable;
  25825. }
  25826. }
  25827. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25828. geometry.delayLoadState = this.delayLoadState;
  25829. geometry.delayLoadingFile = this.delayLoadingFile;
  25830. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25831. for (kind in this._delayInfo) {
  25832. geometry._delayInfo = geometry._delayInfo || [];
  25833. geometry._delayInfo.push(kind);
  25834. }
  25835. // Bounding info
  25836. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  25837. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25838. return geometry;
  25839. };
  25840. // Statics
  25841. Geometry.ExtractFromMesh = function (mesh, id) {
  25842. var geometry = mesh._geometry;
  25843. if (!geometry) {
  25844. return null;
  25845. }
  25846. return geometry.copy(id);
  25847. };
  25848. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25849. // be aware Math.random() could cause collisions
  25850. Geometry.RandomId = function () {
  25851. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25852. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25853. return v.toString(16);
  25854. });
  25855. };
  25856. return Geometry;
  25857. })();
  25858. BABYLON.Geometry = Geometry;
  25859. /////// Primitives //////////////////////////////////////////////
  25860. var Geometry;
  25861. (function (Geometry) {
  25862. var Primitives;
  25863. (function (Primitives) {
  25864. /// Abstract class
  25865. var _Primitive = (function (_super) {
  25866. __extends(_Primitive, _super);
  25867. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25868. this._beingRegenerated = true;
  25869. this._canBeRegenerated = canBeRegenerated;
  25870. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25871. this._beingRegenerated = false;
  25872. }
  25873. _Primitive.prototype.canBeRegenerated = function () {
  25874. return this._canBeRegenerated;
  25875. };
  25876. _Primitive.prototype.regenerate = function () {
  25877. if (!this._canBeRegenerated) {
  25878. return;
  25879. }
  25880. this._beingRegenerated = true;
  25881. this.setAllVerticesData(this._regenerateVertexData(), false);
  25882. this._beingRegenerated = false;
  25883. };
  25884. _Primitive.prototype.asNewGeometry = function (id) {
  25885. return _super.prototype.copy.call(this, id);
  25886. };
  25887. // overrides
  25888. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25889. if (!this._beingRegenerated) {
  25890. return;
  25891. }
  25892. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25893. };
  25894. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25895. if (!this._beingRegenerated) {
  25896. return;
  25897. }
  25898. _super.prototype.setVerticesData.call(this, kind, data, false);
  25899. };
  25900. // to override
  25901. // protected
  25902. _Primitive.prototype._regenerateVertexData = function () {
  25903. throw new Error("Abstract method");
  25904. };
  25905. _Primitive.prototype.copy = function (id) {
  25906. throw new Error("Must be overriden in sub-classes.");
  25907. };
  25908. return _Primitive;
  25909. })(Geometry);
  25910. Primitives._Primitive = _Primitive;
  25911. var Ribbon = (function (_super) {
  25912. __extends(Ribbon, _super);
  25913. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25914. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25915. this.pathArray = pathArray;
  25916. this.closeArray = closeArray;
  25917. this.closePath = closePath;
  25918. this.offset = offset;
  25919. this.side = side;
  25920. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25921. }
  25922. Ribbon.prototype._regenerateVertexData = function () {
  25923. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  25924. };
  25925. Ribbon.prototype.copy = function (id) {
  25926. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25927. };
  25928. return Ribbon;
  25929. })(_Primitive);
  25930. Primitives.Ribbon = Ribbon;
  25931. var Box = (function (_super) {
  25932. __extends(Box, _super);
  25933. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25934. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25935. this.size = size;
  25936. this.side = side;
  25937. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25938. }
  25939. Box.prototype._regenerateVertexData = function () {
  25940. return BABYLON.VertexData.CreateBox(this.size, this.side);
  25941. };
  25942. Box.prototype.copy = function (id) {
  25943. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25944. };
  25945. return Box;
  25946. })(_Primitive);
  25947. Primitives.Box = Box;
  25948. var Sphere = (function (_super) {
  25949. __extends(Sphere, _super);
  25950. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25951. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25952. this.segments = segments;
  25953. this.diameter = diameter;
  25954. this.side = side;
  25955. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25956. }
  25957. Sphere.prototype._regenerateVertexData = function () {
  25958. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  25959. };
  25960. Sphere.prototype.copy = function (id) {
  25961. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25962. };
  25963. return Sphere;
  25964. })(_Primitive);
  25965. Primitives.Sphere = Sphere;
  25966. var Cylinder = (function (_super) {
  25967. __extends(Cylinder, _super);
  25968. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  25969. if (subdivisions === void 0) { subdivisions = 1; }
  25970. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25971. this.height = height;
  25972. this.diameterTop = diameterTop;
  25973. this.diameterBottom = diameterBottom;
  25974. this.tessellation = tessellation;
  25975. this.subdivisions = subdivisions;
  25976. this.side = side;
  25977. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25978. }
  25979. Cylinder.prototype._regenerateVertexData = function () {
  25980. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  25981. };
  25982. Cylinder.prototype.copy = function (id) {
  25983. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  25984. };
  25985. return Cylinder;
  25986. })(_Primitive);
  25987. Primitives.Cylinder = Cylinder;
  25988. var Torus = (function (_super) {
  25989. __extends(Torus, _super);
  25990. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  25991. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25992. this.diameter = diameter;
  25993. this.thickness = thickness;
  25994. this.tessellation = tessellation;
  25995. this.side = side;
  25996. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25997. }
  25998. Torus.prototype._regenerateVertexData = function () {
  25999. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  26000. };
  26001. Torus.prototype.copy = function (id) {
  26002. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26003. };
  26004. return Torus;
  26005. })(_Primitive);
  26006. Primitives.Torus = Torus;
  26007. var Ground = (function (_super) {
  26008. __extends(Ground, _super);
  26009. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26010. this.width = width;
  26011. this.height = height;
  26012. this.subdivisions = subdivisions;
  26013. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26014. }
  26015. Ground.prototype._regenerateVertexData = function () {
  26016. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  26017. };
  26018. Ground.prototype.copy = function (id) {
  26019. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26020. };
  26021. return Ground;
  26022. })(_Primitive);
  26023. Primitives.Ground = Ground;
  26024. var TiledGround = (function (_super) {
  26025. __extends(TiledGround, _super);
  26026. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26027. this.xmin = xmin;
  26028. this.zmin = zmin;
  26029. this.xmax = xmax;
  26030. this.zmax = zmax;
  26031. this.subdivisions = subdivisions;
  26032. this.precision = precision;
  26033. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26034. }
  26035. TiledGround.prototype._regenerateVertexData = function () {
  26036. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  26037. };
  26038. TiledGround.prototype.copy = function (id) {
  26039. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26040. };
  26041. return TiledGround;
  26042. })(_Primitive);
  26043. Primitives.TiledGround = TiledGround;
  26044. var Plane = (function (_super) {
  26045. __extends(Plane, _super);
  26046. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26047. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26048. this.size = size;
  26049. this.side = side;
  26050. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26051. }
  26052. Plane.prototype._regenerateVertexData = function () {
  26053. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  26054. };
  26055. Plane.prototype.copy = function (id) {
  26056. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26057. };
  26058. return Plane;
  26059. })(_Primitive);
  26060. Primitives.Plane = Plane;
  26061. var TorusKnot = (function (_super) {
  26062. __extends(TorusKnot, _super);
  26063. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26064. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26065. this.radius = radius;
  26066. this.tube = tube;
  26067. this.radialSegments = radialSegments;
  26068. this.tubularSegments = tubularSegments;
  26069. this.p = p;
  26070. this.q = q;
  26071. this.side = side;
  26072. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26073. }
  26074. TorusKnot.prototype._regenerateVertexData = function () {
  26075. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  26076. };
  26077. TorusKnot.prototype.copy = function (id) {
  26078. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26079. };
  26080. return TorusKnot;
  26081. })(_Primitive);
  26082. Primitives.TorusKnot = TorusKnot;
  26083. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26084. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26085. })(BABYLON || (BABYLON = {}));
  26086. //# sourceMappingURL=babylon.geometry.js.map
  26087. var BABYLON;
  26088. (function (BABYLON) {
  26089. var Gamepads = (function () {
  26090. function Gamepads(ongamedpadconnected) {
  26091. var _this = this;
  26092. this.babylonGamepads = [];
  26093. this.oneGamepadConnected = false;
  26094. this.isMonitoring = false;
  26095. this.gamepadEventSupported = 'GamepadEvent' in window;
  26096. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  26097. 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=";
  26098. this._callbackGamepadConnected = ongamedpadconnected;
  26099. if (this.gamepadSupportAvailable) {
  26100. // Checking if the gamepad connected event is supported (like in Firefox)
  26101. if (this.gamepadEventSupported) {
  26102. window.addEventListener('gamepadconnected', function (evt) {
  26103. _this._onGamepadConnected(evt);
  26104. }, false);
  26105. window.addEventListener('gamepaddisconnected', function (evt) {
  26106. _this._onGamepadDisconnected(evt);
  26107. }, false);
  26108. }
  26109. else {
  26110. this._startMonitoringGamepads();
  26111. }
  26112. if (!this.oneGamepadConnected) {
  26113. this._insertGamepadDOMInstructions();
  26114. }
  26115. }
  26116. else {
  26117. this._insertGamepadDOMNotSupported();
  26118. }
  26119. }
  26120. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  26121. Gamepads.gamepadDOMInfo = document.createElement("div");
  26122. var buttonAImage = document.createElement("img");
  26123. buttonAImage.src = this.buttonADataURL;
  26124. var spanMessage = document.createElement("span");
  26125. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  26126. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  26127. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  26128. Gamepads.gamepadDOMInfo.style.position = "absolute";
  26129. Gamepads.gamepadDOMInfo.style.width = "100%";
  26130. Gamepads.gamepadDOMInfo.style.height = "48px";
  26131. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  26132. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  26133. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  26134. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  26135. buttonAImage.style.position = "relative";
  26136. buttonAImage.style.bottom = "8px";
  26137. spanMessage.style.position = "relative";
  26138. spanMessage.style.fontSize = "32px";
  26139. spanMessage.style.bottom = "32px";
  26140. spanMessage.style.color = "green";
  26141. document.body.appendChild(Gamepads.gamepadDOMInfo);
  26142. };
  26143. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  26144. Gamepads.gamepadDOMInfo = document.createElement("div");
  26145. var spanMessage = document.createElement("span");
  26146. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  26147. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  26148. Gamepads.gamepadDOMInfo.style.position = "absolute";
  26149. Gamepads.gamepadDOMInfo.style.width = "100%";
  26150. Gamepads.gamepadDOMInfo.style.height = "40px";
  26151. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  26152. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  26153. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  26154. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  26155. spanMessage.style.position = "relative";
  26156. spanMessage.style.fontSize = "32px";
  26157. spanMessage.style.color = "red";
  26158. document.body.appendChild(Gamepads.gamepadDOMInfo);
  26159. };
  26160. Gamepads.prototype.dispose = function () {
  26161. if (Gamepads.gamepadDOMInfo) {
  26162. document.body.removeChild(Gamepads.gamepadDOMInfo);
  26163. }
  26164. };
  26165. Gamepads.prototype._onGamepadConnected = function (evt) {
  26166. var newGamepad = this._addNewGamepad(evt.gamepad);
  26167. if (this._callbackGamepadConnected)
  26168. this._callbackGamepadConnected(newGamepad);
  26169. this._startMonitoringGamepads();
  26170. };
  26171. Gamepads.prototype._addNewGamepad = function (gamepad) {
  26172. if (!this.oneGamepadConnected) {
  26173. this.oneGamepadConnected = true;
  26174. if (Gamepads.gamepadDOMInfo) {
  26175. document.body.removeChild(Gamepads.gamepadDOMInfo);
  26176. Gamepads.gamepadDOMInfo = null;
  26177. }
  26178. }
  26179. var newGamepad;
  26180. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  26181. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  26182. }
  26183. else {
  26184. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  26185. }
  26186. this.babylonGamepads.push(newGamepad);
  26187. return newGamepad;
  26188. };
  26189. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  26190. for (var i in this.babylonGamepads) {
  26191. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  26192. this.babylonGamepads.splice(i, 1);
  26193. break;
  26194. }
  26195. }
  26196. // If no gamepads are left, stop the polling loop.
  26197. if (this.babylonGamepads.length == 0) {
  26198. this._stopMonitoringGamepads();
  26199. }
  26200. };
  26201. Gamepads.prototype._startMonitoringGamepads = function () {
  26202. if (!this.isMonitoring) {
  26203. this.isMonitoring = true;
  26204. this._checkGamepadsStatus();
  26205. }
  26206. };
  26207. Gamepads.prototype._stopMonitoringGamepads = function () {
  26208. this.isMonitoring = false;
  26209. };
  26210. Gamepads.prototype._checkGamepadsStatus = function () {
  26211. var _this = this;
  26212. // updating gamepad objects
  26213. this._updateGamepadObjects();
  26214. for (var i in this.babylonGamepads) {
  26215. this.babylonGamepads[i].update();
  26216. }
  26217. if (this.isMonitoring) {
  26218. if (window.requestAnimationFrame) {
  26219. window.requestAnimationFrame(function () {
  26220. _this._checkGamepadsStatus();
  26221. });
  26222. }
  26223. else if (window.mozRequestAnimationFrame) {
  26224. window.mozRequestAnimationFrame(function () {
  26225. _this._checkGamepadsStatus();
  26226. });
  26227. }
  26228. else if (window.webkitRequestAnimationFrame) {
  26229. window.webkitRequestAnimationFrame(function () {
  26230. _this._checkGamepadsStatus();
  26231. });
  26232. }
  26233. }
  26234. };
  26235. // This function is called only on Chrome, which does not yet support
  26236. // connection/disconnection events, but requires you to monitor
  26237. // an array for changes.
  26238. Gamepads.prototype._updateGamepadObjects = function () {
  26239. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  26240. for (var i = 0; i < gamepads.length; i++) {
  26241. if (gamepads[i]) {
  26242. if (!(gamepads[i].index in this.babylonGamepads)) {
  26243. var newGamepad = this._addNewGamepad(gamepads[i]);
  26244. if (this._callbackGamepadConnected) {
  26245. this._callbackGamepadConnected(newGamepad);
  26246. }
  26247. }
  26248. else {
  26249. this.babylonGamepads[i].browserGamepad = gamepads[i];
  26250. }
  26251. }
  26252. }
  26253. };
  26254. return Gamepads;
  26255. })();
  26256. BABYLON.Gamepads = Gamepads;
  26257. var StickValues = (function () {
  26258. function StickValues(x, y) {
  26259. this.x = x;
  26260. this.y = y;
  26261. }
  26262. return StickValues;
  26263. })();
  26264. BABYLON.StickValues = StickValues;
  26265. var Gamepad = (function () {
  26266. function Gamepad(id, index, browserGamepad) {
  26267. this.id = id;
  26268. this.index = index;
  26269. this.browserGamepad = browserGamepad;
  26270. if (this.browserGamepad.axes.length >= 2) {
  26271. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  26272. }
  26273. if (this.browserGamepad.axes.length >= 4) {
  26274. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  26275. }
  26276. }
  26277. Gamepad.prototype.onleftstickchanged = function (callback) {
  26278. this._onleftstickchanged = callback;
  26279. };
  26280. Gamepad.prototype.onrightstickchanged = function (callback) {
  26281. this._onrightstickchanged = callback;
  26282. };
  26283. Object.defineProperty(Gamepad.prototype, "leftStick", {
  26284. get: function () {
  26285. return this._leftStick;
  26286. },
  26287. set: function (newValues) {
  26288. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  26289. this._onleftstickchanged(newValues);
  26290. }
  26291. this._leftStick = newValues;
  26292. },
  26293. enumerable: true,
  26294. configurable: true
  26295. });
  26296. Object.defineProperty(Gamepad.prototype, "rightStick", {
  26297. get: function () {
  26298. return this._rightStick;
  26299. },
  26300. set: function (newValues) {
  26301. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  26302. this._onrightstickchanged(newValues);
  26303. }
  26304. this._rightStick = newValues;
  26305. },
  26306. enumerable: true,
  26307. configurable: true
  26308. });
  26309. Gamepad.prototype.update = function () {
  26310. if (this._leftStick) {
  26311. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  26312. }
  26313. if (this._rightStick) {
  26314. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  26315. }
  26316. };
  26317. return Gamepad;
  26318. })();
  26319. BABYLON.Gamepad = Gamepad;
  26320. var GenericPad = (function (_super) {
  26321. __extends(GenericPad, _super);
  26322. function GenericPad(id, index, gamepad) {
  26323. _super.call(this, id, index, gamepad);
  26324. this.id = id;
  26325. this.index = index;
  26326. this.gamepad = gamepad;
  26327. this._buttons = new Array(gamepad.buttons.length);
  26328. }
  26329. GenericPad.prototype.onbuttondown = function (callback) {
  26330. this._onbuttondown = callback;
  26331. };
  26332. GenericPad.prototype.onbuttonup = function (callback) {
  26333. this._onbuttonup = callback;
  26334. };
  26335. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  26336. if (newValue !== currentValue) {
  26337. if (this._onbuttondown && newValue === 1) {
  26338. this._onbuttondown(buttonIndex);
  26339. }
  26340. if (this._onbuttonup && newValue === 0) {
  26341. this._onbuttonup(buttonIndex);
  26342. }
  26343. }
  26344. return newValue;
  26345. };
  26346. GenericPad.prototype.update = function () {
  26347. _super.prototype.update.call(this);
  26348. for (var index = 0; index < this._buttons.length; index++) {
  26349. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  26350. }
  26351. };
  26352. return GenericPad;
  26353. })(Gamepad);
  26354. BABYLON.GenericPad = GenericPad;
  26355. (function (Xbox360Button) {
  26356. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  26357. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  26358. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  26359. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  26360. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  26361. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  26362. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  26363. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  26364. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  26365. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  26366. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  26367. var Xbox360Button = BABYLON.Xbox360Button;
  26368. (function (Xbox360Dpad) {
  26369. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  26370. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  26371. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  26372. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  26373. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  26374. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  26375. var Xbox360Pad = (function (_super) {
  26376. __extends(Xbox360Pad, _super);
  26377. function Xbox360Pad() {
  26378. _super.apply(this, arguments);
  26379. this._leftTrigger = 0;
  26380. this._rightTrigger = 0;
  26381. this._buttonA = 0;
  26382. this._buttonB = 0;
  26383. this._buttonX = 0;
  26384. this._buttonY = 0;
  26385. this._buttonBack = 0;
  26386. this._buttonStart = 0;
  26387. this._buttonLB = 0;
  26388. this._buttonRB = 0;
  26389. this._buttonLeftStick = 0;
  26390. this._buttonRightStick = 0;
  26391. this._dPadUp = 0;
  26392. this._dPadDown = 0;
  26393. this._dPadLeft = 0;
  26394. this._dPadRight = 0;
  26395. }
  26396. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  26397. this._onlefttriggerchanged = callback;
  26398. };
  26399. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  26400. this._onrighttriggerchanged = callback;
  26401. };
  26402. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  26403. get: function () {
  26404. return this._leftTrigger;
  26405. },
  26406. set: function (newValue) {
  26407. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  26408. this._onlefttriggerchanged(newValue);
  26409. }
  26410. this._leftTrigger = newValue;
  26411. },
  26412. enumerable: true,
  26413. configurable: true
  26414. });
  26415. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  26416. get: function () {
  26417. return this._rightTrigger;
  26418. },
  26419. set: function (newValue) {
  26420. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  26421. this._onrighttriggerchanged(newValue);
  26422. }
  26423. this._rightTrigger = newValue;
  26424. },
  26425. enumerable: true,
  26426. configurable: true
  26427. });
  26428. Xbox360Pad.prototype.onbuttondown = function (callback) {
  26429. this._onbuttondown = callback;
  26430. };
  26431. Xbox360Pad.prototype.onbuttonup = function (callback) {
  26432. this._onbuttonup = callback;
  26433. };
  26434. Xbox360Pad.prototype.ondpaddown = function (callback) {
  26435. this._ondpaddown = callback;
  26436. };
  26437. Xbox360Pad.prototype.ondpadup = function (callback) {
  26438. this._ondpadup = callback;
  26439. };
  26440. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  26441. if (newValue !== currentValue) {
  26442. if (this._onbuttondown && newValue === 1) {
  26443. this._onbuttondown(buttonType);
  26444. }
  26445. if (this._onbuttonup && newValue === 0) {
  26446. this._onbuttonup(buttonType);
  26447. }
  26448. }
  26449. return newValue;
  26450. };
  26451. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  26452. if (newValue !== currentValue) {
  26453. if (this._ondpaddown && newValue === 1) {
  26454. this._ondpaddown(buttonType);
  26455. }
  26456. if (this._ondpadup && newValue === 0) {
  26457. this._ondpadup(buttonType);
  26458. }
  26459. }
  26460. return newValue;
  26461. };
  26462. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  26463. get: function () {
  26464. return this._buttonA;
  26465. },
  26466. set: function (value) {
  26467. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  26468. },
  26469. enumerable: true,
  26470. configurable: true
  26471. });
  26472. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  26473. get: function () {
  26474. return this._buttonB;
  26475. },
  26476. set: function (value) {
  26477. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  26478. },
  26479. enumerable: true,
  26480. configurable: true
  26481. });
  26482. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  26483. get: function () {
  26484. return this._buttonX;
  26485. },
  26486. set: function (value) {
  26487. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  26488. },
  26489. enumerable: true,
  26490. configurable: true
  26491. });
  26492. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  26493. get: function () {
  26494. return this._buttonY;
  26495. },
  26496. set: function (value) {
  26497. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  26498. },
  26499. enumerable: true,
  26500. configurable: true
  26501. });
  26502. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  26503. get: function () {
  26504. return this._buttonStart;
  26505. },
  26506. set: function (value) {
  26507. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  26508. },
  26509. enumerable: true,
  26510. configurable: true
  26511. });
  26512. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  26513. get: function () {
  26514. return this._buttonBack;
  26515. },
  26516. set: function (value) {
  26517. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  26518. },
  26519. enumerable: true,
  26520. configurable: true
  26521. });
  26522. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  26523. get: function () {
  26524. return this._buttonLB;
  26525. },
  26526. set: function (value) {
  26527. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  26528. },
  26529. enumerable: true,
  26530. configurable: true
  26531. });
  26532. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  26533. get: function () {
  26534. return this._buttonRB;
  26535. },
  26536. set: function (value) {
  26537. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  26538. },
  26539. enumerable: true,
  26540. configurable: true
  26541. });
  26542. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  26543. get: function () {
  26544. return this._buttonLeftStick;
  26545. },
  26546. set: function (value) {
  26547. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  26548. },
  26549. enumerable: true,
  26550. configurable: true
  26551. });
  26552. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  26553. get: function () {
  26554. return this._buttonRightStick;
  26555. },
  26556. set: function (value) {
  26557. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  26558. },
  26559. enumerable: true,
  26560. configurable: true
  26561. });
  26562. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  26563. get: function () {
  26564. return this._dPadUp;
  26565. },
  26566. set: function (value) {
  26567. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  26568. },
  26569. enumerable: true,
  26570. configurable: true
  26571. });
  26572. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  26573. get: function () {
  26574. return this._dPadDown;
  26575. },
  26576. set: function (value) {
  26577. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  26578. },
  26579. enumerable: true,
  26580. configurable: true
  26581. });
  26582. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  26583. get: function () {
  26584. return this._dPadLeft;
  26585. },
  26586. set: function (value) {
  26587. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  26588. },
  26589. enumerable: true,
  26590. configurable: true
  26591. });
  26592. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  26593. get: function () {
  26594. return this._dPadRight;
  26595. },
  26596. set: function (value) {
  26597. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  26598. },
  26599. enumerable: true,
  26600. configurable: true
  26601. });
  26602. Xbox360Pad.prototype.update = function () {
  26603. _super.prototype.update.call(this);
  26604. this.buttonA = this.browserGamepad.buttons[0].value;
  26605. this.buttonB = this.browserGamepad.buttons[1].value;
  26606. this.buttonX = this.browserGamepad.buttons[2].value;
  26607. this.buttonY = this.browserGamepad.buttons[3].value;
  26608. this.buttonLB = this.browserGamepad.buttons[4].value;
  26609. this.buttonRB = this.browserGamepad.buttons[5].value;
  26610. this.leftTrigger = this.browserGamepad.buttons[6].value;
  26611. this.rightTrigger = this.browserGamepad.buttons[7].value;
  26612. this.buttonBack = this.browserGamepad.buttons[8].value;
  26613. this.buttonStart = this.browserGamepad.buttons[9].value;
  26614. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  26615. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  26616. this.dPadUp = this.browserGamepad.buttons[12].value;
  26617. this.dPadDown = this.browserGamepad.buttons[13].value;
  26618. this.dPadLeft = this.browserGamepad.buttons[14].value;
  26619. this.dPadRight = this.browserGamepad.buttons[15].value;
  26620. };
  26621. return Xbox360Pad;
  26622. })(Gamepad);
  26623. BABYLON.Xbox360Pad = Xbox360Pad;
  26624. })(BABYLON || (BABYLON = {}));
  26625. //# sourceMappingURL=babylon.gamepads.js.map
  26626. var BABYLON;
  26627. (function (BABYLON) {
  26628. // We're mainly based on the logic defined into the FreeCamera code
  26629. var GamepadCamera = (function (_super) {
  26630. __extends(GamepadCamera, _super);
  26631. function GamepadCamera(name, position, scene) {
  26632. var _this = this;
  26633. _super.call(this, name, position, scene);
  26634. this.angularSensibility = 200;
  26635. this.moveSensibility = 75;
  26636. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  26637. _this._onNewGameConnected(gamepad);
  26638. });
  26639. }
  26640. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  26641. // Only the first gamepad can control the camera
  26642. if (gamepad.index === 0) {
  26643. this._gamepad = gamepad;
  26644. }
  26645. };
  26646. GamepadCamera.prototype._checkInputs = function () {
  26647. if (!this._gamepad) {
  26648. return;
  26649. }
  26650. var LSValues = this._gamepad.leftStick;
  26651. var normalizedLX = LSValues.x / this.moveSensibility;
  26652. var normalizedLY = LSValues.y / this.moveSensibility;
  26653. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  26654. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  26655. var RSValues = this._gamepad.rightStick;
  26656. var normalizedRX = RSValues.x / this.angularSensibility;
  26657. var normalizedRY = RSValues.y / this.angularSensibility;
  26658. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  26659. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  26660. ;
  26661. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  26662. var speed = this._computeLocalCameraSpeed() * 50.0;
  26663. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  26664. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  26665. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  26666. };
  26667. GamepadCamera.prototype.dispose = function () {
  26668. this._gamepads.dispose();
  26669. _super.prototype.dispose.call(this);
  26670. };
  26671. return GamepadCamera;
  26672. })(BABYLON.FreeCamera);
  26673. BABYLON.GamepadCamera = GamepadCamera;
  26674. })(BABYLON || (BABYLON = {}));
  26675. //# sourceMappingURL=babylon.gamepadCamera.js.map
  26676. var BABYLON;
  26677. (function (BABYLON) {
  26678. var LinesMesh = (function (_super) {
  26679. __extends(LinesMesh, _super);
  26680. function LinesMesh(name, scene, updatable) {
  26681. if (updatable === void 0) { updatable = false; }
  26682. _super.call(this, name, scene);
  26683. this.color = new BABYLON.Color3(1, 1, 1);
  26684. this.alpha = 1;
  26685. this._indices = new Array();
  26686. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26687. attributes: ["position"],
  26688. uniforms: ["worldViewProjection", "color"],
  26689. needAlphaBlending: true
  26690. });
  26691. }
  26692. Object.defineProperty(LinesMesh.prototype, "material", {
  26693. get: function () {
  26694. return this._colorShader;
  26695. },
  26696. enumerable: true,
  26697. configurable: true
  26698. });
  26699. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26700. get: function () {
  26701. return false;
  26702. },
  26703. enumerable: true,
  26704. configurable: true
  26705. });
  26706. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26707. get: function () {
  26708. return false;
  26709. },
  26710. enumerable: true,
  26711. configurable: true
  26712. });
  26713. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26714. var engine = this.getScene().getEngine();
  26715. var indexToBind = this._geometry.getIndexBuffer();
  26716. // VBOs
  26717. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26718. // Color
  26719. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26720. };
  26721. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26722. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26723. return;
  26724. }
  26725. var engine = this.getScene().getEngine();
  26726. // Draw order
  26727. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26728. };
  26729. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26730. return null;
  26731. };
  26732. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26733. this._colorShader.dispose();
  26734. _super.prototype.dispose.call(this, doNotRecurse);
  26735. };
  26736. return LinesMesh;
  26737. })(BABYLON.Mesh);
  26738. BABYLON.LinesMesh = LinesMesh;
  26739. })(BABYLON || (BABYLON = {}));
  26740. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  26741. (function (BABYLON) {
  26742. var OutlineRenderer = (function () {
  26743. function OutlineRenderer(scene) {
  26744. this._scene = scene;
  26745. }
  26746. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  26747. var _this = this;
  26748. if (useOverlay === void 0) { useOverlay = false; }
  26749. var scene = this._scene;
  26750. var engine = this._scene.getEngine();
  26751. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26752. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  26753. return;
  26754. }
  26755. var mesh = subMesh.getRenderingMesh();
  26756. var material = subMesh.getMaterial();
  26757. engine.enableEffect(this._effect);
  26758. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  26759. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  26760. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26761. // Bones
  26762. if (mesh.useBones) {
  26763. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26764. }
  26765. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  26766. // Alpha test
  26767. if (material && material.needAlphaTesting()) {
  26768. var alphaTexture = material.getAlphaTestTexture();
  26769. this._effect.setTexture("diffuseSampler", alphaTexture);
  26770. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  26771. }
  26772. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  26773. _this._effect.setMatrix("world", world);
  26774. });
  26775. };
  26776. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  26777. var defines = [];
  26778. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  26779. var mesh = subMesh.getMesh();
  26780. var material = subMesh.getMaterial();
  26781. // Alpha test
  26782. if (material && material.needAlphaTesting()) {
  26783. defines.push("#define ALPHATEST");
  26784. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26785. attribs.push(BABYLON.VertexBuffer.UVKind);
  26786. defines.push("#define UV1");
  26787. }
  26788. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26789. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26790. defines.push("#define UV2");
  26791. }
  26792. }
  26793. // Bones
  26794. if (mesh.useBones) {
  26795. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26796. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26797. defines.push("#define BONES");
  26798. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26799. }
  26800. // Instances
  26801. if (useInstances) {
  26802. defines.push("#define INSTANCES");
  26803. attribs.push("world0");
  26804. attribs.push("world1");
  26805. attribs.push("world2");
  26806. attribs.push("world3");
  26807. }
  26808. // Get correct effect
  26809. var join = defines.join("\n");
  26810. if (this._cachedDefines !== join) {
  26811. this._cachedDefines = join;
  26812. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  26813. }
  26814. return this._effect.isReady();
  26815. };
  26816. return OutlineRenderer;
  26817. })();
  26818. BABYLON.OutlineRenderer = OutlineRenderer;
  26819. })(BABYLON || (BABYLON = {}));
  26820. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  26821. (function (BABYLON) {
  26822. var MeshAssetTask = (function () {
  26823. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  26824. this.name = name;
  26825. this.meshesNames = meshesNames;
  26826. this.rootUrl = rootUrl;
  26827. this.sceneFilename = sceneFilename;
  26828. this.isCompleted = false;
  26829. }
  26830. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26831. var _this = this;
  26832. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  26833. _this.loadedMeshes = meshes;
  26834. _this.loadedParticleSystems = particleSystems;
  26835. _this.loadedSkeletons = skeletons;
  26836. _this.isCompleted = true;
  26837. if (_this.onSuccess) {
  26838. _this.onSuccess(_this);
  26839. }
  26840. onSuccess();
  26841. }, null, function () {
  26842. if (_this.onError) {
  26843. _this.onError(_this);
  26844. }
  26845. onError();
  26846. });
  26847. };
  26848. return MeshAssetTask;
  26849. })();
  26850. BABYLON.MeshAssetTask = MeshAssetTask;
  26851. var TextFileAssetTask = (function () {
  26852. function TextFileAssetTask(name, url) {
  26853. this.name = name;
  26854. this.url = url;
  26855. this.isCompleted = false;
  26856. }
  26857. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26858. var _this = this;
  26859. BABYLON.Tools.LoadFile(this.url, function (data) {
  26860. _this.text = data;
  26861. _this.isCompleted = true;
  26862. if (_this.onSuccess) {
  26863. _this.onSuccess(_this);
  26864. }
  26865. onSuccess();
  26866. }, null, scene.database, false, function () {
  26867. if (_this.onError) {
  26868. _this.onError(_this);
  26869. }
  26870. onError();
  26871. });
  26872. };
  26873. return TextFileAssetTask;
  26874. })();
  26875. BABYLON.TextFileAssetTask = TextFileAssetTask;
  26876. var BinaryFileAssetTask = (function () {
  26877. function BinaryFileAssetTask(name, url) {
  26878. this.name = name;
  26879. this.url = url;
  26880. this.isCompleted = false;
  26881. }
  26882. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26883. var _this = this;
  26884. BABYLON.Tools.LoadFile(this.url, function (data) {
  26885. _this.data = data;
  26886. _this.isCompleted = true;
  26887. if (_this.onSuccess) {
  26888. _this.onSuccess(_this);
  26889. }
  26890. onSuccess();
  26891. }, null, scene.database, true, function () {
  26892. if (_this.onError) {
  26893. _this.onError(_this);
  26894. }
  26895. onError();
  26896. });
  26897. };
  26898. return BinaryFileAssetTask;
  26899. })();
  26900. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  26901. var ImageAssetTask = (function () {
  26902. function ImageAssetTask(name, url) {
  26903. this.name = name;
  26904. this.url = url;
  26905. this.isCompleted = false;
  26906. }
  26907. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26908. var _this = this;
  26909. var img = new Image();
  26910. img.onload = function () {
  26911. _this.image = img;
  26912. _this.isCompleted = true;
  26913. if (_this.onSuccess) {
  26914. _this.onSuccess(_this);
  26915. }
  26916. onSuccess();
  26917. };
  26918. img.onerror = function () {
  26919. if (_this.onError) {
  26920. _this.onError(_this);
  26921. }
  26922. onError();
  26923. };
  26924. img.src = this.url;
  26925. };
  26926. return ImageAssetTask;
  26927. })();
  26928. BABYLON.ImageAssetTask = ImageAssetTask;
  26929. var TextureAssetTask = (function () {
  26930. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  26931. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26932. this.name = name;
  26933. this.url = url;
  26934. this.noMipmap = noMipmap;
  26935. this.invertY = invertY;
  26936. this.samplingMode = samplingMode;
  26937. this.isCompleted = false;
  26938. }
  26939. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26940. var _this = this;
  26941. var onload = function () {
  26942. _this.isCompleted = true;
  26943. if (_this.onSuccess) {
  26944. _this.onSuccess(_this);
  26945. }
  26946. onSuccess();
  26947. };
  26948. var onerror = function () {
  26949. if (_this.onError) {
  26950. _this.onError(_this);
  26951. }
  26952. onError();
  26953. };
  26954. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  26955. };
  26956. return TextureAssetTask;
  26957. })();
  26958. BABYLON.TextureAssetTask = TextureAssetTask;
  26959. var AssetsManager = (function () {
  26960. function AssetsManager(scene) {
  26961. this._tasks = new Array();
  26962. this._waitingTasksCount = 0;
  26963. this.useDefaultLoadingScreen = true;
  26964. this._scene = scene;
  26965. }
  26966. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  26967. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  26968. this._tasks.push(task);
  26969. return task;
  26970. };
  26971. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  26972. var task = new TextFileAssetTask(taskName, url);
  26973. this._tasks.push(task);
  26974. return task;
  26975. };
  26976. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  26977. var task = new BinaryFileAssetTask(taskName, url);
  26978. this._tasks.push(task);
  26979. return task;
  26980. };
  26981. AssetsManager.prototype.addImageTask = function (taskName, url) {
  26982. var task = new ImageAssetTask(taskName, url);
  26983. this._tasks.push(task);
  26984. return task;
  26985. };
  26986. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  26987. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26988. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  26989. this._tasks.push(task);
  26990. return task;
  26991. };
  26992. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  26993. this._waitingTasksCount--;
  26994. if (this._waitingTasksCount === 0) {
  26995. if (this.onFinish) {
  26996. this.onFinish(this._tasks);
  26997. }
  26998. this._scene.getEngine().hideLoadingUI();
  26999. }
  27000. };
  27001. AssetsManager.prototype._runTask = function (task) {
  27002. var _this = this;
  27003. task.run(this._scene, function () {
  27004. if (_this.onTaskSuccess) {
  27005. _this.onTaskSuccess(task);
  27006. }
  27007. _this._decreaseWaitingTasksCount();
  27008. }, function () {
  27009. if (_this.onTaskError) {
  27010. _this.onTaskError(task);
  27011. }
  27012. _this._decreaseWaitingTasksCount();
  27013. });
  27014. };
  27015. AssetsManager.prototype.reset = function () {
  27016. this._tasks = new Array();
  27017. return this;
  27018. };
  27019. AssetsManager.prototype.load = function () {
  27020. this._waitingTasksCount = this._tasks.length;
  27021. if (this._waitingTasksCount === 0) {
  27022. if (this.onFinish) {
  27023. this.onFinish(this._tasks);
  27024. }
  27025. return this;
  27026. }
  27027. if (this.useDefaultLoadingScreen) {
  27028. this._scene.getEngine().displayLoadingUI();
  27029. }
  27030. for (var index = 0; index < this._tasks.length; index++) {
  27031. var task = this._tasks[index];
  27032. this._runTask(task);
  27033. }
  27034. return this;
  27035. };
  27036. return AssetsManager;
  27037. })();
  27038. BABYLON.AssetsManager = AssetsManager;
  27039. })(BABYLON || (BABYLON = {}));
  27040. //# sourceMappingURL=babylon.assetsManager.js.map
  27041. var BABYLON;
  27042. (function (BABYLON) {
  27043. var VRDeviceOrientationCamera = (function (_super) {
  27044. __extends(VRDeviceOrientationCamera, _super);
  27045. function VRDeviceOrientationCamera(name, position, scene) {
  27046. _super.call(this, name, position, scene);
  27047. this._alpha = 0;
  27048. this._beta = 0;
  27049. this._gamma = 0;
  27050. }
  27051. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  27052. this._alpha = +evt.alpha | 0;
  27053. this._beta = +evt.beta | 0;
  27054. this._gamma = +evt.gamma | 0;
  27055. if (this._gamma < 0) {
  27056. this._gamma = 90 + this._gamma;
  27057. }
  27058. else {
  27059. // Incline it in the correct angle.
  27060. this._gamma = 270 - this._gamma;
  27061. }
  27062. this.rotation.x = this._gamma / 180.0 * Math.PI;
  27063. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  27064. this.rotation.z = this._beta / 180.0 * Math.PI;
  27065. };
  27066. return VRDeviceOrientationCamera;
  27067. })(BABYLON.OculusCamera);
  27068. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  27069. })(BABYLON || (BABYLON = {}));
  27070. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  27071. var BABYLON;
  27072. (function (BABYLON) {
  27073. var WebVRCamera = (function (_super) {
  27074. __extends(WebVRCamera, _super);
  27075. function WebVRCamera(name, position, scene) {
  27076. _super.call(this, name, position, scene);
  27077. this._hmdDevice = null;
  27078. this._sensorDevice = null;
  27079. this._cacheState = null;
  27080. this._cacheQuaternion = new BABYLON.Quaternion();
  27081. this._cacheRotation = BABYLON.Vector3.Zero();
  27082. this._vrEnabled = false;
  27083. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  27084. }
  27085. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  27086. var size = devices.length;
  27087. var i = 0;
  27088. // Reset devices.
  27089. this._sensorDevice = null;
  27090. this._hmdDevice = null;
  27091. while (i < size && this._hmdDevice === null) {
  27092. if (devices[i] instanceof HMDVRDevice) {
  27093. this._hmdDevice = devices[i];
  27094. }
  27095. i++;
  27096. }
  27097. i = 0;
  27098. while (i < size && this._sensorDevice === null) {
  27099. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  27100. this._sensorDevice = devices[i];
  27101. }
  27102. i++;
  27103. }
  27104. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  27105. };
  27106. WebVRCamera.prototype._update = function () {
  27107. if (this._vrEnabled) {
  27108. this._cacheState = this._sensorDevice.getState();
  27109. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  27110. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  27111. this.rotation.x = -this._cacheRotation.z;
  27112. this.rotation.y = -this._cacheRotation.y;
  27113. this.rotation.z = this._cacheRotation.x;
  27114. }
  27115. _super.prototype._update.call(this);
  27116. };
  27117. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  27118. _super.prototype.attachControl.call(this, element, noPreventDefault);
  27119. if (navigator.getVRDevices) {
  27120. navigator.getVRDevices().then(this._getWebVRDevices);
  27121. }
  27122. else if (navigator.mozGetVRDevices) {
  27123. navigator.mozGetVRDevices(this._getWebVRDevices);
  27124. }
  27125. };
  27126. WebVRCamera.prototype.detachControl = function (element) {
  27127. _super.prototype.detachControl.call(this, element);
  27128. this._vrEnabled = false;
  27129. };
  27130. return WebVRCamera;
  27131. })(BABYLON.OculusCamera);
  27132. BABYLON.WebVRCamera = WebVRCamera;
  27133. })(BABYLON || (BABYLON = {}));
  27134. //# sourceMappingURL=babylon.webVRCamera.js.map
  27135. var BABYLON;
  27136. (function (BABYLON) {
  27137. // Standard optimizations
  27138. var SceneOptimization = (function () {
  27139. function SceneOptimization(priority) {
  27140. if (priority === void 0) { priority = 0; }
  27141. this.priority = priority;
  27142. this.apply = function (scene) {
  27143. return true; // Return true if everything that can be done was applied
  27144. };
  27145. }
  27146. return SceneOptimization;
  27147. })();
  27148. BABYLON.SceneOptimization = SceneOptimization;
  27149. var TextureOptimization = (function (_super) {
  27150. __extends(TextureOptimization, _super);
  27151. function TextureOptimization(priority, maximumSize) {
  27152. var _this = this;
  27153. if (priority === void 0) { priority = 0; }
  27154. if (maximumSize === void 0) { maximumSize = 1024; }
  27155. _super.call(this, priority);
  27156. this.priority = priority;
  27157. this.maximumSize = maximumSize;
  27158. this.apply = function (scene) {
  27159. var allDone = true;
  27160. for (var index = 0; index < scene.textures.length; index++) {
  27161. var texture = scene.textures[index];
  27162. if (!texture.canRescale) {
  27163. continue;
  27164. }
  27165. var currentSize = texture.getSize();
  27166. var maxDimension = Math.max(currentSize.width, currentSize.height);
  27167. if (maxDimension > _this.maximumSize) {
  27168. texture.scale(0.5);
  27169. allDone = false;
  27170. }
  27171. }
  27172. return allDone;
  27173. };
  27174. }
  27175. return TextureOptimization;
  27176. })(SceneOptimization);
  27177. BABYLON.TextureOptimization = TextureOptimization;
  27178. var HardwareScalingOptimization = (function (_super) {
  27179. __extends(HardwareScalingOptimization, _super);
  27180. function HardwareScalingOptimization(priority, maximumScale) {
  27181. var _this = this;
  27182. if (priority === void 0) { priority = 0; }
  27183. if (maximumScale === void 0) { maximumScale = 2; }
  27184. _super.call(this, priority);
  27185. this.priority = priority;
  27186. this.maximumScale = maximumScale;
  27187. this._currentScale = 1;
  27188. this.apply = function (scene) {
  27189. _this._currentScale++;
  27190. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  27191. return _this._currentScale >= _this.maximumScale;
  27192. };
  27193. }
  27194. return HardwareScalingOptimization;
  27195. })(SceneOptimization);
  27196. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  27197. var ShadowsOptimization = (function (_super) {
  27198. __extends(ShadowsOptimization, _super);
  27199. function ShadowsOptimization() {
  27200. _super.apply(this, arguments);
  27201. this.apply = function (scene) {
  27202. scene.shadowsEnabled = false;
  27203. return true;
  27204. };
  27205. }
  27206. return ShadowsOptimization;
  27207. })(SceneOptimization);
  27208. BABYLON.ShadowsOptimization = ShadowsOptimization;
  27209. var PostProcessesOptimization = (function (_super) {
  27210. __extends(PostProcessesOptimization, _super);
  27211. function PostProcessesOptimization() {
  27212. _super.apply(this, arguments);
  27213. this.apply = function (scene) {
  27214. scene.postProcessesEnabled = false;
  27215. return true;
  27216. };
  27217. }
  27218. return PostProcessesOptimization;
  27219. })(SceneOptimization);
  27220. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  27221. var LensFlaresOptimization = (function (_super) {
  27222. __extends(LensFlaresOptimization, _super);
  27223. function LensFlaresOptimization() {
  27224. _super.apply(this, arguments);
  27225. this.apply = function (scene) {
  27226. scene.lensFlaresEnabled = false;
  27227. return true;
  27228. };
  27229. }
  27230. return LensFlaresOptimization;
  27231. })(SceneOptimization);
  27232. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  27233. var ParticlesOptimization = (function (_super) {
  27234. __extends(ParticlesOptimization, _super);
  27235. function ParticlesOptimization() {
  27236. _super.apply(this, arguments);
  27237. this.apply = function (scene) {
  27238. scene.particlesEnabled = false;
  27239. return true;
  27240. };
  27241. }
  27242. return ParticlesOptimization;
  27243. })(SceneOptimization);
  27244. BABYLON.ParticlesOptimization = ParticlesOptimization;
  27245. var RenderTargetsOptimization = (function (_super) {
  27246. __extends(RenderTargetsOptimization, _super);
  27247. function RenderTargetsOptimization() {
  27248. _super.apply(this, arguments);
  27249. this.apply = function (scene) {
  27250. scene.renderTargetsEnabled = false;
  27251. return true;
  27252. };
  27253. }
  27254. return RenderTargetsOptimization;
  27255. })(SceneOptimization);
  27256. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  27257. var MergeMeshesOptimization = (function (_super) {
  27258. __extends(MergeMeshesOptimization, _super);
  27259. function MergeMeshesOptimization() {
  27260. var _this = this;
  27261. _super.apply(this, arguments);
  27262. this._canBeMerged = function (abstractMesh) {
  27263. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  27264. return false;
  27265. }
  27266. var mesh = abstractMesh;
  27267. if (!mesh.isVisible || !mesh.isEnabled()) {
  27268. return false;
  27269. }
  27270. if (mesh.instances.length > 0) {
  27271. return false;
  27272. }
  27273. if (mesh.skeleton || mesh.hasLODLevels) {
  27274. return false;
  27275. }
  27276. return true;
  27277. };
  27278. this.apply = function (scene) {
  27279. var globalPool = scene.meshes.slice(0);
  27280. var globalLength = globalPool.length;
  27281. for (var index = 0; index < globalLength; index++) {
  27282. var currentPool = new Array();
  27283. var current = globalPool[index];
  27284. // Checks
  27285. if (!_this._canBeMerged(current)) {
  27286. continue;
  27287. }
  27288. currentPool.push(current);
  27289. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  27290. var otherMesh = globalPool[subIndex];
  27291. if (!_this._canBeMerged(otherMesh)) {
  27292. continue;
  27293. }
  27294. if (otherMesh.material !== current.material) {
  27295. continue;
  27296. }
  27297. if (otherMesh.checkCollisions !== current.checkCollisions) {
  27298. continue;
  27299. }
  27300. currentPool.push(otherMesh);
  27301. globalLength--;
  27302. globalPool.splice(subIndex, 1);
  27303. subIndex--;
  27304. }
  27305. if (currentPool.length < 2) {
  27306. continue;
  27307. }
  27308. // Merge meshes
  27309. BABYLON.Mesh.MergeMeshes(currentPool);
  27310. }
  27311. return true;
  27312. };
  27313. }
  27314. return MergeMeshesOptimization;
  27315. })(SceneOptimization);
  27316. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  27317. // Options
  27318. var SceneOptimizerOptions = (function () {
  27319. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  27320. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  27321. if (trackerDuration === void 0) { trackerDuration = 2000; }
  27322. this.targetFrameRate = targetFrameRate;
  27323. this.trackerDuration = trackerDuration;
  27324. this.optimizations = new Array();
  27325. }
  27326. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  27327. var result = new SceneOptimizerOptions(targetFrameRate);
  27328. var priority = 0;
  27329. result.optimizations.push(new MergeMeshesOptimization(priority));
  27330. result.optimizations.push(new ShadowsOptimization(priority));
  27331. result.optimizations.push(new LensFlaresOptimization(priority));
  27332. // Next priority
  27333. priority++;
  27334. result.optimizations.push(new PostProcessesOptimization(priority));
  27335. result.optimizations.push(new ParticlesOptimization(priority));
  27336. // Next priority
  27337. priority++;
  27338. result.optimizations.push(new TextureOptimization(priority, 1024));
  27339. return result;
  27340. };
  27341. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  27342. var result = new SceneOptimizerOptions(targetFrameRate);
  27343. var priority = 0;
  27344. result.optimizations.push(new MergeMeshesOptimization(priority));
  27345. result.optimizations.push(new ShadowsOptimization(priority));
  27346. result.optimizations.push(new LensFlaresOptimization(priority));
  27347. // Next priority
  27348. priority++;
  27349. result.optimizations.push(new PostProcessesOptimization(priority));
  27350. result.optimizations.push(new ParticlesOptimization(priority));
  27351. // Next priority
  27352. priority++;
  27353. result.optimizations.push(new TextureOptimization(priority, 512));
  27354. // Next priority
  27355. priority++;
  27356. result.optimizations.push(new RenderTargetsOptimization(priority));
  27357. // Next priority
  27358. priority++;
  27359. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  27360. return result;
  27361. };
  27362. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  27363. var result = new SceneOptimizerOptions(targetFrameRate);
  27364. var priority = 0;
  27365. result.optimizations.push(new MergeMeshesOptimization(priority));
  27366. result.optimizations.push(new ShadowsOptimization(priority));
  27367. result.optimizations.push(new LensFlaresOptimization(priority));
  27368. // Next priority
  27369. priority++;
  27370. result.optimizations.push(new PostProcessesOptimization(priority));
  27371. result.optimizations.push(new ParticlesOptimization(priority));
  27372. // Next priority
  27373. priority++;
  27374. result.optimizations.push(new TextureOptimization(priority, 256));
  27375. // Next priority
  27376. priority++;
  27377. result.optimizations.push(new RenderTargetsOptimization(priority));
  27378. // Next priority
  27379. priority++;
  27380. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  27381. return result;
  27382. };
  27383. return SceneOptimizerOptions;
  27384. })();
  27385. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  27386. // Scene optimizer tool
  27387. var SceneOptimizer = (function () {
  27388. function SceneOptimizer() {
  27389. }
  27390. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  27391. // TODO: add an epsilon
  27392. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  27393. if (onSuccess) {
  27394. onSuccess();
  27395. }
  27396. return;
  27397. }
  27398. // Apply current level of optimizations
  27399. var allDone = true;
  27400. var noOptimizationApplied = true;
  27401. for (var index = 0; index < options.optimizations.length; index++) {
  27402. var optimization = options.optimizations[index];
  27403. if (optimization.priority === currentPriorityLevel) {
  27404. noOptimizationApplied = false;
  27405. allDone = allDone && optimization.apply(scene);
  27406. }
  27407. }
  27408. // If no optimization was applied, this is a failure :(
  27409. if (noOptimizationApplied) {
  27410. if (onFailure) {
  27411. onFailure();
  27412. }
  27413. return;
  27414. }
  27415. // If all optimizations were done, move to next level
  27416. if (allDone) {
  27417. currentPriorityLevel++;
  27418. }
  27419. // Let's the system running for a specific amount of time before checking FPS
  27420. scene.executeWhenReady(function () {
  27421. setTimeout(function () {
  27422. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  27423. }, options.trackerDuration);
  27424. });
  27425. };
  27426. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  27427. if (!options) {
  27428. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  27429. }
  27430. // Let's the system running for a specific amount of time before checking FPS
  27431. scene.executeWhenReady(function () {
  27432. setTimeout(function () {
  27433. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  27434. }, options.trackerDuration);
  27435. });
  27436. };
  27437. return SceneOptimizer;
  27438. })();
  27439. BABYLON.SceneOptimizer = SceneOptimizer;
  27440. })(BABYLON || (BABYLON = {}));
  27441. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  27442. (function (BABYLON) {
  27443. var Internals;
  27444. (function (Internals) {
  27445. var MeshLODLevel = (function () {
  27446. function MeshLODLevel(distance, mesh) {
  27447. this.distance = distance;
  27448. this.mesh = mesh;
  27449. }
  27450. return MeshLODLevel;
  27451. })();
  27452. Internals.MeshLODLevel = MeshLODLevel;
  27453. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27454. })(BABYLON || (BABYLON = {}));
  27455. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  27456. (function (BABYLON) {
  27457. var AudioEngine = (function () {
  27458. function AudioEngine() {
  27459. this._audioContext = null;
  27460. this._audioContextInitialized = false;
  27461. this.canUseWebAudio = false;
  27462. this.WarnedWebAudioUnsupported = false;
  27463. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  27464. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  27465. this.canUseWebAudio = true;
  27466. }
  27467. }
  27468. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  27469. get: function () {
  27470. if (!this._audioContextInitialized) {
  27471. this._initializeAudioContext();
  27472. }
  27473. return this._audioContext;
  27474. },
  27475. enumerable: true,
  27476. configurable: true
  27477. });
  27478. AudioEngine.prototype._initializeAudioContext = function () {
  27479. try {
  27480. if (this.canUseWebAudio) {
  27481. this._audioContext = new AudioContext();
  27482. // create a global volume gain node
  27483. this.masterGain = this._audioContext.createGain();
  27484. this.masterGain.gain.value = 1;
  27485. this.masterGain.connect(this._audioContext.destination);
  27486. this._audioContextInitialized = true;
  27487. }
  27488. }
  27489. catch (e) {
  27490. this.canUseWebAudio = false;
  27491. BABYLON.Tools.Error("Web Audio: " + e.message);
  27492. }
  27493. };
  27494. AudioEngine.prototype.dispose = function () {
  27495. if (this.canUseWebAudio && this._audioContextInitialized) {
  27496. if (this._connectedAnalyser) {
  27497. this._connectedAnalyser.stopDebugCanvas();
  27498. this._connectedAnalyser.dispose();
  27499. this.masterGain.disconnect();
  27500. this.masterGain.connect(this._audioContext.destination);
  27501. this._connectedAnalyser = null;
  27502. }
  27503. this.masterGain.gain.value = 1;
  27504. }
  27505. this.WarnedWebAudioUnsupported = false;
  27506. };
  27507. AudioEngine.prototype.getGlobalVolume = function () {
  27508. if (this.canUseWebAudio && this._audioContextInitialized) {
  27509. return this.masterGain.gain.value;
  27510. }
  27511. else {
  27512. return -1;
  27513. }
  27514. };
  27515. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  27516. if (this.canUseWebAudio && this._audioContextInitialized) {
  27517. this.masterGain.gain.value = newVolume;
  27518. }
  27519. };
  27520. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  27521. if (this._connectedAnalyser) {
  27522. this._connectedAnalyser.stopDebugCanvas();
  27523. }
  27524. if (this.canUseWebAudio && this._audioContextInitialized) {
  27525. this._connectedAnalyser = analyser;
  27526. this.masterGain.disconnect();
  27527. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  27528. }
  27529. };
  27530. return AudioEngine;
  27531. })();
  27532. BABYLON.AudioEngine = AudioEngine;
  27533. })(BABYLON || (BABYLON = {}));
  27534. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  27535. (function (BABYLON) {
  27536. var Sound = (function () {
  27537. /**
  27538. * Create a sound and attach it to a scene
  27539. * @param name Name of your sound
  27540. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  27541. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  27542. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  27543. */
  27544. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  27545. var _this = this;
  27546. this.autoplay = false;
  27547. this.loop = false;
  27548. this.useCustomAttenuation = false;
  27549. this.spatialSound = false;
  27550. this.refDistance = 1;
  27551. this.rolloffFactor = 1;
  27552. this.maxDistance = 100;
  27553. this.distanceModel = "linear";
  27554. this._panningModel = "equalpower";
  27555. this._playbackRate = 1;
  27556. this._startTime = 0;
  27557. this._startOffset = 0;
  27558. this._position = BABYLON.Vector3.Zero();
  27559. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  27560. this._volume = 1;
  27561. this._isLoaded = false;
  27562. this._isReadyToPlay = false;
  27563. this.isPlaying = false;
  27564. this.isPaused = false;
  27565. this._isDirectional = false;
  27566. // Used if you'd like to create a directional sound.
  27567. // If not set, the sound will be omnidirectional
  27568. this._coneInnerAngle = 360;
  27569. this._coneOuterAngle = 360;
  27570. this._coneOuterGain = 0;
  27571. this.name = name;
  27572. this._scene = scene;
  27573. this._readyToPlayCallback = readyToPlayCallback;
  27574. // Default custom attenuation function is a linear attenuation
  27575. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  27576. if (currentDistance < maxDistance) {
  27577. return currentVolume * (1 - currentDistance / maxDistance);
  27578. }
  27579. else {
  27580. return 0;
  27581. }
  27582. };
  27583. if (options) {
  27584. this.autoplay = options.autoplay || false;
  27585. this.loop = options.loop || false;
  27586. // if volume === 0, we need another way to check this option
  27587. if (options.volume !== undefined) {
  27588. this._volume = options.volume;
  27589. }
  27590. this.spatialSound = options.spatialSound || false;
  27591. this.maxDistance = options.maxDistance || 100;
  27592. this.useCustomAttenuation = options.useCustomAttenuation || false;
  27593. this.rolloffFactor = options.rolloffFactor || 1;
  27594. this.refDistance = options.refDistance || 1;
  27595. this.distanceModel = options.distanceModel || "linear";
  27596. this._playbackRate = options.playbackRate || 1;
  27597. }
  27598. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27599. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  27600. this._soundGain.gain.value = this._volume;
  27601. this._inputAudioNode = this._soundGain;
  27602. this._ouputAudioNode = this._soundGain;
  27603. if (this.spatialSound) {
  27604. this._createSpatialParameters();
  27605. }
  27606. this._scene.mainSoundTrack.AddSound(this);
  27607. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  27608. if (urlOrArrayBuffer) {
  27609. // If it's an URL
  27610. if (typeof (urlOrArrayBuffer) === "string") {
  27611. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  27612. _this._soundLoaded(data);
  27613. }, null, null, true);
  27614. }
  27615. else {
  27616. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  27617. this._soundLoaded(urlOrArrayBuffer);
  27618. }
  27619. else {
  27620. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  27621. }
  27622. }
  27623. }
  27624. }
  27625. else {
  27626. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  27627. this._scene.mainSoundTrack.AddSound(this);
  27628. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  27629. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  27630. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  27631. }
  27632. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  27633. if (this._readyToPlayCallback) {
  27634. window.setTimeout(function () {
  27635. _this._readyToPlayCallback();
  27636. }, 1000);
  27637. }
  27638. }
  27639. }
  27640. Sound.prototype.dispose = function () {
  27641. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  27642. if (this.isPlaying) {
  27643. this.stop();
  27644. }
  27645. this._isReadyToPlay = false;
  27646. if (this.soundTrackId === -1) {
  27647. this._scene.mainSoundTrack.RemoveSound(this);
  27648. }
  27649. else {
  27650. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  27651. }
  27652. if (this._soundGain) {
  27653. this._soundGain.disconnect();
  27654. this._soundGain = null;
  27655. }
  27656. if (this._soundPanner) {
  27657. this._soundPanner.disconnect();
  27658. this._soundPanner = null;
  27659. }
  27660. if (this._soundSource) {
  27661. this._soundSource.disconnect();
  27662. this._soundSource = null;
  27663. }
  27664. this._audioBuffer = null;
  27665. if (this._connectedMesh) {
  27666. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  27667. this._connectedMesh = null;
  27668. }
  27669. }
  27670. };
  27671. Sound.prototype._soundLoaded = function (audioData) {
  27672. var _this = this;
  27673. this._isLoaded = true;
  27674. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  27675. _this._audioBuffer = buffer;
  27676. _this._isReadyToPlay = true;
  27677. if (_this.autoplay) {
  27678. _this.play();
  27679. }
  27680. if (_this._readyToPlayCallback) {
  27681. _this._readyToPlayCallback();
  27682. }
  27683. }, function (error) {
  27684. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  27685. });
  27686. };
  27687. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  27688. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27689. this._audioBuffer = audioBuffer;
  27690. this._isReadyToPlay = true;
  27691. }
  27692. };
  27693. Sound.prototype.updateOptions = function (options) {
  27694. if (options) {
  27695. this.loop = options.loop || this.loop;
  27696. this.maxDistance = options.maxDistance || this.maxDistance;
  27697. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  27698. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  27699. this.refDistance = options.refDistance || this.refDistance;
  27700. this.distanceModel = options.distanceModel || this.distanceModel;
  27701. this._playbackRate = options.playbackRate || this._playbackRate;
  27702. }
  27703. };
  27704. Sound.prototype._createSpatialParameters = function () {
  27705. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27706. if (this._scene.headphone) {
  27707. this._panningModel = "HRTF";
  27708. }
  27709. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  27710. if (this.useCustomAttenuation) {
  27711. // Tricks to disable in a way embedded Web Audio attenuation
  27712. this._soundPanner.distanceModel = "linear";
  27713. this._soundPanner.maxDistance = Number.MAX_VALUE;
  27714. this._soundPanner.refDistance = 1;
  27715. this._soundPanner.rolloffFactor = 1;
  27716. this._soundPanner.panningModel = this._panningModel;
  27717. }
  27718. else {
  27719. this._soundPanner.distanceModel = this.distanceModel;
  27720. this._soundPanner.maxDistance = this.maxDistance;
  27721. this._soundPanner.refDistance = this.refDistance;
  27722. this._soundPanner.rolloffFactor = this.rolloffFactor;
  27723. this._soundPanner.panningModel = this._panningModel;
  27724. }
  27725. this._soundPanner.connect(this._ouputAudioNode);
  27726. this._inputAudioNode = this._soundPanner;
  27727. }
  27728. };
  27729. Sound.prototype.switchPanningModelToHRTF = function () {
  27730. this._panningModel = "HRTF";
  27731. this._switchPanningModel();
  27732. };
  27733. Sound.prototype.switchPanningModelToEqualPower = function () {
  27734. this._panningModel = "equalpower";
  27735. this._switchPanningModel();
  27736. };
  27737. Sound.prototype._switchPanningModel = function () {
  27738. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27739. this._soundPanner.panningModel = this._panningModel;
  27740. }
  27741. };
  27742. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  27743. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27744. this._ouputAudioNode.disconnect();
  27745. this._ouputAudioNode.connect(soundTrackAudioNode);
  27746. }
  27747. };
  27748. /**
  27749. * Transform this sound into a directional source
  27750. * @param coneInnerAngle Size of the inner cone in degree
  27751. * @param coneOuterAngle Size of the outer cone in degree
  27752. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  27753. */
  27754. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  27755. if (coneOuterAngle < coneInnerAngle) {
  27756. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  27757. return;
  27758. }
  27759. this._coneInnerAngle = coneInnerAngle;
  27760. this._coneOuterAngle = coneOuterAngle;
  27761. this._coneOuterGain = coneOuterGain;
  27762. this._isDirectional = true;
  27763. if (this.isPlaying && this.loop) {
  27764. this.stop();
  27765. this.play();
  27766. }
  27767. };
  27768. Sound.prototype.setPosition = function (newPosition) {
  27769. this._position = newPosition;
  27770. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27771. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27772. }
  27773. };
  27774. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  27775. this._localDirection = newLocalDirection;
  27776. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  27777. this._updateDirection();
  27778. }
  27779. };
  27780. Sound.prototype._updateDirection = function () {
  27781. var mat = this._connectedMesh.getWorldMatrix();
  27782. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  27783. direction.normalize();
  27784. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  27785. };
  27786. Sound.prototype.updateDistanceFromListener = function () {
  27787. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  27788. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  27789. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  27790. }
  27791. };
  27792. Sound.prototype.setAttenuationFunction = function (callback) {
  27793. this._customAttenuationFunction = callback;
  27794. };
  27795. /**
  27796. * Play the sound
  27797. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  27798. */
  27799. Sound.prototype.play = function (time) {
  27800. var _this = this;
  27801. if (this._isReadyToPlay && this._scene.audioEnabled) {
  27802. try {
  27803. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27804. if (!this._soundSource) {
  27805. if (this.spatialSound) {
  27806. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27807. if (this._isDirectional) {
  27808. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  27809. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  27810. this._soundPanner.coneOuterGain = this._coneOuterGain;
  27811. if (this._connectedMesh) {
  27812. this._updateDirection();
  27813. }
  27814. else {
  27815. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  27816. }
  27817. }
  27818. }
  27819. }
  27820. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  27821. this._soundSource.buffer = this._audioBuffer;
  27822. this._soundSource.connect(this._inputAudioNode);
  27823. this._soundSource.loop = this.loop;
  27824. this._soundSource.playbackRate.value = this._playbackRate;
  27825. this._startTime = startTime;
  27826. this._soundSource.onended = function () {
  27827. _this._onended();
  27828. };
  27829. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  27830. this.isPlaying = true;
  27831. this.isPaused = false;
  27832. }
  27833. catch (ex) {
  27834. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  27835. }
  27836. }
  27837. };
  27838. Sound.prototype._onended = function () {
  27839. this.isPlaying = false;
  27840. if (this.onended) {
  27841. this.onended();
  27842. }
  27843. };
  27844. /**
  27845. * Stop the sound
  27846. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  27847. */
  27848. Sound.prototype.stop = function (time) {
  27849. if (this.isPlaying) {
  27850. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27851. this._soundSource.stop(stopTime);
  27852. this.isPlaying = false;
  27853. }
  27854. };
  27855. Sound.prototype.pause = function () {
  27856. if (this.isPlaying) {
  27857. this.stop(0);
  27858. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  27859. this.isPaused = true;
  27860. }
  27861. };
  27862. Sound.prototype.setVolume = function (newVolume, time) {
  27863. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  27864. if (time) {
  27865. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  27866. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  27867. }
  27868. else {
  27869. this._soundGain.gain.value = newVolume;
  27870. }
  27871. }
  27872. this._volume = newVolume;
  27873. };
  27874. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  27875. this._playbackRate = newPlaybackRate;
  27876. if (this.isPlaying) {
  27877. this._soundSource.playbackRate.value = this._playbackRate;
  27878. }
  27879. };
  27880. Sound.prototype.getVolume = function () {
  27881. return this._volume;
  27882. };
  27883. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  27884. var _this = this;
  27885. this._connectedMesh = meshToConnectTo;
  27886. if (!this.spatialSound) {
  27887. this._createSpatialParameters();
  27888. this.spatialSound = true;
  27889. if (this.isPlaying && this.loop) {
  27890. this.stop();
  27891. this.play();
  27892. }
  27893. }
  27894. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  27895. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  27896. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  27897. };
  27898. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  27899. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  27900. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  27901. this._updateDirection();
  27902. }
  27903. };
  27904. return Sound;
  27905. })();
  27906. BABYLON.Sound = Sound;
  27907. })(BABYLON || (BABYLON = {}));
  27908. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  27909. (function (BABYLON) {
  27910. var SoundTrack = (function () {
  27911. function SoundTrack(scene, options) {
  27912. this.id = -1;
  27913. this._isMainTrack = false;
  27914. this._scene = scene;
  27915. this._audioEngine = BABYLON.Engine.audioEngine;
  27916. this.soundCollection = new Array();
  27917. if (this._audioEngine.canUseWebAudio) {
  27918. this._trackGain = this._audioEngine.audioContext.createGain();
  27919. this._trackGain.connect(this._audioEngine.masterGain);
  27920. if (options) {
  27921. if (options.volume) {
  27922. this._trackGain.gain.value = options.volume;
  27923. }
  27924. if (options.mainTrack) {
  27925. this._isMainTrack = options.mainTrack;
  27926. }
  27927. }
  27928. }
  27929. if (!this._isMainTrack) {
  27930. this._scene.soundTracks.push(this);
  27931. this.id = this._scene.soundTracks.length - 1;
  27932. }
  27933. }
  27934. SoundTrack.prototype.dispose = function () {
  27935. if (this._audioEngine.canUseWebAudio) {
  27936. if (this._connectedAnalyser) {
  27937. this._connectedAnalyser.stopDebugCanvas();
  27938. }
  27939. while (this.soundCollection.length) {
  27940. this.soundCollection[0].dispose();
  27941. }
  27942. this._trackGain.disconnect();
  27943. this._trackGain = null;
  27944. }
  27945. };
  27946. SoundTrack.prototype.AddSound = function (sound) {
  27947. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27948. sound.connectToSoundTrackAudioNode(this._trackGain);
  27949. }
  27950. if (sound.soundTrackId) {
  27951. if (sound.soundTrackId === -1) {
  27952. this._scene.mainSoundTrack.RemoveSound(sound);
  27953. }
  27954. else {
  27955. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  27956. }
  27957. }
  27958. this.soundCollection.push(sound);
  27959. sound.soundTrackId = this.id;
  27960. };
  27961. SoundTrack.prototype.RemoveSound = function (sound) {
  27962. var index = this.soundCollection.indexOf(sound);
  27963. if (index !== -1) {
  27964. this.soundCollection.splice(index, 1);
  27965. }
  27966. };
  27967. SoundTrack.prototype.setVolume = function (newVolume) {
  27968. if (this._audioEngine.canUseWebAudio) {
  27969. this._trackGain.gain.value = newVolume;
  27970. }
  27971. };
  27972. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  27973. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27974. for (var i = 0; i < this.soundCollection.length; i++) {
  27975. this.soundCollection[i].switchPanningModelToHRTF();
  27976. }
  27977. }
  27978. };
  27979. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  27980. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27981. for (var i = 0; i < this.soundCollection.length; i++) {
  27982. this.soundCollection[i].switchPanningModelToEqualPower();
  27983. }
  27984. }
  27985. };
  27986. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  27987. if (this._connectedAnalyser) {
  27988. this._connectedAnalyser.stopDebugCanvas();
  27989. }
  27990. this._connectedAnalyser = analyser;
  27991. if (this._audioEngine.canUseWebAudio) {
  27992. this._trackGain.disconnect();
  27993. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  27994. }
  27995. };
  27996. return SoundTrack;
  27997. })();
  27998. BABYLON.SoundTrack = SoundTrack;
  27999. })(BABYLON || (BABYLON = {}));
  28000. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  28001. (function (BABYLON) {
  28002. var DebugLayer = (function () {
  28003. function DebugLayer(scene) {
  28004. var _this = this;
  28005. this._transformationMatrix = BABYLON.Matrix.Identity();
  28006. this._enabled = false;
  28007. this._labelsEnabled = false;
  28008. this._displayStatistics = true;
  28009. this._displayTree = false;
  28010. this._displayLogs = false;
  28011. this._identityMatrix = BABYLON.Matrix.Identity();
  28012. this.axisRatio = 0.02;
  28013. this.accentColor = "orange";
  28014. this._scene = scene;
  28015. this._syncPositions = function () {
  28016. var engine = _this._scene.getEngine();
  28017. var canvasRect = engine.getRenderingCanvasClientRect();
  28018. if (_this._showUI) {
  28019. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  28020. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  28021. _this._statsDiv.style.width = "400px";
  28022. _this._statsDiv.style.height = "auto";
  28023. _this._statsSubsetDiv.style.maxHeight = "240px";
  28024. _this._optionsDiv.style.left = "0px";
  28025. _this._optionsDiv.style.top = "10px";
  28026. _this._optionsDiv.style.width = "200px";
  28027. _this._optionsDiv.style.height = "auto";
  28028. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  28029. _this._logDiv.style.left = "0px";
  28030. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  28031. _this._logDiv.style.width = "600px";
  28032. _this._logDiv.style.height = "160px";
  28033. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  28034. _this._treeDiv.style.top = "10px";
  28035. _this._treeDiv.style.width = "300px";
  28036. _this._treeDiv.style.height = "auto";
  28037. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  28038. }
  28039. _this._globalDiv.style.left = canvasRect.left + "px";
  28040. _this._globalDiv.style.top = canvasRect.top + "px";
  28041. _this._drawingCanvas.style.left = "0px";
  28042. _this._drawingCanvas.style.top = "0px";
  28043. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  28044. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  28045. var devicePixelRatio = window.devicePixelRatio || 1;
  28046. var context = _this._drawingContext;
  28047. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  28048. _this._ratio = devicePixelRatio / backingStoreRatio;
  28049. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  28050. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  28051. };
  28052. this._onCanvasClick = function (evt) {
  28053. _this._clickPosition = {
  28054. x: evt.clientX * _this._ratio,
  28055. y: evt.clientY * _this._ratio
  28056. };
  28057. };
  28058. this._syncUI = function () {
  28059. if (_this._showUI) {
  28060. if (_this._displayStatistics) {
  28061. _this._displayStats();
  28062. _this._statsDiv.style.display = "";
  28063. }
  28064. else {
  28065. _this._statsDiv.style.display = "none";
  28066. }
  28067. if (_this._displayLogs) {
  28068. _this._logDiv.style.display = "";
  28069. }
  28070. else {
  28071. _this._logDiv.style.display = "none";
  28072. }
  28073. if (_this._displayTree) {
  28074. _this._treeDiv.style.display = "";
  28075. if (_this._needToRefreshMeshesTree) {
  28076. _this._needToRefreshMeshesTree = false;
  28077. _this._refreshMeshesTreeContent();
  28078. }
  28079. }
  28080. else {
  28081. _this._treeDiv.style.display = "none";
  28082. }
  28083. }
  28084. };
  28085. this._syncData = function () {
  28086. if (_this._labelsEnabled || !_this._showUI) {
  28087. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  28088. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  28089. var engine = _this._scene.getEngine();
  28090. var viewport = _this._camera.viewport;
  28091. var globalViewport = viewport.toGlobal(engine);
  28092. // Meshes
  28093. var meshes = _this._camera.getActiveMeshes();
  28094. for (var index = 0; index < meshes.length; index++) {
  28095. var mesh = meshes.data[index];
  28096. var position = mesh.getBoundingInfo().boundingSphere.center;
  28097. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28098. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  28099. _this._renderAxis(projectedPosition, mesh, globalViewport);
  28100. }
  28101. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  28102. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  28103. mesh.renderOverlay = !mesh.renderOverlay;
  28104. }, function () {
  28105. return mesh.renderOverlay ? 'red' : 'black';
  28106. });
  28107. }
  28108. }
  28109. // Cameras
  28110. var cameras = _this._scene.cameras;
  28111. for (index = 0; index < cameras.length; index++) {
  28112. var camera = cameras[index];
  28113. if (camera === _this._camera) {
  28114. continue;
  28115. }
  28116. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28117. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  28118. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  28119. _this._camera.detachControl(engine.getRenderingCanvas());
  28120. _this._camera = camera;
  28121. _this._camera.attachControl(engine.getRenderingCanvas());
  28122. }, function () {
  28123. return "purple";
  28124. });
  28125. }
  28126. }
  28127. // Lights
  28128. var lights = _this._scene.lights;
  28129. for (index = 0; index < lights.length; index++) {
  28130. var light = lights[index];
  28131. if (light.position) {
  28132. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  28133. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  28134. _this._renderLabel(light.name, projectedPosition, -20, function () {
  28135. light.setEnabled(!light.isEnabled());
  28136. }, function () {
  28137. return light.isEnabled() ? "orange" : "gray";
  28138. });
  28139. }
  28140. }
  28141. }
  28142. }
  28143. _this._clickPosition = undefined;
  28144. };
  28145. }
  28146. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  28147. while (this._treeSubsetDiv.hasChildNodes()) {
  28148. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  28149. }
  28150. // Add meshes
  28151. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  28152. sortedArray.sort(function (a, b) {
  28153. if (a.name === b.name) {
  28154. return 0;
  28155. }
  28156. return (a.name > b.name) ? 1 : -1;
  28157. });
  28158. for (var index = 0; index < sortedArray.length; index++) {
  28159. var mesh = sortedArray[index];
  28160. if (!mesh.isEnabled()) {
  28161. continue;
  28162. }
  28163. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  28164. m.isVisible = element.checked;
  28165. }, mesh);
  28166. }
  28167. };
  28168. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  28169. this._drawingContext.beginPath();
  28170. this._drawingContext.moveTo(zero.x, zero.y);
  28171. this._drawingContext.lineTo(unit.x, unit.y);
  28172. this._drawingContext.strokeStyle = color;
  28173. this._drawingContext.lineWidth = 4;
  28174. this._drawingContext.stroke();
  28175. this._drawingContext.font = "normal 14px Segoe UI";
  28176. this._drawingContext.fillStyle = color;
  28177. this._drawingContext.fillText(label, unitText.x, unitText.y);
  28178. };
  28179. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  28180. var position = mesh.getBoundingInfo().boundingSphere.center;
  28181. var worldMatrix = mesh.getWorldMatrix();
  28182. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  28183. var unit = (unprojectedVector.subtract(position)).length();
  28184. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28185. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28186. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  28187. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28188. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28189. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  28190. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  28191. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  28192. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  28193. };
  28194. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  28195. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  28196. this._drawingContext.font = "normal 12px Segoe UI";
  28197. var textMetrics = this._drawingContext.measureText(text);
  28198. var centerX = projectedPosition.x - textMetrics.width / 2;
  28199. var centerY = projectedPosition.y;
  28200. var clientRect = this._drawingCanvas.getBoundingClientRect();
  28201. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  28202. onClick();
  28203. }
  28204. this._drawingContext.beginPath();
  28205. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  28206. this._drawingContext.fillStyle = getFillStyle();
  28207. this._drawingContext.globalAlpha = 0.5;
  28208. this._drawingContext.fill();
  28209. this._drawingContext.globalAlpha = 1.0;
  28210. this._drawingContext.strokeStyle = '#FFFFFF';
  28211. this._drawingContext.lineWidth = 1;
  28212. this._drawingContext.stroke();
  28213. this._drawingContext.fillStyle = "#FFFFFF";
  28214. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  28215. this._drawingContext.beginPath();
  28216. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  28217. this._drawingContext.fill();
  28218. }
  28219. };
  28220. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  28221. if (!this._clickPosition) {
  28222. return false;
  28223. }
  28224. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  28225. return false;
  28226. }
  28227. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  28228. return false;
  28229. }
  28230. return true;
  28231. };
  28232. DebugLayer.prototype.isVisible = function () {
  28233. return this._enabled;
  28234. };
  28235. DebugLayer.prototype.hide = function () {
  28236. if (!this._enabled) {
  28237. return;
  28238. }
  28239. this._enabled = false;
  28240. var engine = this._scene.getEngine();
  28241. this._scene.unregisterBeforeRender(this._syncData);
  28242. this._scene.unregisterAfterRender(this._syncUI);
  28243. document.body.removeChild(this._globalDiv);
  28244. window.removeEventListener("resize", this._syncPositions);
  28245. this._scene.forceShowBoundingBoxes = false;
  28246. this._scene.forceWireframe = false;
  28247. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  28248. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  28249. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  28250. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  28251. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  28252. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  28253. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  28254. this._scene.shadowsEnabled = true;
  28255. this._scene.particlesEnabled = true;
  28256. this._scene.postProcessesEnabled = true;
  28257. this._scene.collisionsEnabled = true;
  28258. this._scene.lightsEnabled = true;
  28259. this._scene.texturesEnabled = true;
  28260. this._scene.lensFlaresEnabled = true;
  28261. this._scene.proceduralTexturesEnabled = true;
  28262. this._scene.renderTargetsEnabled = true;
  28263. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  28264. };
  28265. DebugLayer.prototype.show = function (showUI, camera) {
  28266. if (showUI === void 0) { showUI = true; }
  28267. if (camera === void 0) { camera = null; }
  28268. if (this._enabled) {
  28269. return;
  28270. }
  28271. this._enabled = true;
  28272. if (camera) {
  28273. this._camera = camera;
  28274. }
  28275. else {
  28276. this._camera = this._scene.activeCamera;
  28277. }
  28278. this._showUI = showUI;
  28279. var engine = this._scene.getEngine();
  28280. this._globalDiv = document.createElement("div");
  28281. document.body.appendChild(this._globalDiv);
  28282. this._generateDOMelements();
  28283. window.addEventListener("resize", this._syncPositions);
  28284. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  28285. this._syncPositions();
  28286. this._scene.registerBeforeRender(this._syncData);
  28287. this._scene.registerAfterRender(this._syncUI);
  28288. };
  28289. DebugLayer.prototype._clearLabels = function () {
  28290. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  28291. for (var index = 0; index < this._scene.meshes.length; index++) {
  28292. var mesh = this._scene.meshes[index];
  28293. mesh.renderOverlay = false;
  28294. }
  28295. };
  28296. DebugLayer.prototype._generateheader = function (root, text) {
  28297. var header = document.createElement("div");
  28298. header.innerHTML = text + "&nbsp;";
  28299. header.style.textAlign = "right";
  28300. header.style.width = "100%";
  28301. header.style.color = "white";
  28302. header.style.backgroundColor = "Black";
  28303. header.style.padding = "5px 5px 4px 0px";
  28304. header.style.marginLeft = "-5px";
  28305. header.style.fontWeight = "bold";
  28306. root.appendChild(header);
  28307. };
  28308. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  28309. var label = document.createElement("label");
  28310. label.innerHTML = title;
  28311. label.style.color = color;
  28312. root.appendChild(label);
  28313. root.appendChild(document.createElement("br"));
  28314. };
  28315. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  28316. if (tag === void 0) { tag = null; }
  28317. var label = document.createElement("label");
  28318. var boundingBoxesCheckbox = document.createElement("input");
  28319. boundingBoxesCheckbox.type = "checkbox";
  28320. boundingBoxesCheckbox.checked = initialState;
  28321. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  28322. task(evt.target, tag);
  28323. });
  28324. label.appendChild(boundingBoxesCheckbox);
  28325. var container = document.createElement("span");
  28326. var leftPart = document.createElement("span");
  28327. var rightPart = document.createElement("span");
  28328. rightPart.style.cssFloat = "right";
  28329. leftPart.innerHTML = leftTitle;
  28330. rightPart.innerHTML = rightTitle;
  28331. rightPart.style.fontSize = "12px";
  28332. rightPart.style.maxWidth = "200px";
  28333. container.appendChild(leftPart);
  28334. container.appendChild(rightPart);
  28335. label.appendChild(container);
  28336. root.appendChild(label);
  28337. root.appendChild(document.createElement("br"));
  28338. };
  28339. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28340. if (tag === void 0) { tag = null; }
  28341. var label = document.createElement("label");
  28342. var checkBox = document.createElement("input");
  28343. checkBox.type = "checkbox";
  28344. checkBox.checked = initialState;
  28345. checkBox.addEventListener("change", function (evt) {
  28346. task(evt.target, tag);
  28347. });
  28348. label.appendChild(checkBox);
  28349. label.appendChild(document.createTextNode(title));
  28350. root.appendChild(label);
  28351. root.appendChild(document.createElement("br"));
  28352. };
  28353. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28354. if (tag === void 0) { tag = null; }
  28355. var button = document.createElement("button");
  28356. button.innerHTML = title;
  28357. button.style.height = "24px";
  28358. button.style.color = "#444444";
  28359. button.style.border = "1px solid white";
  28360. button.className = "debugLayerButton";
  28361. button.addEventListener("click", function (evt) {
  28362. task(evt.target, tag);
  28363. });
  28364. root.appendChild(button);
  28365. root.appendChild(document.createElement("br"));
  28366. };
  28367. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28368. if (tag === void 0) { tag = null; }
  28369. var label = document.createElement("label");
  28370. var boundingBoxesRadio = document.createElement("input");
  28371. boundingBoxesRadio.type = "radio";
  28372. boundingBoxesRadio.name = name;
  28373. boundingBoxesRadio.checked = initialState;
  28374. boundingBoxesRadio.addEventListener("change", function (evt) {
  28375. task(evt.target, tag);
  28376. });
  28377. label.appendChild(boundingBoxesRadio);
  28378. label.appendChild(document.createTextNode(title));
  28379. root.appendChild(label);
  28380. root.appendChild(document.createElement("br"));
  28381. };
  28382. DebugLayer.prototype._generateDOMelements = function () {
  28383. var _this = this;
  28384. this._globalDiv.id = "DebugLayer";
  28385. this._globalDiv.style.position = "absolute";
  28386. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28387. this._globalDiv.style.fontSize = "14px";
  28388. this._globalDiv.style.color = "white";
  28389. // Drawing canvas
  28390. this._drawingCanvas = document.createElement("canvas");
  28391. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28392. this._drawingCanvas.style.position = "absolute";
  28393. this._drawingCanvas.style.pointerEvents = "none";
  28394. this._drawingContext = this._drawingCanvas.getContext("2d");
  28395. this._globalDiv.appendChild(this._drawingCanvas);
  28396. if (this._showUI) {
  28397. var background = "rgba(128, 128, 128, 0.4)";
  28398. var border = "rgb(180, 180, 180) solid 1px";
  28399. // Stats
  28400. this._statsDiv = document.createElement("div");
  28401. this._statsDiv.id = "DebugLayerStats";
  28402. this._statsDiv.style.border = border;
  28403. this._statsDiv.style.position = "absolute";
  28404. this._statsDiv.style.background = background;
  28405. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28406. this._generateheader(this._statsDiv, "STATISTICS");
  28407. this._statsSubsetDiv = document.createElement("div");
  28408. this._statsSubsetDiv.style.paddingTop = "5px";
  28409. this._statsSubsetDiv.style.paddingBottom = "5px";
  28410. this._statsSubsetDiv.style.overflowY = "auto";
  28411. this._statsDiv.appendChild(this._statsSubsetDiv);
  28412. // Tree
  28413. this._treeDiv = document.createElement("div");
  28414. this._treeDiv.id = "DebugLayerTree";
  28415. this._treeDiv.style.border = border;
  28416. this._treeDiv.style.position = "absolute";
  28417. this._treeDiv.style.background = background;
  28418. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28419. this._treeDiv.style.display = "none";
  28420. this._generateheader(this._treeDiv, "MESHES TREE");
  28421. this._treeSubsetDiv = document.createElement("div");
  28422. this._treeSubsetDiv.style.paddingTop = "5px";
  28423. this._treeSubsetDiv.style.paddingRight = "5px";
  28424. this._treeSubsetDiv.style.overflowY = "auto";
  28425. this._treeSubsetDiv.style.maxHeight = "300px";
  28426. this._treeDiv.appendChild(this._treeSubsetDiv);
  28427. this._needToRefreshMeshesTree = true;
  28428. // Logs
  28429. this._logDiv = document.createElement("div");
  28430. this._logDiv.style.border = border;
  28431. this._logDiv.id = "DebugLayerLogs";
  28432. this._logDiv.style.position = "absolute";
  28433. this._logDiv.style.background = background;
  28434. this._logDiv.style.padding = "0px 0px 0px 5px";
  28435. this._logDiv.style.display = "none";
  28436. this._generateheader(this._logDiv, "LOGS");
  28437. this._logSubsetDiv = document.createElement("div");
  28438. this._logSubsetDiv.style.height = "127px";
  28439. this._logSubsetDiv.style.paddingTop = "5px";
  28440. this._logSubsetDiv.style.overflowY = "auto";
  28441. this._logSubsetDiv.style.fontSize = "12px";
  28442. this._logSubsetDiv.style.fontFamily = "consolas";
  28443. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28444. this._logDiv.appendChild(this._logSubsetDiv);
  28445. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28446. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28447. };
  28448. // Options
  28449. this._optionsDiv = document.createElement("div");
  28450. this._optionsDiv.id = "DebugLayerOptions";
  28451. this._optionsDiv.style.border = border;
  28452. this._optionsDiv.style.position = "absolute";
  28453. this._optionsDiv.style.background = background;
  28454. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28455. this._optionsDiv.style.overflowY = "auto";
  28456. this._generateheader(this._optionsDiv, "OPTIONS");
  28457. this._optionsSubsetDiv = document.createElement("div");
  28458. this._optionsSubsetDiv.style.paddingTop = "5px";
  28459. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28460. this._optionsSubsetDiv.style.overflowY = "auto";
  28461. this._optionsSubsetDiv.style.maxHeight = "200px";
  28462. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28463. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28464. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  28465. _this._displayStatistics = element.checked;
  28466. });
  28467. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  28468. _this._displayLogs = element.checked;
  28469. });
  28470. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28471. _this._displayTree = element.checked;
  28472. _this._needToRefreshMeshesTree = true;
  28473. });
  28474. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28475. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28476. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  28477. _this._scene.forceShowBoundingBoxes = element.checked;
  28478. });
  28479. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28480. _this._labelsEnabled = element.checked;
  28481. if (!_this._labelsEnabled) {
  28482. _this._clearLabels();
  28483. }
  28484. });
  28485. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28486. if (element.checked) {
  28487. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28488. }
  28489. else {
  28490. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28491. }
  28492. });
  28493. ;
  28494. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28495. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28496. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28497. if (element.checked) {
  28498. _this._scene.forceWireframe = false;
  28499. _this._scene.forcePointsCloud = false;
  28500. }
  28501. });
  28502. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28503. if (element.checked) {
  28504. _this._scene.forceWireframe = true;
  28505. _this._scene.forcePointsCloud = false;
  28506. }
  28507. });
  28508. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28509. if (element.checked) {
  28510. _this._scene.forceWireframe = false;
  28511. _this._scene.forcePointsCloud = true;
  28512. }
  28513. });
  28514. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28515. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28516. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  28517. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  28518. });
  28519. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  28520. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  28521. });
  28522. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  28523. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  28524. });
  28525. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  28526. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  28527. });
  28528. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  28529. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  28530. });
  28531. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  28532. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  28533. });
  28534. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  28535. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  28536. });
  28537. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  28538. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  28539. });
  28540. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28541. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28542. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  28543. _this._scene.animationsEnabled = element.checked;
  28544. });
  28545. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  28546. _this._scene.collisionsEnabled = element.checked;
  28547. });
  28548. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  28549. _this._scene.fogEnabled = element.checked;
  28550. });
  28551. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  28552. _this._scene.lensFlaresEnabled = element.checked;
  28553. });
  28554. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  28555. _this._scene.lightsEnabled = element.checked;
  28556. });
  28557. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  28558. _this._scene.particlesEnabled = element.checked;
  28559. });
  28560. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  28561. _this._scene.postProcessesEnabled = element.checked;
  28562. });
  28563. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  28564. _this._scene.proceduralTexturesEnabled = element.checked;
  28565. });
  28566. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  28567. _this._scene.renderTargetsEnabled = element.checked;
  28568. });
  28569. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  28570. _this._scene.shadowsEnabled = element.checked;
  28571. });
  28572. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  28573. _this._scene.skeletonsEnabled = element.checked;
  28574. });
  28575. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  28576. _this._scene.spritesEnabled = element.checked;
  28577. });
  28578. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  28579. _this._scene.texturesEnabled = element.checked;
  28580. });
  28581. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28582. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28583. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28584. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28585. if (element.checked) {
  28586. _this._scene.headphone = true;
  28587. }
  28588. });
  28589. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28590. if (element.checked) {
  28591. _this._scene.headphone = false;
  28592. }
  28593. });
  28594. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28595. _this._scene.audioEnabled = !element.checked;
  28596. });
  28597. }
  28598. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28599. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28600. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  28601. _this._scene.dumpNextRenderTargets = true;
  28602. });
  28603. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28604. this._globalDiv.appendChild(this._statsDiv);
  28605. this._globalDiv.appendChild(this._logDiv);
  28606. this._globalDiv.appendChild(this._optionsDiv);
  28607. this._globalDiv.appendChild(this._treeDiv);
  28608. }
  28609. };
  28610. DebugLayer.prototype._displayStats = function () {
  28611. var scene = this._scene;
  28612. var engine = scene.getEngine();
  28613. var glInfo = engine.getGlInfo();
  28614. 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 indices: " + scene.getActiveIndices() + "<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>";
  28615. if (this.customStatsFunction) {
  28616. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28617. }
  28618. };
  28619. return DebugLayer;
  28620. })();
  28621. BABYLON.DebugLayer = DebugLayer;
  28622. })(BABYLON || (BABYLON = {}));
  28623. //# sourceMappingURL=babylon.debugLayer.js.map
  28624. var BABYLON;
  28625. (function (BABYLON) {
  28626. var RawTexture = (function (_super) {
  28627. __extends(RawTexture, _super);
  28628. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  28629. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28630. if (invertY === void 0) { invertY = false; }
  28631. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28632. _super.call(this, null, scene, !generateMipMaps, invertY);
  28633. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  28634. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28635. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28636. }
  28637. // Statics
  28638. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28639. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28640. if (invertY === void 0) { invertY = false; }
  28641. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28642. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  28643. };
  28644. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28645. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28646. if (invertY === void 0) { invertY = false; }
  28647. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28648. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28649. };
  28650. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28651. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28652. if (invertY === void 0) { invertY = false; }
  28653. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28654. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28655. };
  28656. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28657. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28658. if (invertY === void 0) { invertY = false; }
  28659. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28660. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  28661. };
  28662. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28663. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28664. if (invertY === void 0) { invertY = false; }
  28665. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28666. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  28667. };
  28668. return RawTexture;
  28669. })(BABYLON.Texture);
  28670. BABYLON.RawTexture = RawTexture;
  28671. })(BABYLON || (BABYLON = {}));
  28672. //# sourceMappingURL=babylon.rawTexture.js.map
  28673. var BABYLON;
  28674. (function (BABYLON) {
  28675. var IndexedVector2 = (function (_super) {
  28676. __extends(IndexedVector2, _super);
  28677. function IndexedVector2(original, index) {
  28678. _super.call(this, original.x, original.y);
  28679. this.index = index;
  28680. }
  28681. return IndexedVector2;
  28682. })(BABYLON.Vector2);
  28683. var PolygonPoints = (function () {
  28684. function PolygonPoints() {
  28685. this.elements = new Array();
  28686. }
  28687. PolygonPoints.prototype.add = function (originalPoints) {
  28688. var _this = this;
  28689. var result = new Array();
  28690. originalPoints.forEach(function (point) {
  28691. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  28692. var newPoint = new IndexedVector2(point, _this.elements.length);
  28693. result.push(newPoint);
  28694. _this.elements.push(newPoint);
  28695. }
  28696. });
  28697. return result;
  28698. };
  28699. PolygonPoints.prototype.computeBounds = function () {
  28700. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28701. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28702. this.elements.forEach(function (point) {
  28703. // x
  28704. if (point.x < lmin.x) {
  28705. lmin.x = point.x;
  28706. }
  28707. else if (point.x > lmax.x) {
  28708. lmax.x = point.x;
  28709. }
  28710. // y
  28711. if (point.y < lmin.y) {
  28712. lmin.y = point.y;
  28713. }
  28714. else if (point.y > lmax.y) {
  28715. lmax.y = point.y;
  28716. }
  28717. });
  28718. return {
  28719. min: lmin,
  28720. max: lmax,
  28721. width: lmax.x - lmin.x,
  28722. height: lmax.y - lmin.y
  28723. };
  28724. };
  28725. return PolygonPoints;
  28726. })();
  28727. var Polygon = (function () {
  28728. function Polygon() {
  28729. }
  28730. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  28731. return [
  28732. new BABYLON.Vector2(xmin, ymin),
  28733. new BABYLON.Vector2(xmax, ymin),
  28734. new BABYLON.Vector2(xmax, ymax),
  28735. new BABYLON.Vector2(xmin, ymax)
  28736. ];
  28737. };
  28738. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  28739. if (cx === void 0) { cx = 0; }
  28740. if (cy === void 0) { cy = 0; }
  28741. if (numberOfSides === void 0) { numberOfSides = 32; }
  28742. var result = new Array();
  28743. var angle = 0;
  28744. var increment = (Math.PI * 2) / numberOfSides;
  28745. for (var i = 0; i < numberOfSides; i++) {
  28746. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  28747. angle -= increment;
  28748. }
  28749. return result;
  28750. };
  28751. Polygon.Parse = function (input) {
  28752. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  28753. var i, result = [];
  28754. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  28755. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  28756. }
  28757. return result;
  28758. };
  28759. Polygon.StartingAt = function (x, y) {
  28760. return BABYLON.Path2.StartingAt(x, y);
  28761. };
  28762. return Polygon;
  28763. })();
  28764. BABYLON.Polygon = Polygon;
  28765. var PolygonMeshBuilder = (function () {
  28766. function PolygonMeshBuilder(name, contours, scene) {
  28767. this._points = new PolygonPoints();
  28768. if (!("poly2tri" in window)) {
  28769. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  28770. }
  28771. this._name = name;
  28772. this._scene = scene;
  28773. var points;
  28774. if (contours instanceof BABYLON.Path2) {
  28775. points = contours.getPoints();
  28776. }
  28777. else {
  28778. points = contours;
  28779. }
  28780. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  28781. }
  28782. PolygonMeshBuilder.prototype.addHole = function (hole) {
  28783. this._swctx.addHole(this._points.add(hole));
  28784. return this;
  28785. };
  28786. PolygonMeshBuilder.prototype.build = function (updatable) {
  28787. if (updatable === void 0) { updatable = false; }
  28788. var result = new BABYLON.Mesh(this._name, this._scene);
  28789. var normals = [];
  28790. var positions = [];
  28791. var uvs = [];
  28792. var bounds = this._points.computeBounds();
  28793. this._points.elements.forEach(function (p) {
  28794. normals.push(0, 1.0, 0);
  28795. positions.push(p.x, 0, p.y);
  28796. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  28797. });
  28798. var indices = [];
  28799. this._swctx.triangulate();
  28800. this._swctx.getTriangles().forEach(function (triangle) {
  28801. triangle.getPoints().forEach(function (point) {
  28802. indices.push(point.index);
  28803. });
  28804. });
  28805. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  28806. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  28807. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  28808. result.setIndices(indices);
  28809. return result;
  28810. };
  28811. return PolygonMeshBuilder;
  28812. })();
  28813. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  28814. })(BABYLON || (BABYLON = {}));
  28815. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  28816. (function (BABYLON) {
  28817. var SimplificationSettings = (function () {
  28818. function SimplificationSettings(quality, distance, optimizeMesh) {
  28819. this.quality = quality;
  28820. this.distance = distance;
  28821. this.optimizeMesh = optimizeMesh;
  28822. }
  28823. return SimplificationSettings;
  28824. })();
  28825. BABYLON.SimplificationSettings = SimplificationSettings;
  28826. var SimplificationQueue = (function () {
  28827. function SimplificationQueue() {
  28828. this.running = false;
  28829. this._simplificationArray = [];
  28830. }
  28831. SimplificationQueue.prototype.addTask = function (task) {
  28832. this._simplificationArray.push(task);
  28833. };
  28834. SimplificationQueue.prototype.executeNext = function () {
  28835. var task = this._simplificationArray.pop();
  28836. if (task) {
  28837. this.running = true;
  28838. this.runSimplification(task);
  28839. }
  28840. else {
  28841. this.running = false;
  28842. }
  28843. };
  28844. SimplificationQueue.prototype.runSimplification = function (task) {
  28845. var _this = this;
  28846. if (task.parallelProcessing) {
  28847. //parallel simplifier
  28848. task.settings.forEach(function (setting) {
  28849. var simplifier = _this.getSimplifier(task);
  28850. simplifier.simplify(setting, function (newMesh) {
  28851. task.mesh.addLODLevel(setting.distance, newMesh);
  28852. newMesh.isVisible = true;
  28853. //check if it is the last
  28854. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28855. //all done, run the success callback.
  28856. task.successCallback();
  28857. }
  28858. _this.executeNext();
  28859. });
  28860. });
  28861. }
  28862. else {
  28863. //single simplifier.
  28864. var simplifier = this.getSimplifier(task);
  28865. var runDecimation = function (setting, callback) {
  28866. simplifier.simplify(setting, function (newMesh) {
  28867. task.mesh.addLODLevel(setting.distance, newMesh);
  28868. newMesh.isVisible = true;
  28869. //run the next quality level
  28870. callback();
  28871. });
  28872. };
  28873. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28874. runDecimation(task.settings[loop.index], function () {
  28875. loop.executeNext();
  28876. });
  28877. }, function () {
  28878. //execution ended, run the success callback.
  28879. if (task.successCallback) {
  28880. task.successCallback();
  28881. }
  28882. _this.executeNext();
  28883. });
  28884. }
  28885. };
  28886. SimplificationQueue.prototype.getSimplifier = function (task) {
  28887. switch (task.simplificationType) {
  28888. case 0 /* QUADRATIC */:
  28889. default:
  28890. return new QuadraticErrorSimplification(task.mesh);
  28891. }
  28892. };
  28893. return SimplificationQueue;
  28894. })();
  28895. BABYLON.SimplificationQueue = SimplificationQueue;
  28896. /**
  28897. * The implemented types of simplification.
  28898. * At the moment only Quadratic Error Decimation is implemented.
  28899. */
  28900. (function (SimplificationType) {
  28901. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28902. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28903. var SimplificationType = BABYLON.SimplificationType;
  28904. var DecimationTriangle = (function () {
  28905. function DecimationTriangle(vertices) {
  28906. this.vertices = vertices;
  28907. this.error = new Array(4);
  28908. this.deleted = false;
  28909. this.isDirty = false;
  28910. this.deletePending = false;
  28911. this.borderFactor = 0;
  28912. }
  28913. return DecimationTriangle;
  28914. })();
  28915. BABYLON.DecimationTriangle = DecimationTriangle;
  28916. var DecimationVertex = (function () {
  28917. function DecimationVertex(position, id) {
  28918. this.position = position;
  28919. this.id = id;
  28920. this.isBorder = true;
  28921. this.q = new QuadraticMatrix();
  28922. this.triangleCount = 0;
  28923. this.triangleStart = 0;
  28924. this.originalOffsets = [];
  28925. }
  28926. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28927. this.position.copyFrom(newPosition);
  28928. };
  28929. return DecimationVertex;
  28930. })();
  28931. BABYLON.DecimationVertex = DecimationVertex;
  28932. var QuadraticMatrix = (function () {
  28933. function QuadraticMatrix(data) {
  28934. this.data = new Array(10);
  28935. for (var i = 0; i < 10; ++i) {
  28936. if (data && data[i]) {
  28937. this.data[i] = data[i];
  28938. }
  28939. else {
  28940. this.data[i] = 0;
  28941. }
  28942. }
  28943. }
  28944. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28945. 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];
  28946. return det;
  28947. };
  28948. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28949. for (var i = 0; i < 10; ++i) {
  28950. this.data[i] += matrix.data[i];
  28951. }
  28952. };
  28953. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28954. for (var i = 0; i < 10; ++i) {
  28955. this.data[i] += data[i];
  28956. }
  28957. };
  28958. QuadraticMatrix.prototype.add = function (matrix) {
  28959. var m = new QuadraticMatrix();
  28960. for (var i = 0; i < 10; ++i) {
  28961. m.data[i] = this.data[i] + matrix.data[i];
  28962. }
  28963. return m;
  28964. };
  28965. QuadraticMatrix.FromData = function (a, b, c, d) {
  28966. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28967. };
  28968. //returning an array to avoid garbage collection
  28969. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28970. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28971. };
  28972. return QuadraticMatrix;
  28973. })();
  28974. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28975. var Reference = (function () {
  28976. function Reference(vertexId, triangleId) {
  28977. this.vertexId = vertexId;
  28978. this.triangleId = triangleId;
  28979. }
  28980. return Reference;
  28981. })();
  28982. BABYLON.Reference = Reference;
  28983. /**
  28984. * An implementation of the Quadratic Error simplification algorithm.
  28985. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28986. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28987. * @author RaananW
  28988. */
  28989. var QuadraticErrorSimplification = (function () {
  28990. function QuadraticErrorSimplification(_mesh) {
  28991. this._mesh = _mesh;
  28992. this.initialized = false;
  28993. this.syncIterations = 5000;
  28994. this.aggressiveness = 7;
  28995. this.decimationIterations = 100;
  28996. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28997. }
  28998. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28999. var _this = this;
  29000. this.initDecimatedMesh();
  29001. //iterating through the submeshes array, one after the other.
  29002. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  29003. _this.initWithMesh(loop.index, function () {
  29004. _this.runDecimation(settings, loop.index, function () {
  29005. loop.executeNext();
  29006. });
  29007. }, settings.optimizeMesh);
  29008. }, function () {
  29009. setTimeout(function () {
  29010. successCallback(_this._reconstructedMesh);
  29011. }, 0);
  29012. });
  29013. };
  29014. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  29015. var _this = this;
  29016. var gCount = 0;
  29017. triangle.vertices.forEach(function (vertex) {
  29018. var count = 0;
  29019. var vPos = vertex.position;
  29020. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  29021. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  29022. ++count;
  29023. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  29024. ++count;
  29025. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  29026. ++count;
  29027. if (count > 1) {
  29028. ++gCount;
  29029. }
  29030. ;
  29031. });
  29032. if (gCount > 1) {
  29033. console.log(triangle, gCount);
  29034. }
  29035. return gCount > 1;
  29036. };
  29037. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  29038. var _this = this;
  29039. var targetCount = ~~(this.triangles.length * settings.quality);
  29040. var deletedTriangles = 0;
  29041. var triangleCount = this.triangles.length;
  29042. var iterationFunction = function (iteration, callback) {
  29043. setTimeout(function () {
  29044. if (iteration % 5 === 0) {
  29045. _this.updateMesh(iteration === 0);
  29046. }
  29047. for (var i = 0; i < _this.triangles.length; ++i) {
  29048. _this.triangles[i].isDirty = false;
  29049. }
  29050. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  29051. var trianglesIterator = function (i) {
  29052. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  29053. var t = _this.triangles[tIdx];
  29054. if (!t)
  29055. return;
  29056. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  29057. return;
  29058. }
  29059. for (var j = 0; j < 3; ++j) {
  29060. if (t.error[j] < threshold) {
  29061. var deleted0 = [];
  29062. var deleted1 = [];
  29063. var v0 = t.vertices[j];
  29064. var v1 = t.vertices[(j + 1) % 3];
  29065. if (v0.isBorder !== v1.isBorder)
  29066. continue;
  29067. var p = BABYLON.Vector3.Zero();
  29068. var n = BABYLON.Vector3.Zero();
  29069. var uv = BABYLON.Vector2.Zero();
  29070. var color = new BABYLON.Color4(0, 0, 0, 1);
  29071. _this.calculateError(v0, v1, p, n, uv, color);
  29072. var delTr = [];
  29073. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  29074. continue;
  29075. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  29076. continue;
  29077. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  29078. continue;
  29079. var uniqueArray = [];
  29080. delTr.forEach(function (deletedT) {
  29081. if (uniqueArray.indexOf(deletedT) === -1) {
  29082. deletedT.deletePending = true;
  29083. uniqueArray.push(deletedT);
  29084. }
  29085. });
  29086. if (uniqueArray.length % 2 != 0) {
  29087. continue;
  29088. }
  29089. v0.q = v1.q.add(v0.q);
  29090. v0.updatePosition(p);
  29091. var tStart = _this.references.length;
  29092. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  29093. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  29094. var tCount = _this.references.length - tStart;
  29095. if (tCount <= v0.triangleCount) {
  29096. if (tCount) {
  29097. for (var c = 0; c < tCount; c++) {
  29098. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  29099. }
  29100. }
  29101. }
  29102. else {
  29103. v0.triangleStart = tStart;
  29104. }
  29105. v0.triangleCount = tCount;
  29106. break;
  29107. }
  29108. }
  29109. };
  29110. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  29111. return (triangleCount - deletedTriangles <= targetCount);
  29112. });
  29113. }, 0);
  29114. };
  29115. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  29116. if (triangleCount - deletedTriangles <= targetCount)
  29117. loop.breakLoop();
  29118. else {
  29119. iterationFunction(loop.index, function () {
  29120. loop.executeNext();
  29121. });
  29122. }
  29123. }, function () {
  29124. setTimeout(function () {
  29125. //reconstruct this part of the mesh
  29126. _this.reconstructMesh(submeshIndex);
  29127. successCallback();
  29128. }, 0);
  29129. });
  29130. };
  29131. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  29132. var _this = this;
  29133. this.vertices = [];
  29134. this.triangles = [];
  29135. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29136. var indices = this._mesh.getIndices();
  29137. var submesh = this._mesh.subMeshes[submeshIndex];
  29138. var findInVertices = function (positionToSearch) {
  29139. if (optimizeMesh) {
  29140. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  29141. if (_this.vertices[ii].position.equals(positionToSearch)) {
  29142. return _this.vertices[ii];
  29143. }
  29144. }
  29145. }
  29146. return null;
  29147. };
  29148. var vertexReferences = [];
  29149. var vertexInit = function (i) {
  29150. var offset = i + submesh.verticesStart;
  29151. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29152. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29153. vertex.originalOffsets.push(offset);
  29154. if (vertex.id == _this.vertices.length) {
  29155. _this.vertices.push(vertex);
  29156. }
  29157. vertexReferences.push(vertex.id);
  29158. };
  29159. //var totalVertices = mesh.getTotalVertices();
  29160. var totalVertices = submesh.verticesCount;
  29161. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29162. var indicesInit = function (i) {
  29163. var offset = (submesh.indexStart / 3) + i;
  29164. var pos = (offset * 3);
  29165. var i0 = indices[pos + 0];
  29166. var i1 = indices[pos + 1];
  29167. var i2 = indices[pos + 2];
  29168. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29169. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29170. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29171. var triangle = new DecimationTriangle([v0, v1, v2]);
  29172. triangle.originalOffset = pos;
  29173. _this.triangles.push(triangle);
  29174. };
  29175. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  29176. _this.init(callback);
  29177. });
  29178. });
  29179. };
  29180. QuadraticErrorSimplification.prototype.init = function (callback) {
  29181. var _this = this;
  29182. var triangleInit1 = function (i) {
  29183. var t = _this.triangles[i];
  29184. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  29185. for (var j = 0; j < 3; j++) {
  29186. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  29187. }
  29188. };
  29189. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  29190. var triangleInit2 = function (i) {
  29191. var t = _this.triangles[i];
  29192. for (var j = 0; j < 3; ++j) {
  29193. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  29194. }
  29195. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29196. };
  29197. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  29198. _this.initialized = true;
  29199. callback();
  29200. });
  29201. });
  29202. };
  29203. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  29204. var newTriangles = [];
  29205. var i;
  29206. for (i = 0; i < this.vertices.length; ++i) {
  29207. this.vertices[i].triangleCount = 0;
  29208. }
  29209. var t;
  29210. var j;
  29211. for (i = 0; i < this.triangles.length; ++i) {
  29212. if (!this.triangles[i].deleted) {
  29213. t = this.triangles[i];
  29214. for (j = 0; j < 3; ++j) {
  29215. t.vertices[j].triangleCount = 1;
  29216. }
  29217. newTriangles.push(t);
  29218. }
  29219. }
  29220. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  29221. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  29222. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  29223. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  29224. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29225. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29226. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29227. var vertexCount = 0;
  29228. for (i = 0; i < this.vertices.length; ++i) {
  29229. var vertex = this.vertices[i];
  29230. vertex.id = vertexCount;
  29231. if (vertex.triangleCount) {
  29232. vertex.originalOffsets.forEach(function (originalOffset) {
  29233. newPositionData.push(vertex.position.x);
  29234. newPositionData.push(vertex.position.y);
  29235. newPositionData.push(vertex.position.z);
  29236. newNormalData.push(normalData[originalOffset * 3]);
  29237. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29238. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29239. if (uvs && uvs.length) {
  29240. newUVsData.push(uvs[(originalOffset * 2)]);
  29241. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29242. }
  29243. else if (colorsData && colorsData.length) {
  29244. newColorsData.push(colorsData[(originalOffset * 4)]);
  29245. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29246. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29247. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29248. }
  29249. ++vertexCount;
  29250. });
  29251. }
  29252. }
  29253. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29254. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29255. var submeshesArray = this._reconstructedMesh.subMeshes;
  29256. this._reconstructedMesh.subMeshes = [];
  29257. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29258. var originalIndices = this._mesh.getIndices();
  29259. for (i = 0; i < newTriangles.length; ++i) {
  29260. var t = newTriangles[i];
  29261. //now get the new referencing point for each vertex
  29262. [0, 1, 2].forEach(function (idx) {
  29263. var id = originalIndices[t.originalOffset + idx];
  29264. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29265. if (offset < 0)
  29266. offset = 0;
  29267. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29268. });
  29269. }
  29270. //overwriting the old vertex buffers and indices.
  29271. this._reconstructedMesh.setIndices(newIndicesArray);
  29272. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29273. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29274. if (newUVsData.length > 0)
  29275. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29276. if (newColorsData.length > 0)
  29277. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29278. //create submesh
  29279. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29280. if (submeshIndex > 0) {
  29281. this._reconstructedMesh.subMeshes = [];
  29282. submeshesArray.forEach(function (submesh) {
  29283. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29284. });
  29285. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29286. }
  29287. };
  29288. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29289. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29290. this._reconstructedMesh.material = this._mesh.material;
  29291. this._reconstructedMesh.parent = this._mesh.parent;
  29292. this._reconstructedMesh.isVisible = false;
  29293. };
  29294. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29295. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29296. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29297. if (t.deleted)
  29298. continue;
  29299. var s = this.references[vertex1.triangleStart + i].vertexId;
  29300. var v1 = t.vertices[(s + 1) % 3];
  29301. var v2 = t.vertices[(s + 2) % 3];
  29302. if ((v1 === vertex2 || v2 === vertex2)) {
  29303. deletedArray[i] = true;
  29304. delTr.push(t);
  29305. continue;
  29306. }
  29307. var d1 = v1.position.subtract(point);
  29308. d1 = d1.normalize();
  29309. var d2 = v2.position.subtract(point);
  29310. d2 = d2.normalize();
  29311. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29312. return true;
  29313. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29314. deletedArray[i] = false;
  29315. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29316. return true;
  29317. }
  29318. return false;
  29319. };
  29320. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29321. var newDeleted = deletedTriangles;
  29322. for (var i = 0; i < vertex.triangleCount; ++i) {
  29323. var ref = this.references[vertex.triangleStart + i];
  29324. var t = this.triangles[ref.triangleId];
  29325. if (t.deleted)
  29326. continue;
  29327. if (deletedArray[i] && t.deletePending) {
  29328. t.deleted = true;
  29329. newDeleted++;
  29330. continue;
  29331. }
  29332. t.vertices[ref.vertexId] = origVertex;
  29333. t.isDirty = true;
  29334. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29335. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29336. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29337. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29338. this.references.push(ref);
  29339. }
  29340. return newDeleted;
  29341. };
  29342. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29343. for (var i = 0; i < this.vertices.length; ++i) {
  29344. var vCount = [];
  29345. var vId = [];
  29346. var v = this.vertices[i];
  29347. var j;
  29348. for (j = 0; j < v.triangleCount; ++j) {
  29349. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29350. for (var ii = 0; ii < 3; ii++) {
  29351. var ofs = 0;
  29352. var vv = triangle.vertices[ii];
  29353. while (ofs < vCount.length) {
  29354. if (vId[ofs] === vv.id)
  29355. break;
  29356. ++ofs;
  29357. }
  29358. if (ofs === vCount.length) {
  29359. vCount.push(1);
  29360. vId.push(vv.id);
  29361. }
  29362. else {
  29363. vCount[ofs]++;
  29364. }
  29365. }
  29366. }
  29367. for (j = 0; j < vCount.length; ++j) {
  29368. if (vCount[j] === 1) {
  29369. this.vertices[vId[j]].isBorder = true;
  29370. }
  29371. else {
  29372. this.vertices[vId[j]].isBorder = false;
  29373. }
  29374. }
  29375. }
  29376. };
  29377. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29378. if (identifyBorders === void 0) { identifyBorders = false; }
  29379. var i;
  29380. if (!identifyBorders) {
  29381. var newTrianglesVector = [];
  29382. for (i = 0; i < this.triangles.length; ++i) {
  29383. if (!this.triangles[i].deleted) {
  29384. newTrianglesVector.push(this.triangles[i]);
  29385. }
  29386. }
  29387. this.triangles = newTrianglesVector;
  29388. }
  29389. for (i = 0; i < this.vertices.length; ++i) {
  29390. this.vertices[i].triangleCount = 0;
  29391. this.vertices[i].triangleStart = 0;
  29392. }
  29393. var t;
  29394. var j;
  29395. var v;
  29396. for (i = 0; i < this.triangles.length; ++i) {
  29397. t = this.triangles[i];
  29398. for (j = 0; j < 3; ++j) {
  29399. v = t.vertices[j];
  29400. v.triangleCount++;
  29401. }
  29402. }
  29403. var tStart = 0;
  29404. for (i = 0; i < this.vertices.length; ++i) {
  29405. this.vertices[i].triangleStart = tStart;
  29406. tStart += this.vertices[i].triangleCount;
  29407. this.vertices[i].triangleCount = 0;
  29408. }
  29409. var newReferences = new Array(this.triangles.length * 3);
  29410. for (i = 0; i < this.triangles.length; ++i) {
  29411. t = this.triangles[i];
  29412. for (j = 0; j < 3; ++j) {
  29413. v = t.vertices[j];
  29414. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29415. v.triangleCount++;
  29416. }
  29417. }
  29418. this.references = newReferences;
  29419. if (identifyBorders) {
  29420. this.identifyBorder();
  29421. }
  29422. };
  29423. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29424. var x = point.x;
  29425. var y = point.y;
  29426. var z = point.z;
  29427. 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];
  29428. };
  29429. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29430. var q = vertex1.q.add(vertex2.q);
  29431. var border = vertex1.isBorder && vertex2.isBorder;
  29432. var error = 0;
  29433. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29434. if (qDet !== 0 && !border) {
  29435. if (!pointResult) {
  29436. pointResult = BABYLON.Vector3.Zero();
  29437. }
  29438. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29439. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29440. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29441. error = this.vertexError(q, pointResult);
  29442. }
  29443. else {
  29444. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29445. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29446. var error1 = this.vertexError(q, vertex1.position);
  29447. var error2 = this.vertexError(q, vertex2.position);
  29448. var error3 = this.vertexError(q, p3);
  29449. error = Math.min(error1, error2, error3);
  29450. if (error === error1) {
  29451. if (pointResult) {
  29452. pointResult.copyFrom(vertex1.position);
  29453. }
  29454. }
  29455. else if (error === error2) {
  29456. if (pointResult) {
  29457. pointResult.copyFrom(vertex2.position);
  29458. }
  29459. }
  29460. else {
  29461. if (pointResult) {
  29462. pointResult.copyFrom(p3);
  29463. }
  29464. }
  29465. }
  29466. return error;
  29467. };
  29468. return QuadraticErrorSimplification;
  29469. })();
  29470. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29471. })(BABYLON || (BABYLON = {}));
  29472. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  29473. (function (BABYLON) {
  29474. var Analyser = (function () {
  29475. function Analyser(scene) {
  29476. this.SMOOTHING = 0.75;
  29477. this.FFT_SIZE = 512;
  29478. this.BARGRAPHAMPLITUDE = 256;
  29479. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  29480. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  29481. this._scene = scene;
  29482. this._audioEngine = BABYLON.Engine.audioEngine;
  29483. if (this._audioEngine.canUseWebAudio) {
  29484. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  29485. this._webAudioAnalyser.minDecibels = -140;
  29486. this._webAudioAnalyser.maxDecibels = 0;
  29487. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29488. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29489. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  29490. }
  29491. }
  29492. Analyser.prototype.getFrequencyBinCount = function () {
  29493. if (this._audioEngine.canUseWebAudio) {
  29494. return this._webAudioAnalyser.frequencyBinCount;
  29495. }
  29496. else {
  29497. return 0;
  29498. }
  29499. };
  29500. Analyser.prototype.getByteFrequencyData = function () {
  29501. if (this._audioEngine.canUseWebAudio) {
  29502. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29503. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29504. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  29505. }
  29506. return this._byteFreqs;
  29507. };
  29508. Analyser.prototype.getByteTimeDomainData = function () {
  29509. if (this._audioEngine.canUseWebAudio) {
  29510. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29511. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29512. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  29513. }
  29514. return this._byteTime;
  29515. };
  29516. Analyser.prototype.getFloatFrequencyData = function () {
  29517. if (this._audioEngine.canUseWebAudio) {
  29518. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29519. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29520. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  29521. }
  29522. return this._floatFreqs;
  29523. };
  29524. Analyser.prototype.drawDebugCanvas = function () {
  29525. var _this = this;
  29526. if (this._audioEngine.canUseWebAudio) {
  29527. if (!this._debugCanvas) {
  29528. this._debugCanvas = document.createElement("canvas");
  29529. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  29530. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  29531. this._debugCanvas.style.position = "absolute";
  29532. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  29533. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  29534. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  29535. document.body.appendChild(this._debugCanvas);
  29536. this._registerFunc = function () {
  29537. _this.drawDebugCanvas();
  29538. };
  29539. this._scene.registerBeforeRender(this._registerFunc);
  29540. }
  29541. if (this._registerFunc) {
  29542. var workingArray = this.getByteFrequencyData();
  29543. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  29544. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  29545. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  29546. var value = workingArray[i];
  29547. var percent = value / this.BARGRAPHAMPLITUDE;
  29548. var height = this.DEBUGCANVASSIZE.height * percent;
  29549. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  29550. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  29551. var hue = i / this.getFrequencyBinCount() * 360;
  29552. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  29553. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  29554. }
  29555. }
  29556. }
  29557. };
  29558. Analyser.prototype.stopDebugCanvas = function () {
  29559. if (this._debugCanvas) {
  29560. this._scene.unregisterBeforeRender(this._registerFunc);
  29561. this._registerFunc = null;
  29562. document.body.removeChild(this._debugCanvas);
  29563. this._debugCanvas = null;
  29564. this._debugCanvasContext = null;
  29565. }
  29566. };
  29567. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  29568. if (this._audioEngine.canUseWebAudio) {
  29569. inputAudioNode.connect(this._webAudioAnalyser);
  29570. this._webAudioAnalyser.connect(outputAudioNode);
  29571. }
  29572. };
  29573. Analyser.prototype.dispose = function () {
  29574. if (this._audioEngine.canUseWebAudio) {
  29575. this._webAudioAnalyser.disconnect();
  29576. }
  29577. };
  29578. return Analyser;
  29579. })();
  29580. BABYLON.Analyser = Analyser;
  29581. })(BABYLON || (BABYLON = {}));
  29582. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  29583. (function (BABYLON) {
  29584. var DepthRenderer = (function () {
  29585. function DepthRenderer(scene, type) {
  29586. var _this = this;
  29587. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  29588. this._viewMatrix = BABYLON.Matrix.Zero();
  29589. this._projectionMatrix = BABYLON.Matrix.Zero();
  29590. this._transformMatrix = BABYLON.Matrix.Zero();
  29591. this._worldViewProjection = BABYLON.Matrix.Zero();
  29592. this._scene = scene;
  29593. var engine = scene.getEngine();
  29594. // Render target
  29595. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  29596. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29597. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29598. this._depthMap.refreshRate = 1;
  29599. this._depthMap.renderParticles = false;
  29600. this._depthMap.renderList = null;
  29601. // set default depth value to 1.0 (far away)
  29602. this._depthMap.onClear = function (engine) {
  29603. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  29604. };
  29605. // Custom render function
  29606. var renderSubMesh = function (subMesh) {
  29607. var mesh = subMesh.getRenderingMesh();
  29608. var scene = _this._scene;
  29609. var engine = scene.getEngine();
  29610. // Culling
  29611. engine.setState(subMesh.getMaterial().backFaceCulling);
  29612. // Managing instances
  29613. var batch = mesh._getInstancesRenderList(subMesh._id);
  29614. if (batch.mustReturn) {
  29615. return;
  29616. }
  29617. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29618. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29619. engine.enableEffect(_this._effect);
  29620. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  29621. var material = subMesh.getMaterial();
  29622. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29623. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  29624. // Alpha test
  29625. if (material && material.needAlphaTesting()) {
  29626. var alphaTexture = material.getAlphaTestTexture();
  29627. _this._effect.setTexture("diffuseSampler", alphaTexture);
  29628. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29629. }
  29630. // Bones
  29631. if (mesh.useBones) {
  29632. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29633. }
  29634. // Draw
  29635. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  29636. }
  29637. };
  29638. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  29639. var index;
  29640. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29641. renderSubMesh(opaqueSubMeshes.data[index]);
  29642. }
  29643. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29644. renderSubMesh(alphaTestSubMeshes.data[index]);
  29645. }
  29646. };
  29647. }
  29648. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  29649. var defines = [];
  29650. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29651. var mesh = subMesh.getMesh();
  29652. var scene = mesh.getScene();
  29653. var material = subMesh.getMaterial();
  29654. // Alpha test
  29655. if (material && material.needAlphaTesting()) {
  29656. defines.push("#define ALPHATEST");
  29657. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29658. attribs.push(BABYLON.VertexBuffer.UVKind);
  29659. defines.push("#define UV1");
  29660. }
  29661. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29662. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29663. defines.push("#define UV2");
  29664. }
  29665. }
  29666. // Bones
  29667. if (mesh.useBones) {
  29668. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29669. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29670. defines.push("#define BONES");
  29671. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29672. }
  29673. // Instances
  29674. if (useInstances) {
  29675. defines.push("#define INSTANCES");
  29676. attribs.push("world0");
  29677. attribs.push("world1");
  29678. attribs.push("world2");
  29679. attribs.push("world3");
  29680. }
  29681. // Get correct effect
  29682. var join = defines.join("\n");
  29683. if (this._cachedDefines !== join) {
  29684. this._cachedDefines = join;
  29685. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  29686. }
  29687. return this._effect.isReady();
  29688. };
  29689. DepthRenderer.prototype.getDepthMap = function () {
  29690. return this._depthMap;
  29691. };
  29692. // Methods
  29693. DepthRenderer.prototype.dispose = function () {
  29694. this._depthMap.dispose();
  29695. };
  29696. return DepthRenderer;
  29697. })();
  29698. BABYLON.DepthRenderer = DepthRenderer;
  29699. })(BABYLON || (BABYLON = {}));
  29700. //# sourceMappingURL=babylon.depthRenderer.js.map
  29701. var BABYLON;
  29702. (function (BABYLON) {
  29703. var SSAORenderingPipeline = (function (_super) {
  29704. __extends(SSAORenderingPipeline, _super);
  29705. /**
  29706. * @constructor
  29707. * @param {string} name - The rendering pipeline name
  29708. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29709. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  29710. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29711. */
  29712. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  29713. var _this = this;
  29714. _super.call(this, scene.getEngine(), name);
  29715. // Members
  29716. /**
  29717. * The PassPostProcess id in the pipeline that contains the original scene color
  29718. * @type {string}
  29719. */
  29720. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  29721. /**
  29722. * The SSAO PostProcess id in the pipeline
  29723. * @type {string}
  29724. */
  29725. this.SSAORenderEffect = "SSAORenderEffect";
  29726. /**
  29727. * The horizontal blur PostProcess id in the pipeline
  29728. * @type {string}
  29729. */
  29730. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  29731. /**
  29732. * The vertical blur PostProcess id in the pipeline
  29733. * @type {string}
  29734. */
  29735. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  29736. /**
  29737. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  29738. * @type {string}
  29739. */
  29740. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  29741. /**
  29742. * The output strength of the SSAO post-process. Default value is 1.0.
  29743. * @type {number}
  29744. */
  29745. this.totalStrength = 1.0;
  29746. /**
  29747. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  29748. * @type {number}
  29749. */
  29750. this.radius = 0.0002;
  29751. /**
  29752. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  29753. * Must not be equal to fallOff and superior to fallOff.
  29754. * Default value is 0.0075
  29755. * @type {number}
  29756. */
  29757. this.area = 0.0075;
  29758. /**
  29759. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  29760. * Must not be equal to area and inferior to area.
  29761. * Default value is 0.0002
  29762. * @type {number}
  29763. */
  29764. this.fallOff = 0.0002;
  29765. this._firstUpdate = true;
  29766. this._scene = scene;
  29767. // Set up assets
  29768. this._createRandomTexture();
  29769. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29770. var ssaoRatio = ratio.ssaoRatio || ratio;
  29771. var combineRatio = ratio.combineRatio || ratio;
  29772. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29773. this._createSSAOPostProcess(ssaoRatio);
  29774. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29775. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29776. this._createSSAOCombinePostProcess(combineRatio);
  29777. // Set up pipeline
  29778. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  29779. return _this._originalColorPostProcess;
  29780. }, true));
  29781. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  29782. return _this._ssaoPostProcess;
  29783. }, true));
  29784. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  29785. return _this._blurHPostProcess;
  29786. }, true));
  29787. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  29788. return _this._blurVPostProcess;
  29789. }, true));
  29790. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  29791. return _this._ssaoCombinePostProcess;
  29792. }, true));
  29793. // Finish
  29794. scene.postProcessRenderPipelineManager.addPipeline(this);
  29795. if (cameras)
  29796. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29797. }
  29798. // Public Methods
  29799. /**
  29800. * Returns the horizontal blur PostProcess
  29801. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  29802. */
  29803. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  29804. return this._blurHPostProcess;
  29805. };
  29806. /**
  29807. * Returns the vertical blur PostProcess
  29808. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  29809. */
  29810. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  29811. return this._blurVPostProcess;
  29812. };
  29813. /**
  29814. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  29815. */
  29816. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29817. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29818. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29819. this._originalColorPostProcess = undefined;
  29820. this._ssaoPostProcess = undefined;
  29821. this._blurHPostProcess = undefined;
  29822. this._blurVPostProcess = undefined;
  29823. this._ssaoCombinePostProcess = undefined;
  29824. this._randomTexture.dispose();
  29825. if (disableDepthRender)
  29826. this._scene.disableDepthRenderer();
  29827. };
  29828. // Private Methods
  29829. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  29830. var _this = this;
  29831. var sampleSphere = [
  29832. 0.5381,
  29833. 0.1856,
  29834. -0.4319,
  29835. 0.1379,
  29836. 0.2486,
  29837. 0.4430,
  29838. 0.3371,
  29839. 0.5679,
  29840. -0.0057,
  29841. -0.6999,
  29842. -0.0451,
  29843. -0.0019,
  29844. 0.0689,
  29845. -0.1598,
  29846. -0.8547,
  29847. 0.0560,
  29848. 0.0069,
  29849. -0.1843,
  29850. -0.0146,
  29851. 0.1402,
  29852. 0.0762,
  29853. 0.0100,
  29854. -0.1924,
  29855. -0.0344,
  29856. -0.3577,
  29857. -0.5301,
  29858. -0.4358,
  29859. -0.3169,
  29860. 0.1063,
  29861. 0.0158,
  29862. 0.0103,
  29863. -0.5869,
  29864. 0.0046,
  29865. -0.0897,
  29866. -0.4940,
  29867. 0.3287,
  29868. 0.7119,
  29869. -0.0154,
  29870. -0.0918,
  29871. -0.0533,
  29872. 0.0596,
  29873. -0.5411,
  29874. 0.0352,
  29875. -0.0631,
  29876. 0.5460,
  29877. -0.4776,
  29878. 0.2847,
  29879. -0.0271
  29880. ];
  29881. var samplesFactor = 1.0 / 16.0;
  29882. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "area", "fallOff"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29883. this._ssaoPostProcess.onApply = function (effect) {
  29884. if (_this._firstUpdate) {
  29885. effect.setArray3("sampleSphere", sampleSphere);
  29886. effect.setFloat("samplesFactor", samplesFactor);
  29887. effect.setFloat("randTextureTiles", 4.0 / ratio);
  29888. _this._firstUpdate = false;
  29889. }
  29890. effect.setFloat("totalStrength", _this.totalStrength);
  29891. effect.setFloat("radius", _this.radius);
  29892. effect.setFloat("area", _this.area);
  29893. effect.setFloat("fallOff", _this.fallOff);
  29894. effect.setTexture("textureSampler", _this._depthTexture);
  29895. effect.setTexture("randomSampler", _this._randomTexture);
  29896. };
  29897. };
  29898. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  29899. var _this = this;
  29900. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29901. this._ssaoCombinePostProcess.onApply = function (effect) {
  29902. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  29903. };
  29904. };
  29905. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  29906. var size = 512;
  29907. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29908. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29909. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29910. var context = this._randomTexture.getContext();
  29911. var rand = function (min, max) {
  29912. return Math.random() * (max - min) + min;
  29913. };
  29914. for (var x = 0; x < size; x++) {
  29915. for (var y = 0; y < size; y++) {
  29916. var randVector = BABYLON.Vector3.Zero();
  29917. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  29918. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  29919. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  29920. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  29921. context.fillRect(x, y, 1, 1);
  29922. }
  29923. }
  29924. this._randomTexture.update(false);
  29925. };
  29926. return SSAORenderingPipeline;
  29927. })(BABYLON.PostProcessRenderPipeline);
  29928. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  29929. })(BABYLON || (BABYLON = {}));
  29930. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  29931. var BABYLON;
  29932. (function (BABYLON) {
  29933. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  29934. var VolumetricLightScatteringPostProcess = (function (_super) {
  29935. __extends(VolumetricLightScatteringPostProcess, _super);
  29936. /**
  29937. * @constructor
  29938. * @param {string} name - The post-process name
  29939. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  29940. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  29941. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  29942. * @param {number} samples - The post-process quality, default 100
  29943. * @param {number} samplingMode - The post-process filtering mode
  29944. * @param {BABYLON.Engine} engine - The babylon engine
  29945. * @param {boolean} reusable - If the post-process is reusable
  29946. */
  29947. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  29948. var _this = this;
  29949. if (samples === void 0) { samples = 100; }
  29950. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  29951. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  29952. this._screenCoordinates = BABYLON.Vector2.Zero();
  29953. /**
  29954. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  29955. * @type {boolean}
  29956. */
  29957. this.useCustomMeshPosition = false;
  29958. /**
  29959. * If the post-process should inverse the light scattering direction
  29960. * @type {boolean}
  29961. */
  29962. this.invert = true;
  29963. /**
  29964. * Array containing the excluded meshes not rendered in the internal pass
  29965. */
  29966. this.excludedMeshes = new Array();
  29967. this.exposure = 0.3;
  29968. this.decay = 0.96815;
  29969. this.weight = 0.58767;
  29970. this.density = 0.926;
  29971. var scene = camera.getScene();
  29972. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  29973. // Configure mesh
  29974. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  29975. // Configure
  29976. this._createPass(scene, ratio.passRatio || ratio);
  29977. this.onApply = function (effect) {
  29978. _this._updateMeshScreenCoordinates(scene);
  29979. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  29980. effect.setFloat("exposure", _this.exposure);
  29981. effect.setFloat("decay", _this.decay);
  29982. effect.setFloat("weight", _this.weight);
  29983. effect.setFloat("density", _this.density);
  29984. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  29985. };
  29986. }
  29987. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  29988. var mesh = subMesh.getMesh();
  29989. var defines = [];
  29990. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29991. var material = subMesh.getMaterial();
  29992. var needUV = false;
  29993. // Render this.mesh as default
  29994. if (mesh === this.mesh) {
  29995. defines.push("#define BASIC_RENDER");
  29996. defines.push("#define NEED_UV");
  29997. needUV = true;
  29998. }
  29999. // Alpha test
  30000. if (material) {
  30001. if (material.needAlphaTesting() || mesh === this.mesh)
  30002. defines.push("#define ALPHATEST");
  30003. if (material.opacityTexture !== undefined) {
  30004. defines.push("#define OPACITY");
  30005. if (material.opacityTexture.getAlphaFromRGB)
  30006. defines.push("#define OPACITYRGB");
  30007. if (!needUV)
  30008. defines.push("#define NEED_UV");
  30009. }
  30010. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30011. attribs.push(BABYLON.VertexBuffer.UVKind);
  30012. defines.push("#define UV1");
  30013. }
  30014. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30015. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30016. defines.push("#define UV2");
  30017. }
  30018. }
  30019. // Bones
  30020. if (mesh.useBones) {
  30021. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30022. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30023. defines.push("#define BONES");
  30024. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30025. }
  30026. // Instances
  30027. if (useInstances) {
  30028. defines.push("#define INSTANCES");
  30029. attribs.push("world0");
  30030. attribs.push("world1");
  30031. attribs.push("world2");
  30032. attribs.push("world3");
  30033. }
  30034. // Get correct effect
  30035. var join = defines.join("\n");
  30036. if (this._cachedDefines !== join) {
  30037. this._cachedDefines = join;
  30038. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  30039. }
  30040. return this._volumetricLightScatteringPass.isReady();
  30041. };
  30042. /**
  30043. * Sets the new light position for light scattering effect
  30044. * @param {BABYLON.Vector3} The new custom light position
  30045. */
  30046. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  30047. this._customMeshPosition = position;
  30048. };
  30049. /**
  30050. * Returns the light position for light scattering effect
  30051. * @return {BABYLON.Vector3} The custom light position
  30052. */
  30053. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  30054. return this._customMeshPosition;
  30055. };
  30056. /**
  30057. * Disposes the internal assets and detaches the post-process from the camera
  30058. */
  30059. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  30060. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  30061. if (rttIndex !== -1) {
  30062. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  30063. }
  30064. this._volumetricLightScatteringRTT.dispose();
  30065. _super.prototype.dispose.call(this, camera);
  30066. };
  30067. /**
  30068. * Returns the render target texture used by the post-process
  30069. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  30070. */
  30071. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  30072. return this._volumetricLightScatteringRTT;
  30073. };
  30074. // Private methods
  30075. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  30076. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  30077. return true;
  30078. }
  30079. return false;
  30080. };
  30081. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  30082. var _this = this;
  30083. var engine = scene.getEngine();
  30084. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  30085. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30086. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30087. this._volumetricLightScatteringRTT.renderList = null;
  30088. this._volumetricLightScatteringRTT.renderParticles = false;
  30089. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  30090. // Custom render function for submeshes
  30091. var renderSubMesh = function (subMesh) {
  30092. var mesh = subMesh.getRenderingMesh();
  30093. if (_this._meshExcluded(mesh)) {
  30094. return;
  30095. }
  30096. var scene = mesh.getScene();
  30097. var engine = scene.getEngine();
  30098. // Culling
  30099. engine.setState(subMesh.getMaterial().backFaceCulling);
  30100. // Managing instances
  30101. var batch = mesh._getInstancesRenderList(subMesh._id);
  30102. if (batch.mustReturn) {
  30103. return;
  30104. }
  30105. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  30106. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  30107. engine.enableEffect(_this._volumetricLightScatteringPass);
  30108. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  30109. var material = subMesh.getMaterial();
  30110. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  30111. // Alpha test
  30112. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  30113. var alphaTexture = material.getAlphaTestTexture();
  30114. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  30115. if (alphaTexture) {
  30116. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30117. }
  30118. if (material.opacityTexture !== undefined) {
  30119. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  30120. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  30121. }
  30122. }
  30123. // Bones
  30124. if (mesh.useBones) {
  30125. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30126. }
  30127. // Draw
  30128. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  30129. }
  30130. };
  30131. // Render target texture callbacks
  30132. var savedSceneClearColor;
  30133. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  30134. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  30135. savedSceneClearColor = scene.clearColor;
  30136. scene.clearColor = sceneClearColor;
  30137. };
  30138. this._volumetricLightScatteringRTT.onAfterRender = function () {
  30139. scene.clearColor = savedSceneClearColor;
  30140. };
  30141. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  30142. var engine = scene.getEngine();
  30143. var index;
  30144. for (index = 0; index < opaqueSubMeshes.length; index++) {
  30145. renderSubMesh(opaqueSubMeshes.data[index]);
  30146. }
  30147. engine.setAlphaTesting(true);
  30148. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  30149. renderSubMesh(alphaTestSubMeshes.data[index]);
  30150. }
  30151. engine.setAlphaTesting(false);
  30152. if (transparentSubMeshes.length) {
  30153. for (index = 0; index < transparentSubMeshes.length; index++) {
  30154. var submesh = transparentSubMeshes.data[index];
  30155. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  30156. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  30157. }
  30158. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  30159. sortedArray.sort(function (a, b) {
  30160. // Alpha index first
  30161. if (a._alphaIndex > b._alphaIndex) {
  30162. return 1;
  30163. }
  30164. if (a._alphaIndex < b._alphaIndex) {
  30165. return -1;
  30166. }
  30167. // Then distance to camera
  30168. if (a._distanceToCamera < b._distanceToCamera) {
  30169. return 1;
  30170. }
  30171. if (a._distanceToCamera > b._distanceToCamera) {
  30172. return -1;
  30173. }
  30174. return 0;
  30175. });
  30176. // Render sub meshes
  30177. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  30178. for (index = 0; index < sortedArray.length; index++) {
  30179. renderSubMesh(sortedArray[index]);
  30180. }
  30181. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30182. }
  30183. };
  30184. };
  30185. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  30186. var transform = scene.getTransformMatrix();
  30187. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  30188. this._screenCoordinates.x = pos.x / this._viewPort.width;
  30189. this._screenCoordinates.y = pos.y / this._viewPort.height;
  30190. if (this.invert)
  30191. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  30192. };
  30193. // Static methods
  30194. /**
  30195. * Creates a default mesh for the Volumeric Light Scattering post-process
  30196. * @param {string} The mesh name
  30197. * @param {BABYLON.Scene} The scene where to create the mesh
  30198. * @return {BABYLON.Mesh} the default mesh
  30199. */
  30200. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  30201. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  30202. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  30203. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  30204. return mesh;
  30205. };
  30206. return VolumetricLightScatteringPostProcess;
  30207. })(BABYLON.PostProcess);
  30208. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  30209. })(BABYLON || (BABYLON = {}));
  30210. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  30211. var BABYLON;
  30212. (function (BABYLON) {
  30213. var LensRenderingPipeline = (function (_super) {
  30214. __extends(LensRenderingPipeline, _super);
  30215. /**
  30216. * @constructor
  30217. *
  30218. * Effect parameters are as follow:
  30219. * {
  30220. * chromatic_aberration: number; // from 0 to x (1 for realism)
  30221. * edge_blur: number; // from 0 to x (1 for realism)
  30222. * distortion: number; // from 0 to x (1 for realism)
  30223. * grain_amount: number; // from 0 to 1
  30224. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  30225. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  30226. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  30227. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  30228. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  30229. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  30230. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  30231. * }
  30232. * Note: if an effect parameter is unset, effect is disabled
  30233. *
  30234. * @param {string} name - The rendering pipeline name
  30235. * @param {object} parameters - An object containing all parameters (see above)
  30236. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  30237. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  30238. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  30239. */
  30240. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  30241. var _this = this;
  30242. if (ratio === void 0) { ratio = 1.0; }
  30243. _super.call(this, scene.getEngine(), name);
  30244. // Lens effects can be of the following:
  30245. // - chromatic aberration (slight shift of RGB colors)
  30246. // - blur on the edge of the lens
  30247. // - lens distortion
  30248. // - depth-of-field blur & highlights enhancing
  30249. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  30250. // - grain effect (noise or custom texture)
  30251. // Two additional texture samplers are needed:
  30252. // - depth map (for depth-of-field)
  30253. // - grain texture
  30254. /**
  30255. * The chromatic aberration PostProcess id in the pipeline
  30256. * @type {string}
  30257. */
  30258. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  30259. /**
  30260. * The highlights enhancing PostProcess id in the pipeline
  30261. * @type {string}
  30262. */
  30263. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  30264. /**
  30265. * The depth-of-field PostProcess id in the pipeline
  30266. * @type {string}
  30267. */
  30268. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  30269. this._scene = scene;
  30270. // Fetch texture samplers
  30271. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  30272. if (parameters.grain_texture) {
  30273. this._grainTexture = parameters.grain_texture;
  30274. }
  30275. else {
  30276. this._createGrainTexture();
  30277. }
  30278. // save parameters
  30279. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  30280. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  30281. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  30282. this._distortion = parameters.distortion ? parameters.distortion : 0;
  30283. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  30284. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  30285. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  30286. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  30287. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  30288. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  30289. // Create effects
  30290. this._createChromaticAberrationPostProcess(ratio);
  30291. this._createHighlightsPostProcess(ratio);
  30292. this._createDepthOfFieldPostProcess(ratio);
  30293. // Set up pipeline
  30294. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  30295. return _this._chromaticAberrationPostProcess;
  30296. }, true));
  30297. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () {
  30298. return _this._highlightsPostProcess;
  30299. }, true));
  30300. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  30301. return _this._depthOfFieldPostProcess;
  30302. }, true));
  30303. if (this._highlightsGain == -1) {
  30304. this._disableEffect(this.HighlightsEnhancingEffect, null);
  30305. }
  30306. // Finish
  30307. scene.postProcessRenderPipelineManager.addPipeline(this);
  30308. if (cameras) {
  30309. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  30310. }
  30311. }
  30312. // public methods (self explanatory)
  30313. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  30314. this._edgeBlur = amount;
  30315. };
  30316. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  30317. this._edgeBlur = 0;
  30318. };
  30319. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  30320. this._grainAmount = amount;
  30321. };
  30322. LensRenderingPipeline.prototype.disableGrain = function () {
  30323. this._grainAmount = 0;
  30324. };
  30325. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  30326. this._chromaticAberration = amount;
  30327. };
  30328. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  30329. this._chromaticAberration = 0;
  30330. };
  30331. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  30332. this._distortion = amount;
  30333. };
  30334. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  30335. this._distortion = 0;
  30336. };
  30337. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  30338. this._dofDepth = amount;
  30339. };
  30340. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  30341. this._dofDepth = -1;
  30342. };
  30343. LensRenderingPipeline.prototype.setAperture = function (amount) {
  30344. this._dofAperture = amount;
  30345. };
  30346. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  30347. this._dofPentagon = true;
  30348. };
  30349. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  30350. this._dofPentagon = false;
  30351. };
  30352. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  30353. this._blurNoise = true;
  30354. };
  30355. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  30356. this._blurNoise = false;
  30357. };
  30358. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  30359. this._highlightsGain = amount;
  30360. };
  30361. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  30362. if (this._highlightsGain == -1) {
  30363. this._highlightsGain = 1.0;
  30364. }
  30365. this._highlightsThreshold = amount;
  30366. };
  30367. LensRenderingPipeline.prototype.disableHighlights = function () {
  30368. this._highlightsGain = -1;
  30369. };
  30370. /**
  30371. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  30372. */
  30373. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  30374. if (disableDepthRender === void 0) { disableDepthRender = false; }
  30375. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  30376. this._chromaticAberrationPostProcess = undefined;
  30377. this._highlightsPostProcess = undefined;
  30378. this._depthOfFieldPostProcess = undefined;
  30379. this._grainTexture.dispose();
  30380. if (disableDepthRender)
  30381. this._scene.disableDepthRenderer();
  30382. };
  30383. // colors shifting and distortion
  30384. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  30385. var _this = this;
  30386. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30387. this._chromaticAberrationPostProcess.onApply = function (effect) {
  30388. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  30389. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30390. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30391. };
  30392. };
  30393. // highlights enhancing
  30394. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  30395. var _this = this;
  30396. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30397. this._highlightsPostProcess.onApply = function (effect) {
  30398. effect.setFloat('gain', _this._highlightsGain);
  30399. effect.setFloat('threshold', _this._highlightsThreshold);
  30400. effect.setBool('pentagon', _this._dofPentagon);
  30401. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  30402. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30403. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30404. };
  30405. };
  30406. // colors shifting and distortion
  30407. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  30408. var _this = this;
  30409. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  30410. "focus_depth",
  30411. "aperture",
  30412. "pentagon",
  30413. "maxZ",
  30414. "edge_blur",
  30415. "chromatic_aberration",
  30416. "distortion",
  30417. "blur_noise",
  30418. "grain_amount",
  30419. "screen_width",
  30420. "screen_height",
  30421. "highlights"
  30422. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30423. this._depthOfFieldPostProcess.onApply = function (effect) {
  30424. effect.setBool('blur_noise', _this._blurNoise);
  30425. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  30426. effect.setFloat('grain_amount', _this._grainAmount);
  30427. effect.setTexture("depthSampler", _this._depthTexture);
  30428. effect.setTexture("grainSampler", _this._grainTexture);
  30429. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  30430. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  30431. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30432. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30433. effect.setFloat('distortion', _this._distortion);
  30434. effect.setFloat('focus_depth', _this._dofDepth);
  30435. effect.setFloat('aperture', _this._dofAperture);
  30436. effect.setFloat('edge_blur', _this._edgeBlur);
  30437. effect.setBool('highlights', (_this._highlightsGain != -1));
  30438. };
  30439. };
  30440. // creates a black and white random noise texture, 512x512
  30441. LensRenderingPipeline.prototype._createGrainTexture = function () {
  30442. var size = 512;
  30443. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  30444. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30445. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30446. var context = this._grainTexture.getContext();
  30447. var rand = function (min, max) {
  30448. return Math.random() * (max - min) + min;
  30449. };
  30450. var value;
  30451. for (var x = 0; x < size; x++) {
  30452. for (var y = 0; y < size; y++) {
  30453. value = Math.floor(rand(0.42, 0.58) * 255);
  30454. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  30455. context.fillRect(x, y, 1, 1);
  30456. }
  30457. }
  30458. this._grainTexture.update(false);
  30459. };
  30460. return LensRenderingPipeline;
  30461. })(BABYLON.PostProcessRenderPipeline);
  30462. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  30463. })(BABYLON || (BABYLON = {}));
  30464. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  30465. // This post-process allows the modification of rendered colors by using
  30466. // a 'look-up table' (LUT). This effect is also called Color Grading.
  30467. //
  30468. // The object needs to be provided an url to a texture containing the color
  30469. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  30470. // Use an image editing software to tweak the LUT to match your needs.
  30471. //
  30472. // For an example of a color LUT, see here:
  30473. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  30474. // For explanations on color grading, see here:
  30475. // http://udn.epicgames.com/Three/ColorGrading.html
  30476. //
  30477. var BABYLON;
  30478. (function (BABYLON) {
  30479. var ColorCorrectionPostProcess = (function (_super) {
  30480. __extends(ColorCorrectionPostProcess, _super);
  30481. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  30482. var _this = this;
  30483. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  30484. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  30485. this._colorTableTexture.anisotropicFilteringLevel = 1;
  30486. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30487. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30488. this.onApply = function (effect) {
  30489. effect.setTexture("colorTable", _this._colorTableTexture);
  30490. };
  30491. }
  30492. return ColorCorrectionPostProcess;
  30493. })(BABYLON.PostProcess);
  30494. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  30495. })(BABYLON || (BABYLON = {}));
  30496. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.mapvar BABYLON;
  30497. (function (BABYLON) {
  30498. var SmartCollection = (function () {
  30499. function SmartCollection(capacity) {
  30500. if (capacity === void 0) { capacity = 10; }
  30501. this.count = 0;
  30502. this._initialCapacity = capacity;
  30503. this.items = {};
  30504. this._keys = new Array(this._initialCapacity);
  30505. }
  30506. SmartCollection.prototype.add = function (key, item) {
  30507. if (this.items[key] != undefined) {
  30508. return -1;
  30509. }
  30510. this.items[key] = item;
  30511. //literal keys are always strings, but we keep source type of key in _keys array
  30512. this._keys[this.count++] = key;
  30513. if (this.count > this._keys.length) {
  30514. this._keys.length *= 2;
  30515. }
  30516. return this.count;
  30517. };
  30518. SmartCollection.prototype.remove = function (key) {
  30519. if (this.items[key] == undefined) {
  30520. return -1;
  30521. }
  30522. return this.removeItemOfIndex(this.indexOf(key));
  30523. };
  30524. SmartCollection.prototype.removeItemOfIndex = function (index) {
  30525. if (index < this.count && index > -1) {
  30526. delete this.items[this._keys[index]];
  30527. while (index < this.count) {
  30528. this._keys[index] = this._keys[index + 1];
  30529. index++;
  30530. }
  30531. }
  30532. else {
  30533. return -1;
  30534. }
  30535. return --this.count;
  30536. };
  30537. SmartCollection.prototype.indexOf = function (key) {
  30538. for (var i = 0; i !== this.count; i++) {
  30539. if (this._keys[i] === key) {
  30540. return i;
  30541. }
  30542. }
  30543. return -1;
  30544. };
  30545. SmartCollection.prototype.item = function (key) {
  30546. return this.items[key];
  30547. };
  30548. SmartCollection.prototype.getAllKeys = function () {
  30549. if (this.count > 0) {
  30550. var keys = new Array(this.count);
  30551. for (var i = 0; i < this.count; i++) {
  30552. keys[i] = this._keys[i];
  30553. }
  30554. return keys;
  30555. }
  30556. else {
  30557. return undefined;
  30558. }
  30559. };
  30560. SmartCollection.prototype.getKeyByIndex = function (index) {
  30561. if (index < this.count && index > -1) {
  30562. return this._keys[index];
  30563. }
  30564. else {
  30565. return undefined;
  30566. }
  30567. };
  30568. SmartCollection.prototype.getItemByIndex = function (index) {
  30569. if (index < this.count && index > -1) {
  30570. return this.items[this._keys[index]];
  30571. }
  30572. else {
  30573. return undefined;
  30574. }
  30575. };
  30576. SmartCollection.prototype.empty = function () {
  30577. if (this.count > 0) {
  30578. this.count = 0;
  30579. this.items = {};
  30580. this._keys = new Array(this._initialCapacity);
  30581. }
  30582. };
  30583. SmartCollection.prototype.forEach = function (block) {
  30584. var key;
  30585. for (key in this.items) {
  30586. if (this.items.hasOwnProperty(key)) {
  30587. block(this.items[key]);
  30588. }
  30589. }
  30590. };
  30591. return SmartCollection;
  30592. })();
  30593. BABYLON.SmartCollection = SmartCollection;
  30594. })(BABYLON || (BABYLON = {}));
  30595. //# sourceMappingURL=babylon.smartCollection.js.map