babylon.2.1-beta.debug.js 1.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Color3 = (function () {
  4. function Color3(r, g, b) {
  5. if (r === void 0) { r = 0; }
  6. if (g === void 0) { g = 0; }
  7. if (b === void 0) { b = 0; }
  8. this.r = r;
  9. this.g = g;
  10. this.b = b;
  11. }
  12. Color3.prototype.toString = function () {
  13. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  14. };
  15. // Operators
  16. Color3.prototype.toArray = function (array, index) {
  17. if (index === undefined) {
  18. index = 0;
  19. }
  20. array[index] = this.r;
  21. array[index + 1] = this.g;
  22. array[index + 2] = this.b;
  23. return this;
  24. };
  25. Color3.prototype.toColor4 = function (alpha) {
  26. if (alpha === void 0) { alpha = 1; }
  27. return new Color4(this.r, this.g, this.b, alpha);
  28. };
  29. Color3.prototype.asArray = function () {
  30. var result = [];
  31. this.toArray(result, 0);
  32. return result;
  33. };
  34. Color3.prototype.toLuminance = function () {
  35. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  36. };
  37. Color3.prototype.multiply = function (otherColor) {
  38. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  39. };
  40. Color3.prototype.multiplyToRef = function (otherColor, result) {
  41. result.r = this.r * otherColor.r;
  42. result.g = this.g * otherColor.g;
  43. result.b = this.b * otherColor.b;
  44. return this;
  45. };
  46. Color3.prototype.equals = function (otherColor) {
  47. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  48. };
  49. Color3.prototype.scale = function (scale) {
  50. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  51. };
  52. Color3.prototype.scaleToRef = function (scale, result) {
  53. result.r = this.r * scale;
  54. result.g = this.g * scale;
  55. result.b = this.b * scale;
  56. return this;
  57. };
  58. Color3.prototype.add = function (otherColor) {
  59. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  60. };
  61. Color3.prototype.addToRef = function (otherColor, result) {
  62. result.r = this.r + otherColor.r;
  63. result.g = this.g + otherColor.g;
  64. result.b = this.b + otherColor.b;
  65. return this;
  66. };
  67. Color3.prototype.subtract = function (otherColor) {
  68. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  69. };
  70. Color3.prototype.subtractToRef = function (otherColor, result) {
  71. result.r = this.r - otherColor.r;
  72. result.g = this.g - otherColor.g;
  73. result.b = this.b - otherColor.b;
  74. return this;
  75. };
  76. Color3.prototype.clone = function () {
  77. return new Color3(this.r, this.g, this.b);
  78. };
  79. Color3.prototype.copyFrom = function (source) {
  80. this.r = source.r;
  81. this.g = source.g;
  82. this.b = source.b;
  83. return this;
  84. };
  85. Color3.prototype.copyFromFloats = function (r, g, b) {
  86. this.r = r;
  87. this.g = g;
  88. this.b = b;
  89. return this;
  90. };
  91. // Statics
  92. Color3.FromArray = function (array, offset) {
  93. if (offset === void 0) { offset = 0; }
  94. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  95. };
  96. Color3.FromInts = function (r, g, b) {
  97. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  98. };
  99. Color3.Lerp = function (start, end, amount) {
  100. var r = start.r + ((end.r - start.r) * amount);
  101. var g = start.g + ((end.g - start.g) * amount);
  102. var b = start.b + ((end.b - start.b) * amount);
  103. return new Color3(r, g, b);
  104. };
  105. Color3.Red = function () {
  106. return new Color3(1, 0, 0);
  107. };
  108. Color3.Green = function () {
  109. return new Color3(0, 1, 0);
  110. };
  111. Color3.Blue = function () {
  112. return new Color3(0, 0, 1);
  113. };
  114. Color3.Black = function () {
  115. return new Color3(0, 0, 0);
  116. };
  117. Color3.White = function () {
  118. return new Color3(1, 1, 1);
  119. };
  120. Color3.Purple = function () {
  121. return new Color3(0.5, 0, 0.5);
  122. };
  123. Color3.Magenta = function () {
  124. return new Color3(1, 0, 1);
  125. };
  126. Color3.Yellow = function () {
  127. return new Color3(1, 1, 0);
  128. };
  129. Color3.Gray = function () {
  130. return new Color3(0.5, 0.5, 0.5);
  131. };
  132. return Color3;
  133. })();
  134. BABYLON.Color3 = Color3;
  135. var Color4 = (function () {
  136. function Color4(r, g, b, a) {
  137. this.r = r;
  138. this.g = g;
  139. this.b = b;
  140. this.a = a;
  141. }
  142. // Operators
  143. Color4.prototype.addInPlace = function (right) {
  144. this.r += right.r;
  145. this.g += right.g;
  146. this.b += right.b;
  147. this.a += right.a;
  148. return this;
  149. };
  150. Color4.prototype.asArray = function () {
  151. var result = [];
  152. this.toArray(result, 0);
  153. return result;
  154. };
  155. Color4.prototype.toArray = function (array, index) {
  156. if (index === undefined) {
  157. index = 0;
  158. }
  159. array[index] = this.r;
  160. array[index + 1] = this.g;
  161. array[index + 2] = this.b;
  162. array[index + 3] = this.a;
  163. return this;
  164. };
  165. Color4.prototype.add = function (right) {
  166. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  167. };
  168. Color4.prototype.subtract = function (right) {
  169. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  170. };
  171. Color4.prototype.subtractToRef = function (right, result) {
  172. result.r = this.r - right.r;
  173. result.g = this.g - right.g;
  174. result.b = this.b - right.b;
  175. result.a = this.a - right.a;
  176. return this;
  177. };
  178. Color4.prototype.scale = function (scale) {
  179. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  180. };
  181. Color4.prototype.scaleToRef = function (scale, result) {
  182. result.r = this.r * scale;
  183. result.g = this.g * scale;
  184. result.b = this.b * scale;
  185. result.a = this.a * scale;
  186. return this;
  187. };
  188. Color4.prototype.toString = function () {
  189. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  190. };
  191. Color4.prototype.clone = function () {
  192. return new Color4(this.r, this.g, this.b, this.a);
  193. };
  194. Color4.prototype.copyFrom = function (source) {
  195. this.r = source.r;
  196. this.g = source.g;
  197. this.b = source.b;
  198. this.a = source.a;
  199. return this;
  200. };
  201. // Statics
  202. Color4.Lerp = function (left, right, amount) {
  203. var result = new Color4(0, 0, 0, 0);
  204. Color4.LerpToRef(left, right, amount, result);
  205. return result;
  206. };
  207. Color4.LerpToRef = function (left, right, amount, result) {
  208. result.r = left.r + (right.r - left.r) * amount;
  209. result.g = left.g + (right.g - left.g) * amount;
  210. result.b = left.b + (right.b - left.b) * amount;
  211. result.a = left.a + (right.a - left.a) * amount;
  212. };
  213. Color4.FromArray = function (array, offset) {
  214. if (offset === void 0) { offset = 0; }
  215. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  216. };
  217. Color4.FromInts = function (r, g, b, a) {
  218. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  219. };
  220. return Color4;
  221. })();
  222. BABYLON.Color4 = Color4;
  223. var Vector2 = (function () {
  224. function Vector2(x, y) {
  225. this.x = x;
  226. this.y = y;
  227. }
  228. Vector2.prototype.toString = function () {
  229. return "{X: " + this.x + " Y:" + this.y + "}";
  230. };
  231. // Operators
  232. Vector2.prototype.toArray = function (array, index) {
  233. if (index === void 0) { index = 0; }
  234. array[index] = this.x;
  235. array[index + 1] = this.y;
  236. return this;
  237. };
  238. Vector2.prototype.asArray = function () {
  239. var result = [];
  240. this.toArray(result, 0);
  241. return result;
  242. };
  243. Vector2.prototype.copyFrom = function (source) {
  244. this.x = source.x;
  245. this.y = source.y;
  246. return this;
  247. };
  248. Vector2.prototype.copyFromFloats = function (x, y) {
  249. this.x = x;
  250. this.y = y;
  251. return this;
  252. };
  253. Vector2.prototype.add = function (otherVector) {
  254. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  255. };
  256. Vector2.prototype.addVector3 = function (otherVector) {
  257. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  258. };
  259. Vector2.prototype.subtract = function (otherVector) {
  260. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  261. };
  262. Vector2.prototype.subtractInPlace = function (otherVector) {
  263. this.x -= otherVector.x;
  264. this.y -= otherVector.y;
  265. return this;
  266. };
  267. Vector2.prototype.multiplyInPlace = function (otherVector) {
  268. this.x *= otherVector.x;
  269. this.y *= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiply = function (otherVector) {
  273. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  274. };
  275. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  276. result.x = this.x * otherVector.x;
  277. result.y = this.y * otherVector.y;
  278. return this;
  279. };
  280. Vector2.prototype.multiplyByFloats = function (x, y) {
  281. return new Vector2(this.x * x, this.y * y);
  282. };
  283. Vector2.prototype.divide = function (otherVector) {
  284. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  285. };
  286. Vector2.prototype.divideToRef = function (otherVector, result) {
  287. result.x = this.x / otherVector.x;
  288. result.y = this.y / otherVector.y;
  289. return this;
  290. };
  291. Vector2.prototype.negate = function () {
  292. return new Vector2(-this.x, -this.y);
  293. };
  294. Vector2.prototype.scaleInPlace = function (scale) {
  295. this.x *= scale;
  296. this.y *= scale;
  297. return this;
  298. };
  299. Vector2.prototype.scale = function (scale) {
  300. return new Vector2(this.x * scale, this.y * scale);
  301. };
  302. Vector2.prototype.equals = function (otherVector) {
  303. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  304. };
  305. // Properties
  306. Vector2.prototype.length = function () {
  307. return Math.sqrt(this.x * this.x + this.y * this.y);
  308. };
  309. Vector2.prototype.lengthSquared = function () {
  310. return (this.x * this.x + this.y * this.y);
  311. };
  312. // Methods
  313. Vector2.prototype.normalize = function () {
  314. var len = this.length();
  315. if (len === 0)
  316. return this;
  317. var num = 1.0 / len;
  318. this.x *= num;
  319. this.y *= num;
  320. return this;
  321. };
  322. Vector2.prototype.clone = function () {
  323. return new Vector2(this.x, this.y);
  324. };
  325. // Statics
  326. Vector2.Zero = function () {
  327. return new Vector2(0, 0);
  328. };
  329. Vector2.FromArray = function (array, offset) {
  330. if (offset === void 0) { offset = 0; }
  331. return new Vector2(array[offset], array[offset + 1]);
  332. };
  333. Vector2.FromArrayToRef = function (array, offset, result) {
  334. result.x = array[offset];
  335. result.y = array[offset + 1];
  336. };
  337. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  338. var squared = amount * amount;
  339. var cubed = amount * squared;
  340. 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));
  341. 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));
  342. return new Vector2(x, y);
  343. };
  344. Vector2.Clamp = function (value, min, max) {
  345. var x = value.x;
  346. x = (x > max.x) ? max.x : x;
  347. x = (x < min.x) ? min.x : x;
  348. var y = value.y;
  349. y = (y > max.y) ? max.y : y;
  350. y = (y < min.y) ? min.y : y;
  351. return new Vector2(x, y);
  352. };
  353. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  354. var squared = amount * amount;
  355. var cubed = amount * squared;
  356. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  357. var part2 = (-2.0 * cubed) + (3.0 * squared);
  358. var part3 = (cubed - (2.0 * squared)) + amount;
  359. var part4 = cubed - squared;
  360. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  361. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  362. return new Vector2(x, y);
  363. };
  364. Vector2.Lerp = function (start, end, amount) {
  365. var x = start.x + ((end.x - start.x) * amount);
  366. var y = start.y + ((end.y - start.y) * amount);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Dot = function (left, right) {
  370. return left.x * right.x + left.y * right.y;
  371. };
  372. Vector2.Normalize = function (vector) {
  373. var newVector = vector.clone();
  374. newVector.normalize();
  375. return newVector;
  376. };
  377. Vector2.Minimize = function (left, right) {
  378. var x = (left.x < right.x) ? left.x : right.x;
  379. var y = (left.y < right.y) ? left.y : right.y;
  380. return new Vector2(x, y);
  381. };
  382. Vector2.Maximize = 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.Transform = function (vector, transformation) {
  388. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  389. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Distance = function (value1, value2) {
  393. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  394. };
  395. Vector2.DistanceSquared = function (value1, value2) {
  396. var x = value1.x - value2.x;
  397. var y = value1.y - value2.y;
  398. return (x * x) + (y * y);
  399. };
  400. return Vector2;
  401. })();
  402. BABYLON.Vector2 = Vector2;
  403. var Vector3 = (function () {
  404. function Vector3(x, y, z) {
  405. this.x = x;
  406. this.y = y;
  407. this.z = z;
  408. }
  409. Vector3.prototype.toString = function () {
  410. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  411. };
  412. // Operators
  413. Vector3.prototype.asArray = function () {
  414. var result = [];
  415. this.toArray(result, 0);
  416. return result;
  417. };
  418. Vector3.prototype.toArray = function (array, index) {
  419. if (index === void 0) { index = 0; }
  420. array[index] = this.x;
  421. array[index + 1] = this.y;
  422. array[index + 2] = this.z;
  423. return this;
  424. };
  425. Vector3.prototype.toQuaternion = function () {
  426. var result = new Quaternion(0, 0, 0, 1);
  427. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  428. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  429. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  430. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  431. var cosy = Math.cos(this.y * 0.5);
  432. var siny = Math.sin(this.y * 0.5);
  433. result.x = coszMinusx * siny;
  434. result.y = -sinzMinusx * siny;
  435. result.z = sinxPlusz * cosy;
  436. result.w = cosxPlusz * cosy;
  437. return result;
  438. };
  439. Vector3.prototype.addInPlace = function (otherVector) {
  440. this.x += otherVector.x;
  441. this.y += otherVector.y;
  442. this.z += otherVector.z;
  443. return this;
  444. };
  445. Vector3.prototype.add = function (otherVector) {
  446. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  447. };
  448. Vector3.prototype.addToRef = function (otherVector, result) {
  449. result.x = this.x + otherVector.x;
  450. result.y = this.y + otherVector.y;
  451. result.z = this.z + otherVector.z;
  452. return this;
  453. };
  454. Vector3.prototype.subtractInPlace = function (otherVector) {
  455. this.x -= otherVector.x;
  456. this.y -= otherVector.y;
  457. this.z -= otherVector.z;
  458. return this;
  459. };
  460. Vector3.prototype.subtract = function (otherVector) {
  461. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  462. };
  463. Vector3.prototype.subtractToRef = function (otherVector, result) {
  464. result.x = this.x - otherVector.x;
  465. result.y = this.y - otherVector.y;
  466. result.z = this.z - otherVector.z;
  467. return this;
  468. };
  469. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  470. return new Vector3(this.x - x, this.y - y, this.z - z);
  471. };
  472. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  473. result.x = this.x - x;
  474. result.y = this.y - y;
  475. result.z = this.z - z;
  476. return this;
  477. };
  478. Vector3.prototype.negate = function () {
  479. return new Vector3(-this.x, -this.y, -this.z);
  480. };
  481. Vector3.prototype.scaleInPlace = function (scale) {
  482. this.x *= scale;
  483. this.y *= scale;
  484. this.z *= scale;
  485. return this;
  486. };
  487. Vector3.prototype.scale = function (scale) {
  488. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  489. };
  490. Vector3.prototype.scaleToRef = function (scale, result) {
  491. result.x = this.x * scale;
  492. result.y = this.y * scale;
  493. result.z = this.z * scale;
  494. };
  495. Vector3.prototype.equals = function (otherVector) {
  496. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  497. };
  498. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  499. 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;
  500. };
  501. Vector3.prototype.equalsToFloats = function (x, y, z) {
  502. return this.x === x && this.y === y && this.z === z;
  503. };
  504. Vector3.prototype.multiplyInPlace = function (otherVector) {
  505. this.x *= otherVector.x;
  506. this.y *= otherVector.y;
  507. this.z *= otherVector.z;
  508. return this;
  509. };
  510. Vector3.prototype.multiply = function (otherVector) {
  511. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  512. };
  513. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  514. result.x = this.x * otherVector.x;
  515. result.y = this.y * otherVector.y;
  516. result.z = this.z * otherVector.z;
  517. return this;
  518. };
  519. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  520. return new Vector3(this.x * x, this.y * y, this.z * z);
  521. };
  522. Vector3.prototype.divide = function (otherVector) {
  523. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  524. };
  525. Vector3.prototype.divideToRef = function (otherVector, result) {
  526. result.x = this.x / otherVector.x;
  527. result.y = this.y / otherVector.y;
  528. result.z = this.z / otherVector.z;
  529. return this;
  530. };
  531. Vector3.prototype.MinimizeInPlace = function (other) {
  532. if (other.x < this.x)
  533. this.x = other.x;
  534. if (other.y < this.y)
  535. this.y = other.y;
  536. if (other.z < this.z)
  537. this.z = other.z;
  538. return this;
  539. };
  540. Vector3.prototype.MaximizeInPlace = function (other) {
  541. if (other.x > this.x)
  542. this.x = other.x;
  543. if (other.y > this.y)
  544. this.y = other.y;
  545. if (other.z > this.z)
  546. this.z = other.z;
  547. return this;
  548. };
  549. // Properties
  550. Vector3.prototype.length = function () {
  551. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  552. };
  553. Vector3.prototype.lengthSquared = function () {
  554. return (this.x * this.x + this.y * this.y + this.z * this.z);
  555. };
  556. // Methods
  557. Vector3.prototype.normalize = function () {
  558. var len = this.length();
  559. if (len === 0)
  560. return this;
  561. var num = 1.0 / len;
  562. this.x *= num;
  563. this.y *= num;
  564. this.z *= num;
  565. return this;
  566. };
  567. Vector3.prototype.clone = function () {
  568. return new Vector3(this.x, this.y, this.z);
  569. };
  570. Vector3.prototype.copyFrom = function (source) {
  571. this.x = source.x;
  572. this.y = source.y;
  573. this.z = source.z;
  574. return this;
  575. };
  576. Vector3.prototype.copyFromFloats = function (x, y, z) {
  577. this.x = x;
  578. this.y = y;
  579. this.z = z;
  580. return this;
  581. };
  582. // Statics
  583. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  584. var d0 = Vector3.Dot(vector0, axis) - size;
  585. var d1 = Vector3.Dot(vector1, axis) - size;
  586. var s = d0 / (d0 - d1);
  587. return s;
  588. };
  589. Vector3.FromArray = function (array, offset) {
  590. if (!offset) {
  591. offset = 0;
  592. }
  593. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  594. };
  595. Vector3.FromArrayToRef = function (array, offset, result) {
  596. result.x = array[offset];
  597. result.y = array[offset + 1];
  598. result.z = array[offset + 2];
  599. };
  600. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  601. result.x = array[offset];
  602. result.y = array[offset + 1];
  603. result.z = array[offset + 2];
  604. };
  605. Vector3.FromFloatsToRef = function (x, y, z, result) {
  606. result.x = x;
  607. result.y = y;
  608. result.z = z;
  609. };
  610. Vector3.Zero = function () {
  611. return new Vector3(0, 0, 0);
  612. };
  613. Vector3.Up = function () {
  614. return new Vector3(0, 1.0, 0);
  615. };
  616. Vector3.TransformCoordinates = function (vector, transformation) {
  617. var result = Vector3.Zero();
  618. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  619. return result;
  620. };
  621. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  622. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  623. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  624. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  625. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  626. result.x = x / w;
  627. result.y = y / w;
  628. result.z = z / w;
  629. };
  630. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  631. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  632. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  633. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  634. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  635. result.x = rx / rw;
  636. result.y = ry / rw;
  637. result.z = rz / rw;
  638. };
  639. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  640. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  641. var m0 = SIMD.float32x4.load(transformation.m, 0);
  642. var m1 = SIMD.float32x4.load(transformation.m, 4);
  643. var m2 = SIMD.float32x4.load(transformation.m, 8);
  644. var m3 = SIMD.float32x4.load(transformation.m, 12);
  645. 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));
  646. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  647. SIMD.float32x4.storeXYZ(result._data, 0, r);
  648. };
  649. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  650. var v0 = SIMD.float32x4.splat(x);
  651. var v1 = SIMD.float32x4.splat(y);
  652. var v2 = SIMD.float32x4.splat(z);
  653. var m0 = SIMD.float32x4.load(transformation.m, 0);
  654. var m1 = SIMD.float32x4.load(transformation.m, 4);
  655. var m2 = SIMD.float32x4.load(transformation.m, 8);
  656. var m3 = SIMD.float32x4.load(transformation.m, 12);
  657. 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));
  658. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  659. SIMD.float32x4.storeXYZ(result._data, 0, r);
  660. };
  661. Vector3.TransformNormal = function (vector, transformation) {
  662. var result = Vector3.Zero();
  663. Vector3.TransformNormalToRef(vector, transformation, result);
  664. return result;
  665. };
  666. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  667. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  668. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  669. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  670. };
  671. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  672. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  673. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  674. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  675. };
  676. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  677. var squared = amount * amount;
  678. var cubed = amount * squared;
  679. 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));
  680. 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));
  681. 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));
  682. return new Vector3(x, y, z);
  683. };
  684. Vector3.Clamp = function (value, min, max) {
  685. var x = value.x;
  686. x = (x > max.x) ? max.x : x;
  687. x = (x < min.x) ? min.x : x;
  688. var y = value.y;
  689. y = (y > max.y) ? max.y : y;
  690. y = (y < min.y) ? min.y : y;
  691. var z = value.z;
  692. z = (z > max.z) ? max.z : z;
  693. z = (z < min.z) ? min.z : z;
  694. return new Vector3(x, y, z);
  695. };
  696. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  697. var squared = amount * amount;
  698. var cubed = amount * squared;
  699. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  700. var part2 = (-2.0 * cubed) + (3.0 * squared);
  701. var part3 = (cubed - (2.0 * squared)) + amount;
  702. var part4 = cubed - squared;
  703. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  704. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  705. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  706. return new Vector3(x, y, z);
  707. };
  708. Vector3.Lerp = function (start, end, amount) {
  709. var x = start.x + ((end.x - start.x) * amount);
  710. var y = start.y + ((end.y - start.y) * amount);
  711. var z = start.z + ((end.z - start.z) * amount);
  712. return new Vector3(x, y, z);
  713. };
  714. Vector3.Dot = function (left, right) {
  715. return (left.x * right.x + left.y * right.y + left.z * right.z);
  716. };
  717. Vector3.Cross = function (left, right) {
  718. var result = Vector3.Zero();
  719. Vector3.CrossToRef(left, right, result);
  720. return result;
  721. };
  722. Vector3.CrossToRef = function (left, right, result) {
  723. result.x = left.y * right.z - left.z * right.y;
  724. result.y = left.z * right.x - left.x * right.z;
  725. result.z = left.x * right.y - left.y * right.x;
  726. };
  727. Vector3.Normalize = function (vector) {
  728. var result = Vector3.Zero();
  729. Vector3.NormalizeToRef(vector, result);
  730. return result;
  731. };
  732. Vector3.NormalizeToRef = function (vector, result) {
  733. result.copyFrom(vector);
  734. result.normalize();
  735. };
  736. Vector3.Project = function (vector, world, transform, viewport) {
  737. var cw = viewport.width;
  738. var ch = viewport.height;
  739. var cx = viewport.x;
  740. var cy = viewport.y;
  741. 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);
  742. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  743. return Vector3.TransformCoordinates(vector, finalMatrix);
  744. };
  745. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  746. var matrix = world.multiply(transform);
  747. matrix.invert();
  748. source.x = source.x / viewportWidth * 2 - 1;
  749. source.y = -(source.y / viewportHeight * 2 - 1);
  750. var vector = Vector3.TransformCoordinates(source, matrix);
  751. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  752. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  753. vector = vector.scale(1.0 / num);
  754. }
  755. return vector;
  756. };
  757. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  758. var matrix = world.multiply(view).multiply(projection);
  759. matrix.invert();
  760. source.x = source.x / viewportWidth * 2 - 1;
  761. source.y = -(source.y / viewportHeight * 2 - 1);
  762. var vector = Vector3.TransformCoordinates(source, matrix);
  763. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  764. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  765. vector = vector.scale(1.0 / num);
  766. }
  767. return vector;
  768. };
  769. Vector3.Minimize = function (left, right) {
  770. var min = left.clone();
  771. min.MinimizeInPlace(right);
  772. return min;
  773. };
  774. Vector3.Maximize = function (left, right) {
  775. var max = left.clone();
  776. max.MaximizeInPlace(right);
  777. return max;
  778. };
  779. Vector3.Distance = function (value1, value2) {
  780. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  781. };
  782. Vector3.DistanceSquared = function (value1, value2) {
  783. var x = value1.x - value2.x;
  784. var y = value1.y - value2.y;
  785. var z = value1.z - value2.z;
  786. return (x * x) + (y * y) + (z * z);
  787. };
  788. Vector3.Center = function (value1, value2) {
  789. var center = value1.add(value2);
  790. center.scaleInPlace(0.5);
  791. return center;
  792. };
  793. return Vector3;
  794. })();
  795. BABYLON.Vector3 = Vector3;
  796. //Vector4 class created for EulerAngle class conversion to Quaternion
  797. var Vector4 = (function () {
  798. function Vector4(x, y, z, w) {
  799. this.x = x;
  800. this.y = y;
  801. this.z = z;
  802. this.w = w;
  803. }
  804. Vector4.prototype.toString = function () {
  805. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  806. };
  807. // Operators
  808. Vector4.prototype.asArray = function () {
  809. var result = [];
  810. this.toArray(result, 0);
  811. return result;
  812. };
  813. Vector4.prototype.toArray = function (array, index) {
  814. if (index === undefined) {
  815. index = 0;
  816. }
  817. array[index] = this.x;
  818. array[index + 1] = this.y;
  819. array[index + 2] = this.z;
  820. array[index + 3] = this.w;
  821. return this;
  822. };
  823. Vector4.prototype.addInPlace = function (otherVector) {
  824. this.x += otherVector.x;
  825. this.y += otherVector.y;
  826. this.z += otherVector.z;
  827. this.w += otherVector.w;
  828. return this;
  829. };
  830. Vector4.prototype.add = function (otherVector) {
  831. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  832. };
  833. Vector4.prototype.addToRef = function (otherVector, result) {
  834. result.x = this.x + otherVector.x;
  835. result.y = this.y + otherVector.y;
  836. result.z = this.z + otherVector.z;
  837. result.w = this.w + otherVector.w;
  838. return this;
  839. };
  840. Vector4.prototype.subtractInPlace = function (otherVector) {
  841. this.x -= otherVector.x;
  842. this.y -= otherVector.y;
  843. this.z -= otherVector.z;
  844. this.w -= otherVector.w;
  845. return this;
  846. };
  847. Vector4.prototype.subtract = function (otherVector) {
  848. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  849. };
  850. Vector4.prototype.subtractToRef = function (otherVector, result) {
  851. result.x = this.x - otherVector.x;
  852. result.y = this.y - otherVector.y;
  853. result.z = this.z - otherVector.z;
  854. result.w = this.w - otherVector.w;
  855. return this;
  856. };
  857. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  858. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  859. };
  860. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  861. result.x = this.x - x;
  862. result.y = this.y - y;
  863. result.z = this.z - z;
  864. result.w = this.w - w;
  865. return this;
  866. };
  867. Vector4.prototype.negate = function () {
  868. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  869. };
  870. Vector4.prototype.scaleInPlace = function (scale) {
  871. this.x *= scale;
  872. this.y *= scale;
  873. this.z *= scale;
  874. this.w *= scale;
  875. return this;
  876. };
  877. Vector4.prototype.scale = function (scale) {
  878. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  879. };
  880. Vector4.prototype.scaleToRef = function (scale, result) {
  881. result.x = this.x * scale;
  882. result.y = this.y * scale;
  883. result.z = this.z * scale;
  884. result.w = this.w * scale;
  885. };
  886. Vector4.prototype.equals = function (otherVector) {
  887. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  888. };
  889. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  890. 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;
  891. };
  892. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  893. return this.x === x && this.y === y && this.z === z && this.w === w;
  894. };
  895. Vector4.prototype.multiplyInPlace = function (otherVector) {
  896. this.x *= otherVector.x;
  897. this.y *= otherVector.y;
  898. this.z *= otherVector.z;
  899. this.w *= otherVector.w;
  900. return this;
  901. };
  902. Vector4.prototype.multiply = function (otherVector) {
  903. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  904. };
  905. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  906. result.x = this.x * otherVector.x;
  907. result.y = this.y * otherVector.y;
  908. result.z = this.z * otherVector.z;
  909. result.w = this.w * otherVector.w;
  910. return this;
  911. };
  912. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  913. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  914. };
  915. Vector4.prototype.divide = function (otherVector) {
  916. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  917. };
  918. Vector4.prototype.divideToRef = function (otherVector, result) {
  919. result.x = this.x / otherVector.x;
  920. result.y = this.y / otherVector.y;
  921. result.z = this.z / otherVector.z;
  922. result.w = this.w / otherVector.w;
  923. return this;
  924. };
  925. Vector4.prototype.MinimizeInPlace = function (other) {
  926. if (other.x < this.x)
  927. this.x = other.x;
  928. if (other.y < this.y)
  929. this.y = other.y;
  930. if (other.z < this.z)
  931. this.z = other.z;
  932. if (other.w < this.w)
  933. this.w = other.w;
  934. return this;
  935. };
  936. Vector4.prototype.MaximizeInPlace = function (other) {
  937. if (other.x > this.x)
  938. this.x = other.x;
  939. if (other.y > this.y)
  940. this.y = other.y;
  941. if (other.z > this.z)
  942. this.z = other.z;
  943. if (other.w > this.w)
  944. this.w = other.w;
  945. return this;
  946. };
  947. // Properties
  948. Vector4.prototype.length = function () {
  949. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  950. };
  951. Vector4.prototype.lengthSquared = function () {
  952. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  953. };
  954. // Methods
  955. Vector4.prototype.normalize = function () {
  956. var len = this.length();
  957. if (len === 0)
  958. return this;
  959. var num = 1.0 / len;
  960. this.x *= num;
  961. this.y *= num;
  962. this.z *= num;
  963. this.w *= num;
  964. return this;
  965. };
  966. Vector4.prototype.clone = function () {
  967. return new Vector4(this.x, this.y, this.z, this.w);
  968. };
  969. Vector4.prototype.copyFrom = function (source) {
  970. this.x = source.x;
  971. this.y = source.y;
  972. this.z = source.z;
  973. this.w = source.w;
  974. return this;
  975. };
  976. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  977. this.x = x;
  978. this.y = y;
  979. this.z = z;
  980. this.w = w;
  981. return this;
  982. };
  983. // Statics
  984. Vector4.FromArray = function (array, offset) {
  985. if (!offset) {
  986. offset = 0;
  987. }
  988. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  989. };
  990. Vector4.FromArrayToRef = function (array, offset, result) {
  991. result.x = array[offset];
  992. result.y = array[offset + 1];
  993. result.z = array[offset + 2];
  994. result.w = array[offset + 3];
  995. };
  996. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  997. result.x = array[offset];
  998. result.y = array[offset + 1];
  999. result.z = array[offset + 2];
  1000. result.w = array[offset + 3];
  1001. };
  1002. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1003. result.x = x;
  1004. result.y = y;
  1005. result.z = z;
  1006. result.w = w;
  1007. };
  1008. Vector4.Zero = function () {
  1009. return new Vector4(0, 0, 0, 0);
  1010. };
  1011. Vector4.Normalize = function (vector) {
  1012. var result = Vector4.Zero();
  1013. Vector4.NormalizeToRef(vector, result);
  1014. return result;
  1015. };
  1016. Vector4.NormalizeToRef = function (vector, result) {
  1017. result.copyFrom(vector);
  1018. result.normalize();
  1019. };
  1020. Vector4.Minimize = function (left, right) {
  1021. var min = left.clone();
  1022. min.MinimizeInPlace(right);
  1023. return min;
  1024. };
  1025. Vector4.Maximize = function (left, right) {
  1026. var max = left.clone();
  1027. max.MaximizeInPlace(right);
  1028. return max;
  1029. };
  1030. Vector4.Distance = function (value1, value2) {
  1031. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1032. };
  1033. Vector4.DistanceSquared = function (value1, value2) {
  1034. var x = value1.x - value2.x;
  1035. var y = value1.y - value2.y;
  1036. var z = value1.z - value2.z;
  1037. var w = value1.w - value2.w;
  1038. return (x * x) + (y * y) + (z * z) + (w * w);
  1039. };
  1040. Vector4.Center = function (value1, value2) {
  1041. var center = value1.add(value2);
  1042. center.scaleInPlace(0.5);
  1043. return center;
  1044. };
  1045. return Vector4;
  1046. })();
  1047. BABYLON.Vector4 = Vector4;
  1048. var Quaternion = (function () {
  1049. function Quaternion(x, y, z, w) {
  1050. if (x === void 0) { x = 0; }
  1051. if (y === void 0) { y = 0; }
  1052. if (z === void 0) { z = 0; }
  1053. if (w === void 0) { w = 1; }
  1054. this.x = x;
  1055. this.y = y;
  1056. this.z = z;
  1057. this.w = w;
  1058. }
  1059. Quaternion.prototype.toString = function () {
  1060. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1061. };
  1062. Quaternion.prototype.asArray = function () {
  1063. return [this.x, this.y, this.z, this.w];
  1064. };
  1065. Quaternion.prototype.equals = function (otherQuaternion) {
  1066. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1067. };
  1068. Quaternion.prototype.clone = function () {
  1069. return new Quaternion(this.x, this.y, this.z, this.w);
  1070. };
  1071. Quaternion.prototype.copyFrom = function (other) {
  1072. this.x = other.x;
  1073. this.y = other.y;
  1074. this.z = other.z;
  1075. this.w = other.w;
  1076. return this;
  1077. };
  1078. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1079. this.x = x;
  1080. this.y = y;
  1081. this.z = z;
  1082. this.w = w;
  1083. return this;
  1084. };
  1085. Quaternion.prototype.add = function (other) {
  1086. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1087. };
  1088. Quaternion.prototype.subtract = function (other) {
  1089. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1090. };
  1091. Quaternion.prototype.scale = function (value) {
  1092. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1093. };
  1094. Quaternion.prototype.multiply = function (q1) {
  1095. var result = new Quaternion(0, 0, 0, 1.0);
  1096. this.multiplyToRef(q1, result);
  1097. return result;
  1098. };
  1099. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1100. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1101. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1102. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1103. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1104. return this;
  1105. };
  1106. Quaternion.prototype.length = function () {
  1107. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1108. };
  1109. Quaternion.prototype.normalize = function () {
  1110. var length = 1.0 / this.length();
  1111. this.x *= length;
  1112. this.y *= length;
  1113. this.z *= length;
  1114. this.w *= length;
  1115. return this;
  1116. };
  1117. Quaternion.prototype.toEulerAngles = function () {
  1118. var result = Vector3.Zero();
  1119. this.toEulerAnglesToRef(result);
  1120. return result;
  1121. };
  1122. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1123. //result is an EulerAngles in the in the z-x-z convention
  1124. var qx = this.x;
  1125. var qy = this.y;
  1126. var qz = this.z;
  1127. var qw = this.w;
  1128. var qxy = qx * qy;
  1129. var qxz = qx * qz;
  1130. var qwy = qw * qy;
  1131. var qwz = qw * qz;
  1132. var qwx = qw * qx;
  1133. var qyz = qy * qz;
  1134. var sqx = qx * qx;
  1135. var sqy = qy * qy;
  1136. var determinant = sqx + sqy;
  1137. if (determinant !== 0.000 && determinant !== 1.000) {
  1138. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1139. result.y = Math.acos(1 - 2 * determinant);
  1140. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1141. }
  1142. else {
  1143. if (determinant === 0.0) {
  1144. result.x = 0.0;
  1145. result.y = 0.0;
  1146. 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)
  1147. }
  1148. else {
  1149. 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)
  1150. result.y = Math.PI;
  1151. result.z = 0.0;
  1152. }
  1153. }
  1154. return this;
  1155. };
  1156. Quaternion.prototype.toRotationMatrix = function (result) {
  1157. var xx = this.x * this.x;
  1158. var yy = this.y * this.y;
  1159. var zz = this.z * this.z;
  1160. var xy = this.x * this.y;
  1161. var zw = this.z * this.w;
  1162. var zx = this.z * this.x;
  1163. var yw = this.y * this.w;
  1164. var yz = this.y * this.z;
  1165. var xw = this.x * this.w;
  1166. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1167. result.m[1] = 2.0 * (xy + zw);
  1168. result.m[2] = 2.0 * (zx - yw);
  1169. result.m[3] = 0;
  1170. result.m[4] = 2.0 * (xy - zw);
  1171. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1172. result.m[6] = 2.0 * (yz + xw);
  1173. result.m[7] = 0;
  1174. result.m[8] = 2.0 * (zx + yw);
  1175. result.m[9] = 2.0 * (yz - xw);
  1176. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1177. result.m[11] = 0;
  1178. result.m[12] = 0;
  1179. result.m[13] = 0;
  1180. result.m[14] = 0;
  1181. result.m[15] = 1.0;
  1182. return this;
  1183. };
  1184. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1185. Quaternion.FromRotationMatrixToRef(matrix, this);
  1186. return this;
  1187. };
  1188. // Statics
  1189. Quaternion.FromRotationMatrix = function (matrix) {
  1190. var result = new Quaternion();
  1191. Quaternion.FromRotationMatrixToRef(matrix, result);
  1192. return result;
  1193. };
  1194. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1195. var data = matrix.m;
  1196. var m11 = data[0], m12 = data[4], m13 = data[8];
  1197. var m21 = data[1], m22 = data[5], m23 = data[9];
  1198. var m31 = data[2], m32 = data[6], m33 = data[10];
  1199. var trace = m11 + m22 + m33;
  1200. var s;
  1201. if (trace > 0) {
  1202. s = 0.5 / Math.sqrt(trace + 1.0);
  1203. result.w = 0.25 / s;
  1204. result.x = (m32 - m23) * s;
  1205. result.y = (m13 - m31) * s;
  1206. result.z = (m21 - m12) * s;
  1207. }
  1208. else if (m11 > m22 && m11 > m33) {
  1209. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1210. result.w = (m32 - m23) / s;
  1211. result.x = 0.25 * s;
  1212. result.y = (m12 + m21) / s;
  1213. result.z = (m13 + m31) / s;
  1214. }
  1215. else if (m22 > m33) {
  1216. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1217. result.w = (m13 - m31) / s;
  1218. result.x = (m12 + m21) / s;
  1219. result.y = 0.25 * s;
  1220. result.z = (m23 + m32) / s;
  1221. }
  1222. else {
  1223. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1224. result.w = (m21 - m12) / s;
  1225. result.x = (m13 + m31) / s;
  1226. result.y = (m23 + m32) / s;
  1227. result.z = 0.25 * s;
  1228. }
  1229. };
  1230. Quaternion.Inverse = function (q) {
  1231. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1232. };
  1233. Quaternion.Identity = function () {
  1234. return new Quaternion(0, 0, 0, 1);
  1235. };
  1236. Quaternion.RotationAxis = function (axis, angle) {
  1237. var result = new Quaternion();
  1238. var sin = Math.sin(angle / 2);
  1239. result.w = Math.cos(angle / 2);
  1240. result.x = axis.x * sin;
  1241. result.y = axis.y * sin;
  1242. result.z = axis.z * sin;
  1243. return result;
  1244. };
  1245. Quaternion.FromArray = function (array, offset) {
  1246. if (!offset) {
  1247. offset = 0;
  1248. }
  1249. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1250. };
  1251. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1252. var result = new Quaternion();
  1253. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1254. return result;
  1255. };
  1256. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1257. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1258. var halfRoll = roll * 0.5;
  1259. var halfPitch = pitch * 0.5;
  1260. var halfYaw = yaw * 0.5;
  1261. var sinRoll = Math.sin(halfRoll);
  1262. var cosRoll = Math.cos(halfRoll);
  1263. var sinPitch = Math.sin(halfPitch);
  1264. var cosPitch = Math.cos(halfPitch);
  1265. var sinYaw = Math.sin(halfYaw);
  1266. var cosYaw = Math.cos(halfYaw);
  1267. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1268. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1269. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1270. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1271. };
  1272. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1273. var result = new Quaternion();
  1274. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1275. return result;
  1276. };
  1277. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1278. // Produces a quaternion from Euler angles in the z-x-z orientation
  1279. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1280. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1281. var halfBeta = beta * 0.5;
  1282. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1283. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1284. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1285. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1286. };
  1287. Quaternion.Slerp = function (left, right, amount) {
  1288. var num2;
  1289. var num3;
  1290. var num = amount;
  1291. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1292. var flag = false;
  1293. if (num4 < 0) {
  1294. flag = true;
  1295. num4 = -num4;
  1296. }
  1297. if (num4 > 0.999999) {
  1298. num3 = 1 - num;
  1299. num2 = flag ? -num : num;
  1300. }
  1301. else {
  1302. var num5 = Math.acos(num4);
  1303. var num6 = (1.0 / Math.sin(num5));
  1304. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1305. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1306. }
  1307. 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));
  1308. };
  1309. return Quaternion;
  1310. })();
  1311. BABYLON.Quaternion = Quaternion;
  1312. var Matrix = (function () {
  1313. function Matrix() {
  1314. this.m = new Float32Array(16);
  1315. }
  1316. // Properties
  1317. Matrix.prototype.isIdentity = function () {
  1318. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1319. return false;
  1320. 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)
  1321. return false;
  1322. return true;
  1323. };
  1324. Matrix.prototype.determinant = function () {
  1325. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1326. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1327. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1328. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1329. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1330. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1331. 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))));
  1332. };
  1333. // Methods
  1334. Matrix.prototype.toArray = function () {
  1335. return this.m;
  1336. };
  1337. Matrix.prototype.asArray = function () {
  1338. return this.toArray();
  1339. };
  1340. Matrix.prototype.invert = function () {
  1341. this.invertToRef(this);
  1342. return this;
  1343. };
  1344. Matrix.prototype.invertToRef = function (other) {
  1345. var l1 = this.m[0];
  1346. var l2 = this.m[1];
  1347. var l3 = this.m[2];
  1348. var l4 = this.m[3];
  1349. var l5 = this.m[4];
  1350. var l6 = this.m[5];
  1351. var l7 = this.m[6];
  1352. var l8 = this.m[7];
  1353. var l9 = this.m[8];
  1354. var l10 = this.m[9];
  1355. var l11 = this.m[10];
  1356. var l12 = this.m[11];
  1357. var l13 = this.m[12];
  1358. var l14 = this.m[13];
  1359. var l15 = this.m[14];
  1360. var l16 = this.m[15];
  1361. var l17 = (l11 * l16) - (l12 * l15);
  1362. var l18 = (l10 * l16) - (l12 * l14);
  1363. var l19 = (l10 * l15) - (l11 * l14);
  1364. var l20 = (l9 * l16) - (l12 * l13);
  1365. var l21 = (l9 * l15) - (l11 * l13);
  1366. var l22 = (l9 * l14) - (l10 * l13);
  1367. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1368. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1369. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1370. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1371. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1372. var l28 = (l7 * l16) - (l8 * l15);
  1373. var l29 = (l6 * l16) - (l8 * l14);
  1374. var l30 = (l6 * l15) - (l7 * l14);
  1375. var l31 = (l5 * l16) - (l8 * l13);
  1376. var l32 = (l5 * l15) - (l7 * l13);
  1377. var l33 = (l5 * l14) - (l6 * l13);
  1378. var l34 = (l7 * l12) - (l8 * l11);
  1379. var l35 = (l6 * l12) - (l8 * l10);
  1380. var l36 = (l6 * l11) - (l7 * l10);
  1381. var l37 = (l5 * l12) - (l8 * l9);
  1382. var l38 = (l5 * l11) - (l7 * l9);
  1383. var l39 = (l5 * l10) - (l6 * l9);
  1384. other.m[0] = l23 * l27;
  1385. other.m[4] = l24 * l27;
  1386. other.m[8] = l25 * l27;
  1387. other.m[12] = l26 * l27;
  1388. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1389. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1390. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1391. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1392. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1393. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1394. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1395. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1396. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1397. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1398. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1399. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1400. return this;
  1401. };
  1402. Matrix.prototype.invertToRefSIMD = function (other) {
  1403. var src = this.m;
  1404. var dest = other.m;
  1405. var row0, row1, row2, row3;
  1406. var tmp1;
  1407. var minor0, minor1, minor2, minor3;
  1408. var det;
  1409. // Load the 4 rows
  1410. var src0 = SIMD.float32x4.load(src, 0);
  1411. var src1 = SIMD.float32x4.load(src, 4);
  1412. var src2 = SIMD.float32x4.load(src, 8);
  1413. var src3 = SIMD.float32x4.load(src, 12);
  1414. // Transpose the source matrix. Sort of. Not a true transpose operation
  1415. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1416. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1417. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1418. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1419. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1420. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1421. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1422. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1423. // This is a true transposition, but it will lead to an incorrect result
  1424. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1425. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1426. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1427. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1428. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1429. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1430. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1431. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1432. // ----
  1433. tmp1 = SIMD.float32x4.mul(row2, row3);
  1434. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1435. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1436. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1437. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1438. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1439. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1440. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1441. // ----
  1442. tmp1 = SIMD.float32x4.mul(row1, row2);
  1443. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1444. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1445. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1446. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1447. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1448. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1449. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1450. // ----
  1451. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1452. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1453. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1454. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1455. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1456. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1457. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1458. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1459. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1460. // ----
  1461. tmp1 = SIMD.float32x4.mul(row0, row1);
  1462. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1463. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1464. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1465. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1466. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1467. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1468. // ----
  1469. tmp1 = SIMD.float32x4.mul(row0, row3);
  1470. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1471. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1472. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1473. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1474. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1475. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1476. // ----
  1477. tmp1 = SIMD.float32x4.mul(row0, row2);
  1478. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1479. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1480. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1481. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1482. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1483. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1484. // Compute determinant
  1485. det = SIMD.float32x4.mul(row0, minor0);
  1486. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1487. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1488. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1489. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1490. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1491. // These shuffles aren't necessary if the faulty transposition is done
  1492. // up at the top of this function.
  1493. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1494. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1495. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1496. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1497. // Compute final values by multiplying with 1/det
  1498. minor0 = SIMD.float32x4.mul(det, minor0);
  1499. minor1 = SIMD.float32x4.mul(det, minor1);
  1500. minor2 = SIMD.float32x4.mul(det, minor2);
  1501. minor3 = SIMD.float32x4.mul(det, minor3);
  1502. SIMD.float32x4.store(dest, 0, minor0);
  1503. SIMD.float32x4.store(dest, 4, minor1);
  1504. SIMD.float32x4.store(dest, 8, minor2);
  1505. SIMD.float32x4.store(dest, 12, minor3);
  1506. return this;
  1507. };
  1508. Matrix.prototype.setTranslation = function (vector3) {
  1509. this.m[12] = vector3.x;
  1510. this.m[13] = vector3.y;
  1511. this.m[14] = vector3.z;
  1512. return this;
  1513. };
  1514. Matrix.prototype.multiply = function (other) {
  1515. var result = new Matrix();
  1516. this.multiplyToRef(other, result);
  1517. return result;
  1518. };
  1519. Matrix.prototype.copyFrom = function (other) {
  1520. for (var index = 0; index < 16; index++) {
  1521. this.m[index] = other.m[index];
  1522. }
  1523. return this;
  1524. };
  1525. Matrix.prototype.copyToArray = function (array, offset) {
  1526. if (offset === void 0) { offset = 0; }
  1527. for (var index = 0; index < 16; index++) {
  1528. array[offset + index] = this.m[index];
  1529. }
  1530. return this;
  1531. };
  1532. Matrix.prototype.multiplyToRef = function (other, result) {
  1533. this.multiplyToArray(other, result.m, 0);
  1534. return this;
  1535. };
  1536. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1537. var tm0 = this.m[0];
  1538. var tm1 = this.m[1];
  1539. var tm2 = this.m[2];
  1540. var tm3 = this.m[3];
  1541. var tm4 = this.m[4];
  1542. var tm5 = this.m[5];
  1543. var tm6 = this.m[6];
  1544. var tm7 = this.m[7];
  1545. var tm8 = this.m[8];
  1546. var tm9 = this.m[9];
  1547. var tm10 = this.m[10];
  1548. var tm11 = this.m[11];
  1549. var tm12 = this.m[12];
  1550. var tm13 = this.m[13];
  1551. var tm14 = this.m[14];
  1552. var tm15 = this.m[15];
  1553. var om0 = other.m[0];
  1554. var om1 = other.m[1];
  1555. var om2 = other.m[2];
  1556. var om3 = other.m[3];
  1557. var om4 = other.m[4];
  1558. var om5 = other.m[5];
  1559. var om6 = other.m[6];
  1560. var om7 = other.m[7];
  1561. var om8 = other.m[8];
  1562. var om9 = other.m[9];
  1563. var om10 = other.m[10];
  1564. var om11 = other.m[11];
  1565. var om12 = other.m[12];
  1566. var om13 = other.m[13];
  1567. var om14 = other.m[14];
  1568. var om15 = other.m[15];
  1569. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1570. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1571. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1572. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1573. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1574. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1575. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1576. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1577. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1578. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1579. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1580. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1581. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1582. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1583. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1584. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1585. return this;
  1586. };
  1587. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1588. if (offset === void 0) { offset = 0; }
  1589. var tm = this.m;
  1590. var om = other.m;
  1591. var om0 = SIMD.float32x4.load(om, 0);
  1592. var om1 = SIMD.float32x4.load(om, 4);
  1593. var om2 = SIMD.float32x4.load(om, 8);
  1594. var om3 = SIMD.float32x4.load(om, 12);
  1595. var tm0 = SIMD.float32x4.load(tm, 0);
  1596. 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)))));
  1597. var tm1 = SIMD.float32x4.load(tm, 4);
  1598. 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)))));
  1599. var tm2 = SIMD.float32x4.load(tm, 8);
  1600. 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)))));
  1601. var tm3 = SIMD.float32x4.load(tm, 12);
  1602. 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)))));
  1603. };
  1604. Matrix.prototype.equals = function (value) {
  1605. 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]);
  1606. };
  1607. Matrix.prototype.clone = function () {
  1608. 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]);
  1609. };
  1610. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1611. translation.x = this.m[12];
  1612. translation.y = this.m[13];
  1613. translation.z = this.m[14];
  1614. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1615. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1616. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1617. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1618. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1619. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1620. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1621. rotation.x = 0;
  1622. rotation.y = 0;
  1623. rotation.z = 0;
  1624. rotation.w = 1;
  1625. return false;
  1626. }
  1627. 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);
  1628. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1629. return true;
  1630. };
  1631. // Statics
  1632. Matrix.FromArray = function (array, offset) {
  1633. var result = new Matrix();
  1634. if (!offset) {
  1635. offset = 0;
  1636. }
  1637. Matrix.FromArrayToRef(array, offset, result);
  1638. return result;
  1639. };
  1640. Matrix.FromArrayToRef = function (array, offset, result) {
  1641. for (var index = 0; index < 16; index++) {
  1642. result.m[index] = array[index + offset];
  1643. }
  1644. };
  1645. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1646. result.m[0] = initialM11;
  1647. result.m[1] = initialM12;
  1648. result.m[2] = initialM13;
  1649. result.m[3] = initialM14;
  1650. result.m[4] = initialM21;
  1651. result.m[5] = initialM22;
  1652. result.m[6] = initialM23;
  1653. result.m[7] = initialM24;
  1654. result.m[8] = initialM31;
  1655. result.m[9] = initialM32;
  1656. result.m[10] = initialM33;
  1657. result.m[11] = initialM34;
  1658. result.m[12] = initialM41;
  1659. result.m[13] = initialM42;
  1660. result.m[14] = initialM43;
  1661. result.m[15] = initialM44;
  1662. };
  1663. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1664. var result = new Matrix();
  1665. result.m[0] = initialM11;
  1666. result.m[1] = initialM12;
  1667. result.m[2] = initialM13;
  1668. result.m[3] = initialM14;
  1669. result.m[4] = initialM21;
  1670. result.m[5] = initialM22;
  1671. result.m[6] = initialM23;
  1672. result.m[7] = initialM24;
  1673. result.m[8] = initialM31;
  1674. result.m[9] = initialM32;
  1675. result.m[10] = initialM33;
  1676. result.m[11] = initialM34;
  1677. result.m[12] = initialM41;
  1678. result.m[13] = initialM42;
  1679. result.m[14] = initialM43;
  1680. result.m[15] = initialM44;
  1681. return result;
  1682. };
  1683. Matrix.Compose = function (scale, rotation, translation) {
  1684. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1685. var rotationMatrix = Matrix.Identity();
  1686. rotation.toRotationMatrix(rotationMatrix);
  1687. result = result.multiply(rotationMatrix);
  1688. result.setTranslation(translation);
  1689. return result;
  1690. };
  1691. Matrix.Identity = function () {
  1692. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1693. };
  1694. Matrix.IdentityToRef = function (result) {
  1695. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1696. };
  1697. Matrix.Zero = function () {
  1698. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1699. };
  1700. Matrix.RotationX = function (angle) {
  1701. var result = new Matrix();
  1702. Matrix.RotationXToRef(angle, result);
  1703. return result;
  1704. };
  1705. Matrix.Invert = function (source) {
  1706. var result = new Matrix();
  1707. source.invertToRef(result);
  1708. return result;
  1709. };
  1710. Matrix.RotationXToRef = function (angle, result) {
  1711. var s = Math.sin(angle);
  1712. var c = Math.cos(angle);
  1713. result.m[0] = 1.0;
  1714. result.m[15] = 1.0;
  1715. result.m[5] = c;
  1716. result.m[10] = c;
  1717. result.m[9] = -s;
  1718. result.m[6] = s;
  1719. result.m[1] = 0;
  1720. result.m[2] = 0;
  1721. result.m[3] = 0;
  1722. result.m[4] = 0;
  1723. result.m[7] = 0;
  1724. result.m[8] = 0;
  1725. result.m[11] = 0;
  1726. result.m[12] = 0;
  1727. result.m[13] = 0;
  1728. result.m[14] = 0;
  1729. };
  1730. Matrix.RotationY = function (angle) {
  1731. var result = new Matrix();
  1732. Matrix.RotationYToRef(angle, result);
  1733. return result;
  1734. };
  1735. Matrix.RotationYToRef = function (angle, result) {
  1736. var s = Math.sin(angle);
  1737. var c = Math.cos(angle);
  1738. result.m[5] = 1.0;
  1739. result.m[15] = 1.0;
  1740. result.m[0] = c;
  1741. result.m[2] = -s;
  1742. result.m[8] = s;
  1743. result.m[10] = c;
  1744. result.m[1] = 0;
  1745. result.m[3] = 0;
  1746. result.m[4] = 0;
  1747. result.m[6] = 0;
  1748. result.m[7] = 0;
  1749. result.m[9] = 0;
  1750. result.m[11] = 0;
  1751. result.m[12] = 0;
  1752. result.m[13] = 0;
  1753. result.m[14] = 0;
  1754. };
  1755. Matrix.RotationZ = function (angle) {
  1756. var result = new Matrix();
  1757. Matrix.RotationZToRef(angle, result);
  1758. return result;
  1759. };
  1760. Matrix.RotationZToRef = function (angle, result) {
  1761. var s = Math.sin(angle);
  1762. var c = Math.cos(angle);
  1763. result.m[10] = 1.0;
  1764. result.m[15] = 1.0;
  1765. result.m[0] = c;
  1766. result.m[1] = s;
  1767. result.m[4] = -s;
  1768. result.m[5] = c;
  1769. result.m[2] = 0;
  1770. result.m[3] = 0;
  1771. result.m[6] = 0;
  1772. result.m[7] = 0;
  1773. result.m[8] = 0;
  1774. result.m[9] = 0;
  1775. result.m[11] = 0;
  1776. result.m[12] = 0;
  1777. result.m[13] = 0;
  1778. result.m[14] = 0;
  1779. };
  1780. Matrix.RotationAxis = function (axis, angle) {
  1781. var s = Math.sin(-angle);
  1782. var c = Math.cos(-angle);
  1783. var c1 = 1 - c;
  1784. axis.normalize();
  1785. var result = Matrix.Zero();
  1786. result.m[0] = (axis.x * axis.x) * c1 + c;
  1787. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1788. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1789. result.m[3] = 0.0;
  1790. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1791. result.m[5] = (axis.y * axis.y) * c1 + c;
  1792. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1793. result.m[7] = 0.0;
  1794. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1795. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1796. result.m[10] = (axis.z * axis.z) * c1 + c;
  1797. result.m[11] = 0.0;
  1798. result.m[15] = 1.0;
  1799. return result;
  1800. };
  1801. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1802. var result = new Matrix();
  1803. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1804. return result;
  1805. };
  1806. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1807. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1808. this._tempQuaternion.toRotationMatrix(result);
  1809. };
  1810. Matrix.Scaling = function (x, y, z) {
  1811. var result = Matrix.Zero();
  1812. Matrix.ScalingToRef(x, y, z, result);
  1813. return result;
  1814. };
  1815. Matrix.ScalingToRef = function (x, y, z, result) {
  1816. result.m[0] = x;
  1817. result.m[1] = 0;
  1818. result.m[2] = 0;
  1819. result.m[3] = 0;
  1820. result.m[4] = 0;
  1821. result.m[5] = y;
  1822. result.m[6] = 0;
  1823. result.m[7] = 0;
  1824. result.m[8] = 0;
  1825. result.m[9] = 0;
  1826. result.m[10] = z;
  1827. result.m[11] = 0;
  1828. result.m[12] = 0;
  1829. result.m[13] = 0;
  1830. result.m[14] = 0;
  1831. result.m[15] = 1.0;
  1832. };
  1833. Matrix.Translation = function (x, y, z) {
  1834. var result = Matrix.Identity();
  1835. Matrix.TranslationToRef(x, y, z, result);
  1836. return result;
  1837. };
  1838. Matrix.TranslationToRef = function (x, y, z, result) {
  1839. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1840. };
  1841. Matrix.LookAtLH = function (eye, target, up) {
  1842. var result = Matrix.Zero();
  1843. Matrix.LookAtLHToRef(eye, target, up, result);
  1844. return result;
  1845. };
  1846. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1847. // Z axis
  1848. target.subtractToRef(eye, this._zAxis);
  1849. this._zAxis.normalize();
  1850. // X axis
  1851. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1852. this._xAxis.normalize();
  1853. // Y axis
  1854. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1855. this._yAxis.normalize();
  1856. // Eye angles
  1857. var ex = -Vector3.Dot(this._xAxis, eye);
  1858. var ey = -Vector3.Dot(this._yAxis, eye);
  1859. var ez = -Vector3.Dot(this._zAxis, eye);
  1860. 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);
  1861. };
  1862. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1863. var out = result.m;
  1864. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1865. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1866. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1867. // cc.kmVec3Subtract(f, pCenter, pEye);
  1868. var f = SIMD.float32x4.sub(center, eye);
  1869. // cc.kmVec3Normalize(f, f);
  1870. var tmp = SIMD.float32x4.mul(f, f);
  1871. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1872. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1873. // cc.kmVec3Assign(up, pUp);
  1874. // cc.kmVec3Normalize(up, up);
  1875. tmp = SIMD.float32x4.mul(up, up);
  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. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1878. // cc.kmVec3Cross(s, f, up);
  1879. 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)));
  1880. // cc.kmVec3Normalize(s, s);
  1881. tmp = SIMD.float32x4.mul(s, s);
  1882. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1883. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1884. // cc.kmVec3Cross(u, s, f);
  1885. 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)));
  1886. // cc.kmVec3Normalize(s, s);
  1887. tmp = SIMD.float32x4.mul(s, s);
  1888. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1889. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1890. var zero = SIMD.float32x4.splat(0.0);
  1891. s = SIMD.float32x4.neg(s);
  1892. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1893. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1894. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1895. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  1896. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  1897. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  1898. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1899. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  1900. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  1901. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  1902. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  1903. var b3 = SIMD.float32x4.neg(eye);
  1904. b3 = SIMD.float32x4.withW(b3, 1.0);
  1905. 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)))));
  1906. 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)))));
  1907. 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)))));
  1908. 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)))));
  1909. };
  1910. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1911. var matrix = Matrix.Zero();
  1912. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1913. return matrix;
  1914. };
  1915. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1916. var hw = 2.0 / width;
  1917. var hh = 2.0 / height;
  1918. var id = 1.0 / (zfar - znear);
  1919. var nid = znear / (znear - zfar);
  1920. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1921. };
  1922. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1923. var matrix = Matrix.Zero();
  1924. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1925. return matrix;
  1926. };
  1927. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1928. result.m[0] = 2.0 / (right - left);
  1929. result.m[1] = result.m[2] = result.m[3] = 0;
  1930. result.m[5] = 2.0 / (top - bottom);
  1931. result.m[4] = result.m[6] = result.m[7] = 0;
  1932. result.m[10] = -1.0 / (znear - zfar);
  1933. result.m[8] = result.m[9] = result.m[11] = 0;
  1934. result.m[12] = (left + right) / (left - right);
  1935. result.m[13] = (top + bottom) / (bottom - top);
  1936. result.m[14] = znear / (znear - zfar);
  1937. result.m[15] = 1.0;
  1938. };
  1939. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1940. var matrix = Matrix.Zero();
  1941. matrix.m[0] = (2.0 * znear) / width;
  1942. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1943. matrix.m[5] = (2.0 * znear) / height;
  1944. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1945. matrix.m[10] = -zfar / (znear - zfar);
  1946. matrix.m[8] = matrix.m[9] = 0.0;
  1947. matrix.m[11] = 1.0;
  1948. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1949. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1950. return matrix;
  1951. };
  1952. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1953. var matrix = Matrix.Zero();
  1954. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1955. return matrix;
  1956. };
  1957. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1958. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1959. var tan = 1.0 / (Math.tan(fov * 0.5));
  1960. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1961. if (v_fixed) {
  1962. result.m[0] = tan / aspect;
  1963. }
  1964. else {
  1965. result.m[0] = tan;
  1966. }
  1967. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1968. if (v_fixed) {
  1969. result.m[5] = tan;
  1970. }
  1971. else {
  1972. result.m[5] = tan * aspect;
  1973. }
  1974. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1975. result.m[8] = result.m[9] = 0.0;
  1976. result.m[10] = -zfar / (znear - zfar);
  1977. result.m[11] = 1.0;
  1978. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1979. result.m[14] = (znear * zfar) / (znear - zfar);
  1980. };
  1981. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1982. var cw = viewport.width;
  1983. var ch = viewport.height;
  1984. var cx = viewport.x;
  1985. var cy = viewport.y;
  1986. 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);
  1987. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1988. };
  1989. Matrix.Transpose = function (matrix) {
  1990. var result = new Matrix();
  1991. result.m[0] = matrix.m[0];
  1992. result.m[1] = matrix.m[4];
  1993. result.m[2] = matrix.m[8];
  1994. result.m[3] = matrix.m[12];
  1995. result.m[4] = matrix.m[1];
  1996. result.m[5] = matrix.m[5];
  1997. result.m[6] = matrix.m[9];
  1998. result.m[7] = matrix.m[13];
  1999. result.m[8] = matrix.m[2];
  2000. result.m[9] = matrix.m[6];
  2001. result.m[10] = matrix.m[10];
  2002. result.m[11] = matrix.m[14];
  2003. result.m[12] = matrix.m[3];
  2004. result.m[13] = matrix.m[7];
  2005. result.m[14] = matrix.m[11];
  2006. result.m[15] = matrix.m[15];
  2007. return result;
  2008. };
  2009. Matrix.Reflection = function (plane) {
  2010. var matrix = new Matrix();
  2011. Matrix.ReflectionToRef(plane, matrix);
  2012. return matrix;
  2013. };
  2014. Matrix.ReflectionToRef = function (plane, result) {
  2015. plane.normalize();
  2016. var x = plane.normal.x;
  2017. var y = plane.normal.y;
  2018. var z = plane.normal.z;
  2019. var temp = -2 * x;
  2020. var temp2 = -2 * y;
  2021. var temp3 = -2 * z;
  2022. result.m[0] = (temp * x) + 1;
  2023. result.m[1] = temp2 * x;
  2024. result.m[2] = temp3 * x;
  2025. result.m[3] = 0.0;
  2026. result.m[4] = temp * y;
  2027. result.m[5] = (temp2 * y) + 1;
  2028. result.m[6] = temp3 * y;
  2029. result.m[7] = 0.0;
  2030. result.m[8] = temp * z;
  2031. result.m[9] = temp2 * z;
  2032. result.m[10] = (temp3 * z) + 1;
  2033. result.m[11] = 0.0;
  2034. result.m[12] = temp * plane.d;
  2035. result.m[13] = temp2 * plane.d;
  2036. result.m[14] = temp3 * plane.d;
  2037. result.m[15] = 1.0;
  2038. };
  2039. Matrix._tempQuaternion = new Quaternion();
  2040. Matrix._xAxis = Vector3.Zero();
  2041. Matrix._yAxis = Vector3.Zero();
  2042. Matrix._zAxis = Vector3.Zero();
  2043. return Matrix;
  2044. })();
  2045. BABYLON.Matrix = Matrix;
  2046. var Plane = (function () {
  2047. function Plane(a, b, c, d) {
  2048. this.normal = new Vector3(a, b, c);
  2049. this.d = d;
  2050. }
  2051. Plane.prototype.asArray = function () {
  2052. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2053. };
  2054. // Methods
  2055. Plane.prototype.clone = function () {
  2056. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2057. };
  2058. Plane.prototype.normalize = function () {
  2059. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2060. var magnitude = 0;
  2061. if (norm !== 0) {
  2062. magnitude = 1.0 / norm;
  2063. }
  2064. this.normal.x *= magnitude;
  2065. this.normal.y *= magnitude;
  2066. this.normal.z *= magnitude;
  2067. this.d *= magnitude;
  2068. return this;
  2069. };
  2070. Plane.prototype.transform = function (transformation) {
  2071. var transposedMatrix = Matrix.Transpose(transformation);
  2072. var x = this.normal.x;
  2073. var y = this.normal.y;
  2074. var z = this.normal.z;
  2075. var d = this.d;
  2076. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2077. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2078. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2079. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2080. return new Plane(normalX, normalY, normalZ, finalD);
  2081. };
  2082. Plane.prototype.dotCoordinate = function (point) {
  2083. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2084. };
  2085. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2086. var x1 = point2.x - point1.x;
  2087. var y1 = point2.y - point1.y;
  2088. var z1 = point2.z - point1.z;
  2089. var x2 = point3.x - point1.x;
  2090. var y2 = point3.y - point1.y;
  2091. var z2 = point3.z - point1.z;
  2092. var yz = (y1 * z2) - (z1 * y2);
  2093. var xz = (z1 * x2) - (x1 * z2);
  2094. var xy = (x1 * y2) - (y1 * x2);
  2095. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2096. var invPyth;
  2097. if (pyth !== 0) {
  2098. invPyth = 1.0 / pyth;
  2099. }
  2100. else {
  2101. invPyth = 0;
  2102. }
  2103. this.normal.x = yz * invPyth;
  2104. this.normal.y = xz * invPyth;
  2105. this.normal.z = xy * invPyth;
  2106. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2107. return this;
  2108. };
  2109. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2110. var dot = Vector3.Dot(this.normal, direction);
  2111. return (dot <= epsilon);
  2112. };
  2113. Plane.prototype.signedDistanceTo = function (point) {
  2114. return Vector3.Dot(point, this.normal) + this.d;
  2115. };
  2116. // Statics
  2117. Plane.FromArray = function (array) {
  2118. return new Plane(array[0], array[1], array[2], array[3]);
  2119. };
  2120. Plane.FromPoints = function (point1, point2, point3) {
  2121. var result = new Plane(0, 0, 0, 0);
  2122. result.copyFromPoints(point1, point2, point3);
  2123. return result;
  2124. };
  2125. Plane.FromPositionAndNormal = function (origin, normal) {
  2126. var result = new Plane(0, 0, 0, 0);
  2127. normal.normalize();
  2128. result.normal = normal;
  2129. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2130. return result;
  2131. };
  2132. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2133. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2134. return Vector3.Dot(point, normal) + d;
  2135. };
  2136. return Plane;
  2137. })();
  2138. BABYLON.Plane = Plane;
  2139. var Viewport = (function () {
  2140. function Viewport(x, y, width, height) {
  2141. this.x = x;
  2142. this.y = y;
  2143. this.width = width;
  2144. this.height = height;
  2145. }
  2146. Viewport.prototype.toGlobal = function (engine) {
  2147. var width = engine.getRenderWidth();
  2148. var height = engine.getRenderHeight();
  2149. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2150. };
  2151. return Viewport;
  2152. })();
  2153. BABYLON.Viewport = Viewport;
  2154. var Frustum = (function () {
  2155. function Frustum() {
  2156. }
  2157. Frustum.GetPlanes = function (transform) {
  2158. var frustumPlanes = [];
  2159. for (var index = 0; index < 6; index++) {
  2160. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2161. }
  2162. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2163. return frustumPlanes;
  2164. };
  2165. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2166. // Near
  2167. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2168. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2169. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2170. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2171. frustumPlanes[0].normalize();
  2172. // Far
  2173. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2174. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2175. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2176. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2177. frustumPlanes[1].normalize();
  2178. // Left
  2179. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2180. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2181. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2182. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2183. frustumPlanes[2].normalize();
  2184. // Right
  2185. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2186. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2187. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2188. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2189. frustumPlanes[3].normalize();
  2190. // Top
  2191. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2192. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2193. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2194. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2195. frustumPlanes[4].normalize();
  2196. // Bottom
  2197. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2198. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2199. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2200. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2201. frustumPlanes[5].normalize();
  2202. };
  2203. return Frustum;
  2204. })();
  2205. BABYLON.Frustum = Frustum;
  2206. var Ray = (function () {
  2207. function Ray(origin, direction, length) {
  2208. if (length === void 0) { length = Number.MAX_VALUE; }
  2209. this.origin = origin;
  2210. this.direction = direction;
  2211. this.length = length;
  2212. }
  2213. // Methods
  2214. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2215. var d = 0.0;
  2216. var maxValue = Number.MAX_VALUE;
  2217. if (Math.abs(this.direction.x) < 0.0000001) {
  2218. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2219. return false;
  2220. }
  2221. }
  2222. else {
  2223. var inv = 1.0 / this.direction.x;
  2224. var min = (minimum.x - this.origin.x) * inv;
  2225. var max = (maximum.x - this.origin.x) * inv;
  2226. if (max === -Infinity) {
  2227. max = Infinity;
  2228. }
  2229. if (min > max) {
  2230. var temp = min;
  2231. min = max;
  2232. max = temp;
  2233. }
  2234. d = Math.max(min, d);
  2235. maxValue = Math.min(max, maxValue);
  2236. if (d > maxValue) {
  2237. return false;
  2238. }
  2239. }
  2240. if (Math.abs(this.direction.y) < 0.0000001) {
  2241. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2242. return false;
  2243. }
  2244. }
  2245. else {
  2246. inv = 1.0 / this.direction.y;
  2247. min = (minimum.y - this.origin.y) * inv;
  2248. max = (maximum.y - this.origin.y) * inv;
  2249. if (max === -Infinity) {
  2250. max = Infinity;
  2251. }
  2252. if (min > max) {
  2253. temp = min;
  2254. min = max;
  2255. max = temp;
  2256. }
  2257. d = Math.max(min, d);
  2258. maxValue = Math.min(max, maxValue);
  2259. if (d > maxValue) {
  2260. return false;
  2261. }
  2262. }
  2263. if (Math.abs(this.direction.z) < 0.0000001) {
  2264. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2265. return false;
  2266. }
  2267. }
  2268. else {
  2269. inv = 1.0 / this.direction.z;
  2270. min = (minimum.z - this.origin.z) * inv;
  2271. max = (maximum.z - this.origin.z) * inv;
  2272. if (max === -Infinity) {
  2273. max = Infinity;
  2274. }
  2275. if (min > max) {
  2276. temp = min;
  2277. min = max;
  2278. max = temp;
  2279. }
  2280. d = Math.max(min, d);
  2281. maxValue = Math.min(max, maxValue);
  2282. if (d > maxValue) {
  2283. return false;
  2284. }
  2285. }
  2286. return true;
  2287. };
  2288. Ray.prototype.intersectsBox = function (box) {
  2289. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2290. };
  2291. Ray.prototype.intersectsSphere = function (sphere) {
  2292. var x = sphere.center.x - this.origin.x;
  2293. var y = sphere.center.y - this.origin.y;
  2294. var z = sphere.center.z - this.origin.z;
  2295. var pyth = (x * x) + (y * y) + (z * z);
  2296. var rr = sphere.radius * sphere.radius;
  2297. if (pyth <= rr) {
  2298. return true;
  2299. }
  2300. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2301. if (dot < 0.0) {
  2302. return false;
  2303. }
  2304. var temp = pyth - (dot * dot);
  2305. return temp <= rr;
  2306. };
  2307. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2308. if (!this._edge1) {
  2309. this._edge1 = Vector3.Zero();
  2310. this._edge2 = Vector3.Zero();
  2311. this._pvec = Vector3.Zero();
  2312. this._tvec = Vector3.Zero();
  2313. this._qvec = Vector3.Zero();
  2314. }
  2315. vertex1.subtractToRef(vertex0, this._edge1);
  2316. vertex2.subtractToRef(vertex0, this._edge2);
  2317. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2318. var det = Vector3.Dot(this._edge1, this._pvec);
  2319. if (det === 0) {
  2320. return null;
  2321. }
  2322. var invdet = 1 / det;
  2323. this.origin.subtractToRef(vertex0, this._tvec);
  2324. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2325. if (bu < 0 || bu > 1.0) {
  2326. return null;
  2327. }
  2328. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2329. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2330. if (bv < 0 || bu + bv > 1.0) {
  2331. return null;
  2332. }
  2333. //check if the distance is longer than the predefined length.
  2334. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2335. if (distance > this.length) {
  2336. return null;
  2337. }
  2338. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2339. };
  2340. // Statics
  2341. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2342. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2343. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2344. var direction = end.subtract(start);
  2345. direction.normalize();
  2346. return new Ray(start, direction);
  2347. };
  2348. /**
  2349. * 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
  2350. * transformed to the given world matrix.
  2351. * @param origin The origin point
  2352. * @param end The end point
  2353. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2354. */
  2355. Ray.CreateNewFromTo = function (origin, end, world) {
  2356. if (world === void 0) { world = Matrix.Identity(); }
  2357. var direction = end.subtract(origin);
  2358. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2359. direction.normalize();
  2360. return Ray.Transform(new Ray(origin, direction, length), world);
  2361. };
  2362. Ray.Transform = function (ray, matrix) {
  2363. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2364. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2365. return new Ray(newOrigin, newDirection, ray.length);
  2366. };
  2367. return Ray;
  2368. })();
  2369. BABYLON.Ray = Ray;
  2370. (function (Space) {
  2371. Space[Space["LOCAL"] = 0] = "LOCAL";
  2372. Space[Space["WORLD"] = 1] = "WORLD";
  2373. })(BABYLON.Space || (BABYLON.Space = {}));
  2374. var Space = BABYLON.Space;
  2375. var Axis = (function () {
  2376. function Axis() {
  2377. }
  2378. Axis.X = new Vector3(1, 0, 0);
  2379. Axis.Y = new Vector3(0, 1, 0);
  2380. Axis.Z = new Vector3(0, 0, 1);
  2381. return Axis;
  2382. })();
  2383. BABYLON.Axis = Axis;
  2384. ;
  2385. var BezierCurve = (function () {
  2386. function BezierCurve() {
  2387. }
  2388. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2389. // Extract X (which is equal to time here)
  2390. var f0 = 1 - 3 * x2 + 3 * x1;
  2391. var f1 = 3 * x2 - 6 * x1;
  2392. var f2 = 3 * x1;
  2393. var refinedT = t;
  2394. for (var i = 0; i < 5; i++) {
  2395. var refinedT2 = refinedT * refinedT;
  2396. var refinedT3 = refinedT2 * refinedT;
  2397. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2398. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2399. refinedT -= (x - t) * slope;
  2400. refinedT = Math.min(1, Math.max(0, refinedT));
  2401. }
  2402. // Resolve cubic bezier for the given x
  2403. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2404. };
  2405. return BezierCurve;
  2406. })();
  2407. BABYLON.BezierCurve = BezierCurve;
  2408. (function (Orientation) {
  2409. Orientation[Orientation["CW"] = 0] = "CW";
  2410. Orientation[Orientation["CCW"] = 1] = "CCW";
  2411. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2412. var Orientation = BABYLON.Orientation;
  2413. var Angle = (function () {
  2414. function Angle(radians) {
  2415. var _this = this;
  2416. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2417. this.radians = function () { return _this._radians; };
  2418. this._radians = radians;
  2419. if (this._radians < 0)
  2420. this._radians += (2 * Math.PI);
  2421. }
  2422. Angle.BetweenTwoPoints = function (a, b) {
  2423. var delta = b.subtract(a);
  2424. var theta = Math.atan2(delta.y, delta.x);
  2425. return new Angle(theta);
  2426. };
  2427. Angle.FromRadians = function (radians) {
  2428. return new Angle(radians);
  2429. };
  2430. Angle.FromDegrees = function (degrees) {
  2431. return new Angle(degrees * Math.PI / 180);
  2432. };
  2433. return Angle;
  2434. })();
  2435. BABYLON.Angle = Angle;
  2436. var Arc2 = (function () {
  2437. function Arc2(startPoint, midPoint, endPoint) {
  2438. this.startPoint = startPoint;
  2439. this.midPoint = midPoint;
  2440. this.endPoint = endPoint;
  2441. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2442. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2443. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2444. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2445. 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);
  2446. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2447. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2448. var a1 = this.startAngle.degrees();
  2449. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2450. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2451. // angles correction
  2452. if (a2 - a1 > +180.0)
  2453. a2 -= 360.0;
  2454. if (a2 - a1 < -180.0)
  2455. a2 += 360.0;
  2456. if (a3 - a2 > +180.0)
  2457. a3 -= 360.0;
  2458. if (a3 - a2 < -180.0)
  2459. a3 += 360.0;
  2460. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2461. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2462. }
  2463. return Arc2;
  2464. })();
  2465. BABYLON.Arc2 = Arc2;
  2466. var PathCursor = (function () {
  2467. function PathCursor(path) {
  2468. this.path = path;
  2469. this._onchange = new Array();
  2470. this.value = 0;
  2471. this.animations = new Array();
  2472. }
  2473. PathCursor.prototype.getPoint = function () {
  2474. var point = this.path.getPointAtLengthPosition(this.value);
  2475. return new Vector3(point.x, 0, point.y);
  2476. };
  2477. PathCursor.prototype.moveAhead = function (step) {
  2478. if (step === void 0) { step = 0.002; }
  2479. this.move(step);
  2480. return this;
  2481. };
  2482. PathCursor.prototype.moveBack = function (step) {
  2483. if (step === void 0) { step = 0.002; }
  2484. this.move(-step);
  2485. return this;
  2486. };
  2487. PathCursor.prototype.move = function (step) {
  2488. if (Math.abs(step) > 1) {
  2489. throw "step size should be less than 1.";
  2490. }
  2491. this.value += step;
  2492. this.ensureLimits();
  2493. this.raiseOnChange();
  2494. return this;
  2495. };
  2496. PathCursor.prototype.ensureLimits = function () {
  2497. while (this.value > 1) {
  2498. this.value -= 1;
  2499. }
  2500. while (this.value < 0) {
  2501. this.value += 1;
  2502. }
  2503. return this;
  2504. };
  2505. // used by animation engine
  2506. PathCursor.prototype.markAsDirty = function (propertyName) {
  2507. this.ensureLimits();
  2508. this.raiseOnChange();
  2509. return this;
  2510. };
  2511. PathCursor.prototype.raiseOnChange = function () {
  2512. var _this = this;
  2513. this._onchange.forEach(function (f) { return f(_this); });
  2514. return this;
  2515. };
  2516. PathCursor.prototype.onchange = function (f) {
  2517. this._onchange.push(f);
  2518. return this;
  2519. };
  2520. return PathCursor;
  2521. })();
  2522. BABYLON.PathCursor = PathCursor;
  2523. var Path2 = (function () {
  2524. function Path2(x, y) {
  2525. this._points = new Array();
  2526. this._length = 0;
  2527. this.closed = false;
  2528. this._points.push(new Vector2(x, y));
  2529. }
  2530. Path2.prototype.addLineTo = function (x, y) {
  2531. if (closed) {
  2532. BABYLON.Tools.Error("cannot add lines to closed paths");
  2533. return this;
  2534. }
  2535. var newPoint = new Vector2(x, y);
  2536. var previousPoint = this._points[this._points.length - 1];
  2537. this._points.push(newPoint);
  2538. this._length += newPoint.subtract(previousPoint).length();
  2539. return this;
  2540. };
  2541. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2542. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2543. if (closed) {
  2544. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2545. return this;
  2546. }
  2547. var startPoint = this._points[this._points.length - 1];
  2548. var midPoint = new Vector2(midX, midY);
  2549. var endPoint = new Vector2(endX, endY);
  2550. var arc = new Arc2(startPoint, midPoint, endPoint);
  2551. var increment = arc.angle.radians() / numberOfSegments;
  2552. if (arc.orientation === 0 /* CW */)
  2553. increment *= -1;
  2554. var currentAngle = arc.startAngle.radians() + increment;
  2555. for (var i = 0; i < numberOfSegments; i++) {
  2556. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2557. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2558. this.addLineTo(x, y);
  2559. currentAngle += increment;
  2560. }
  2561. return this;
  2562. };
  2563. Path2.prototype.close = function () {
  2564. this.closed = true;
  2565. return this;
  2566. };
  2567. Path2.prototype.length = function () {
  2568. var result = this._length;
  2569. if (!this.closed) {
  2570. var lastPoint = this._points[this._points.length - 1];
  2571. var firstPoint = this._points[0];
  2572. result += (firstPoint.subtract(lastPoint).length());
  2573. }
  2574. return result;
  2575. };
  2576. Path2.prototype.getPoints = function () {
  2577. return this._points;
  2578. };
  2579. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2580. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2581. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2582. return Vector2.Zero();
  2583. }
  2584. var lengthPosition = normalizedLengthPosition * this.length();
  2585. var previousOffset = 0;
  2586. for (var i = 0; i < this._points.length; i++) {
  2587. var j = (i + 1) % this._points.length;
  2588. var a = this._points[i];
  2589. var b = this._points[j];
  2590. var bToA = b.subtract(a);
  2591. var nextOffset = (bToA.length() + previousOffset);
  2592. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2593. var dir = bToA.normalize();
  2594. var localOffset = lengthPosition - previousOffset;
  2595. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2596. }
  2597. previousOffset = nextOffset;
  2598. }
  2599. BABYLON.Tools.Error("internal error");
  2600. return Vector2.Zero();
  2601. };
  2602. Path2.StartingAt = function (x, y) {
  2603. return new Path2(x, y);
  2604. };
  2605. return Path2;
  2606. })();
  2607. BABYLON.Path2 = Path2;
  2608. var Path3D = (function () {
  2609. function Path3D(path, firstNormal) {
  2610. this.path = path;
  2611. this._curve = new Array();
  2612. this._distances = new Array();
  2613. this._tangents = new Array();
  2614. this._normals = new Array();
  2615. this._binormals = new Array();
  2616. for (var p = 0; p < path.length; p++) {
  2617. this._curve[p] = path[p].clone(); // hard copy
  2618. }
  2619. this._compute(firstNormal);
  2620. }
  2621. Path3D.prototype.getCurve = function () {
  2622. return this._curve;
  2623. };
  2624. Path3D.prototype.getTangents = function () {
  2625. return this._tangents;
  2626. };
  2627. Path3D.prototype.getNormals = function () {
  2628. return this._normals;
  2629. };
  2630. Path3D.prototype.getBinormals = function () {
  2631. return this._binormals;
  2632. };
  2633. Path3D.prototype.getDistances = function () {
  2634. return this._distances;
  2635. };
  2636. Path3D.prototype.update = function (path, firstNormal) {
  2637. for (var p = 0; p < path.length; p++) {
  2638. this._curve[p].x = path[p].x;
  2639. this._curve[p].y = path[p].y;
  2640. this._curve[p].z = path[p].z;
  2641. }
  2642. this._compute(firstNormal);
  2643. return this;
  2644. };
  2645. // private function compute() : computes tangents, normals and binormals
  2646. Path3D.prototype._compute = function (firstNormal) {
  2647. var l = this._curve.length;
  2648. // first and last tangents
  2649. this._tangents[0] = this._getFirstNonNullVector(0);
  2650. this._tangents[0].normalize();
  2651. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2652. this._tangents[l - 1].normalize();
  2653. // normals and binormals at first point : arbitrary vector with _normalVector()
  2654. var tg0 = this._tangents[0];
  2655. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2656. this._normals[0] = pp0;
  2657. this._normals[0].normalize();
  2658. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2659. this._binormals[0].normalize();
  2660. this._distances[0] = 0;
  2661. // normals and binormals : next points
  2662. var prev; // previous vector (segment)
  2663. var cur; // current vector (segment)
  2664. var curTang; // current tangent
  2665. var prevNorm; // previous normal
  2666. var prevBinor; // previous binormal
  2667. for (var i = 1; i < l; i++) {
  2668. // tangents
  2669. prev = this._getLastNonNullVector(i);
  2670. if (i < l - 1) {
  2671. cur = this._getFirstNonNullVector(i);
  2672. this._tangents[i] = prev.add(cur);
  2673. this._tangents[i].normalize();
  2674. }
  2675. this._distances[i] = this._distances[i - 1] + prev.length();
  2676. // normals and binormals
  2677. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2678. curTang = this._tangents[i];
  2679. prevNorm = this._normals[i - 1];
  2680. prevBinor = this._binormals[i - 1];
  2681. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2682. this._normals[i].normalize();
  2683. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2684. this._binormals[i].normalize();
  2685. }
  2686. };
  2687. // private function getFirstNonNullVector(index)
  2688. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2689. Path3D.prototype._getFirstNonNullVector = function (index) {
  2690. var i = 1;
  2691. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2692. while (nNVector.length() == 0 && index + i + 1 < this._curve.length) {
  2693. i++;
  2694. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2695. }
  2696. return nNVector;
  2697. };
  2698. // private function getLastNonNullVector(index)
  2699. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2700. Path3D.prototype._getLastNonNullVector = function (index) {
  2701. var i = 1;
  2702. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2703. while (nLVector.length() == 0 && index > i + 1) {
  2704. i++;
  2705. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2706. }
  2707. return nLVector;
  2708. };
  2709. // private function normalVector(v0, vt, va) :
  2710. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2711. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2712. Path3D.prototype._normalVector = function (v0, vt, va) {
  2713. var normal0;
  2714. if (va === undefined || va === null) {
  2715. var point;
  2716. if (vt.x !== 1) {
  2717. point = new Vector3(1, 0, 0);
  2718. }
  2719. else if (vt.y !== 1) {
  2720. point = new Vector3(0, 1, 0);
  2721. }
  2722. else if (vt.z !== 1) {
  2723. point = new Vector3(0, 0, 1);
  2724. }
  2725. normal0 = Vector3.Cross(vt, point);
  2726. }
  2727. else {
  2728. normal0 = Vector3.Cross(vt, va);
  2729. Vector3.CrossToRef(normal0, vt, normal0);
  2730. }
  2731. normal0.normalize();
  2732. return normal0;
  2733. };
  2734. return Path3D;
  2735. })();
  2736. BABYLON.Path3D = Path3D;
  2737. var Curve3 = (function () {
  2738. function Curve3(points) {
  2739. this._length = 0;
  2740. this._points = points;
  2741. this._length = this._computeLength(points);
  2742. }
  2743. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2744. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2745. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2746. var bez = new Array();
  2747. var equation = function (t, val0, val1, val2) {
  2748. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2749. return res;
  2750. };
  2751. for (var i = 0; i <= nbPoints; i++) {
  2752. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2753. }
  2754. return new Curve3(bez);
  2755. };
  2756. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2757. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2758. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2759. var bez = new Array();
  2760. var equation = function (t, val0, val1, val2, val3) {
  2761. 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;
  2762. return res;
  2763. };
  2764. for (var i = 0; i <= nbPoints; i++) {
  2765. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2766. }
  2767. return new Curve3(bez);
  2768. };
  2769. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2770. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2771. var hermite = new Array();
  2772. var step = 1 / nbPoints;
  2773. for (var i = 0; i <= nbPoints; i++) {
  2774. hermite.push(BABYLON.Vector3.Hermite(p1, t1, p2, t2, i * step));
  2775. }
  2776. return new Curve3(hermite);
  2777. };
  2778. Curve3.prototype.getPoints = function () {
  2779. return this._points;
  2780. };
  2781. Curve3.prototype.length = function () {
  2782. return this._length;
  2783. };
  2784. Curve3.prototype.continue = function (curve) {
  2785. var lastPoint = this._points[this._points.length - 1];
  2786. var continuedPoints = this._points.slice();
  2787. var curvePoints = curve.getPoints();
  2788. for (var i = 1; i < curvePoints.length; i++) {
  2789. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2790. }
  2791. var continuedCurve = new Curve3(continuedPoints);
  2792. return continuedCurve;
  2793. };
  2794. Curve3.prototype._computeLength = function (path) {
  2795. var l = 0;
  2796. for (var i = 1; i < path.length; i++) {
  2797. l += (path[i].subtract(path[i - 1])).length();
  2798. }
  2799. return l;
  2800. };
  2801. return Curve3;
  2802. })();
  2803. BABYLON.Curve3 = Curve3;
  2804. // Vertex formats
  2805. var PositionNormalVertex = (function () {
  2806. function PositionNormalVertex(position, normal) {
  2807. if (position === void 0) { position = Vector3.Zero(); }
  2808. if (normal === void 0) { normal = Vector3.Up(); }
  2809. this.position = position;
  2810. this.normal = normal;
  2811. }
  2812. PositionNormalVertex.prototype.clone = function () {
  2813. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2814. };
  2815. return PositionNormalVertex;
  2816. })();
  2817. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2818. var PositionNormalTextureVertex = (function () {
  2819. function PositionNormalTextureVertex(position, normal, uv) {
  2820. if (position === void 0) { position = Vector3.Zero(); }
  2821. if (normal === void 0) { normal = Vector3.Up(); }
  2822. if (uv === void 0) { uv = Vector2.Zero(); }
  2823. this.position = position;
  2824. this.normal = normal;
  2825. this.uv = uv;
  2826. }
  2827. PositionNormalTextureVertex.prototype.clone = function () {
  2828. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2829. };
  2830. return PositionNormalTextureVertex;
  2831. })();
  2832. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2833. // SIMD
  2834. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2835. var previousInvertToRef = Matrix.prototype.invertToRef;
  2836. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2837. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2838. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2839. var SIMDHelper = (function () {
  2840. function SIMDHelper() {
  2841. }
  2842. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2843. get: function () {
  2844. return SIMDHelper._isEnabled;
  2845. },
  2846. enumerable: true,
  2847. configurable: true
  2848. });
  2849. SIMDHelper.DisableSIMD = function () {
  2850. // Replace functions
  2851. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2852. Matrix.prototype.invertToRef = previousInvertToRef;
  2853. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2854. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2855. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2856. SIMDHelper._isEnabled = false;
  2857. };
  2858. SIMDHelper.EnableSIMD = function () {
  2859. if (window.SIMD === undefined) {
  2860. return;
  2861. }
  2862. // Replace functions
  2863. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2864. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2865. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2866. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2867. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2868. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2869. get: function () {
  2870. return this._data[0];
  2871. },
  2872. set: function (value) {
  2873. if (!this._data) {
  2874. this._data = new Float32Array(3);
  2875. }
  2876. this._data[0] = value;
  2877. }
  2878. });
  2879. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2880. get: function () {
  2881. return this._data[1];
  2882. },
  2883. set: function (value) {
  2884. this._data[1] = value;
  2885. }
  2886. });
  2887. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2888. get: function () {
  2889. return this._data[2];
  2890. },
  2891. set: function (value) {
  2892. this._data[2] = value;
  2893. }
  2894. });
  2895. SIMDHelper._isEnabled = true;
  2896. };
  2897. SIMDHelper._isEnabled = false;
  2898. return SIMDHelper;
  2899. })();
  2900. BABYLON.SIMDHelper = SIMDHelper;
  2901. if (window.SIMD !== undefined) {
  2902. SIMDHelper.EnableSIMD();
  2903. }
  2904. })(BABYLON || (BABYLON = {}));
  2905. //# sourceMappingURL=babylon.math.js.map
  2906. var BABYLON;
  2907. (function (BABYLON) {
  2908. var Database = (function () {
  2909. function Database(urlToScene, callbackManifestChecked) {
  2910. // Handling various flavors of prefixed version of IndexedDB
  2911. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2912. this.callbackManifestChecked = callbackManifestChecked;
  2913. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  2914. this.db = null;
  2915. this.enableSceneOffline = false;
  2916. this.enableTexturesOffline = false;
  2917. this.manifestVersionFound = 0;
  2918. this.mustUpdateRessources = false;
  2919. this.hasReachedQuota = false;
  2920. this.checkManifestFile();
  2921. }
  2922. Database.prototype.checkManifestFile = function () {
  2923. var _this = this;
  2924. function noManifestFile() {
  2925. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  2926. that.enableSceneOffline = false;
  2927. that.enableTexturesOffline = false;
  2928. that.callbackManifestChecked(false);
  2929. }
  2930. var that = this;
  2931. var manifestURL = this.currentSceneUrl + ".manifest";
  2932. var xhr = new XMLHttpRequest();
  2933. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  2934. xhr.open("GET", manifestURLTimeStamped, true);
  2935. xhr.addEventListener("load", function () {
  2936. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  2937. try {
  2938. var manifestFile = JSON.parse(xhr.response);
  2939. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  2940. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  2941. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  2942. _this.manifestVersionFound = manifestFile.version;
  2943. }
  2944. if (_this.callbackManifestChecked) {
  2945. _this.callbackManifestChecked(true);
  2946. }
  2947. }
  2948. catch (ex) {
  2949. noManifestFile();
  2950. }
  2951. }
  2952. else {
  2953. noManifestFile();
  2954. }
  2955. }, false);
  2956. xhr.addEventListener("error", function (event) {
  2957. noManifestFile();
  2958. }, false);
  2959. try {
  2960. xhr.send();
  2961. }
  2962. catch (ex) {
  2963. BABYLON.Tools.Error("Error on XHR send request.");
  2964. that.callbackManifestChecked(false);
  2965. }
  2966. };
  2967. Database.prototype.openAsync = function (successCallback, errorCallback) {
  2968. var _this = this;
  2969. function handleError() {
  2970. that.isSupported = false;
  2971. if (errorCallback)
  2972. errorCallback();
  2973. }
  2974. var that = this;
  2975. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  2976. // Your browser doesn't support IndexedDB
  2977. this.isSupported = false;
  2978. if (errorCallback)
  2979. errorCallback();
  2980. }
  2981. else {
  2982. // If the DB hasn't been opened or created yet
  2983. if (!this.db) {
  2984. this.hasReachedQuota = false;
  2985. this.isSupported = true;
  2986. var request = this.idbFactory.open("babylonjs", 1);
  2987. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  2988. request.onerror = function (event) {
  2989. handleError();
  2990. };
  2991. // executes when a version change transaction cannot complete due to other active transactions
  2992. request.onblocked = function (event) {
  2993. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  2994. handleError();
  2995. };
  2996. // DB has been opened successfully
  2997. request.onsuccess = function (event) {
  2998. _this.db = request.result;
  2999. successCallback();
  3000. };
  3001. // Initialization of the DB. Creating Scenes & Textures stores
  3002. request.onupgradeneeded = function (event) {
  3003. _this.db = (event.target).result;
  3004. try {
  3005. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3006. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3007. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3008. }
  3009. catch (ex) {
  3010. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3011. handleError();
  3012. }
  3013. };
  3014. }
  3015. else {
  3016. if (successCallback)
  3017. successCallback();
  3018. }
  3019. }
  3020. };
  3021. Database.prototype.loadImageFromDB = function (url, image) {
  3022. var _this = this;
  3023. var completeURL = Database.ReturnFullUrlLocation(url);
  3024. var saveAndLoadImage = function () {
  3025. if (!_this.hasReachedQuota && _this.db !== null) {
  3026. // the texture is not yet in the DB, let's try to save it
  3027. _this._saveImageIntoDBAsync(completeURL, image);
  3028. }
  3029. else {
  3030. image.src = url;
  3031. }
  3032. };
  3033. if (!this.mustUpdateRessources) {
  3034. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3035. }
  3036. else {
  3037. saveAndLoadImage();
  3038. }
  3039. };
  3040. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3041. if (this.isSupported && this.db !== null) {
  3042. var texture;
  3043. var transaction = this.db.transaction(["textures"]);
  3044. transaction.onabort = function (event) {
  3045. image.src = url;
  3046. };
  3047. transaction.oncomplete = function (event) {
  3048. var blobTextureURL;
  3049. if (texture) {
  3050. var URL = window.URL || window.webkitURL;
  3051. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3052. image.onerror = function () {
  3053. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3054. image.src = url;
  3055. };
  3056. image.src = blobTextureURL;
  3057. }
  3058. else {
  3059. notInDBCallback();
  3060. }
  3061. };
  3062. var getRequest = transaction.objectStore("textures").get(url);
  3063. getRequest.onsuccess = function (event) {
  3064. texture = (event.target).result;
  3065. };
  3066. getRequest.onerror = function (event) {
  3067. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3068. image.src = url;
  3069. };
  3070. }
  3071. else {
  3072. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3073. image.src = url;
  3074. }
  3075. };
  3076. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3077. var _this = this;
  3078. if (this.isSupported) {
  3079. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3080. var generateBlobUrl = function () {
  3081. var blobTextureURL;
  3082. if (blob) {
  3083. var URL = window.URL || window.webkitURL;
  3084. try {
  3085. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3086. }
  3087. catch (ex) {
  3088. blobTextureURL = URL.createObjectURL(blob);
  3089. }
  3090. }
  3091. image.src = blobTextureURL;
  3092. };
  3093. if (Database.isUASupportingBlobStorage) {
  3094. var xhr = new XMLHttpRequest(), blob;
  3095. xhr.open("GET", url, true);
  3096. xhr.responseType = "blob";
  3097. xhr.addEventListener("load", function () {
  3098. if (xhr.status === 200) {
  3099. // Blob as response (XHR2)
  3100. blob = xhr.response;
  3101. var transaction = _this.db.transaction(["textures"], "readwrite");
  3102. // the transaction could abort because of a QuotaExceededError error
  3103. transaction.onabort = function (event) {
  3104. try {
  3105. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3106. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3107. this.hasReachedQuota = true;
  3108. }
  3109. }
  3110. catch (ex) {
  3111. }
  3112. generateBlobUrl();
  3113. };
  3114. transaction.oncomplete = function (event) {
  3115. generateBlobUrl();
  3116. };
  3117. var newTexture = { textureUrl: url, data: blob };
  3118. try {
  3119. // Put the blob into the dabase
  3120. var addRequest = transaction.objectStore("textures").put(newTexture);
  3121. addRequest.onsuccess = function (event) {
  3122. };
  3123. addRequest.onerror = function (event) {
  3124. generateBlobUrl();
  3125. };
  3126. }
  3127. catch (ex) {
  3128. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3129. if (ex.code === 25) {
  3130. Database.isUASupportingBlobStorage = false;
  3131. }
  3132. image.src = url;
  3133. }
  3134. }
  3135. else {
  3136. image.src = url;
  3137. }
  3138. }, false);
  3139. xhr.addEventListener("error", function (event) {
  3140. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3141. image.src = url;
  3142. }, false);
  3143. xhr.send();
  3144. }
  3145. else {
  3146. image.src = url;
  3147. }
  3148. }
  3149. else {
  3150. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3151. image.src = url;
  3152. }
  3153. };
  3154. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3155. var _this = this;
  3156. var updateVersion = function (event) {
  3157. // the version is not yet in the DB or we need to update it
  3158. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3159. };
  3160. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3161. };
  3162. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3163. var _this = this;
  3164. if (this.isSupported) {
  3165. var version;
  3166. try {
  3167. var transaction = this.db.transaction(["versions"]);
  3168. transaction.oncomplete = function (event) {
  3169. if (version) {
  3170. // If the version in the JSON file is > than the version in DB
  3171. if (_this.manifestVersionFound > version.data) {
  3172. _this.mustUpdateRessources = true;
  3173. updateInDBCallback();
  3174. }
  3175. else {
  3176. callback(version.data);
  3177. }
  3178. }
  3179. else {
  3180. _this.mustUpdateRessources = true;
  3181. updateInDBCallback();
  3182. }
  3183. };
  3184. transaction.onabort = function (event) {
  3185. callback(-1);
  3186. };
  3187. var getRequest = transaction.objectStore("versions").get(url);
  3188. getRequest.onsuccess = function (event) {
  3189. version = (event.target).result;
  3190. };
  3191. getRequest.onerror = function (event) {
  3192. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3193. callback(-1);
  3194. };
  3195. }
  3196. catch (ex) {
  3197. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3198. callback(-1);
  3199. }
  3200. }
  3201. else {
  3202. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3203. callback(-1);
  3204. }
  3205. };
  3206. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3207. var _this = this;
  3208. if (this.isSupported && !this.hasReachedQuota) {
  3209. try {
  3210. // Open a transaction to the database
  3211. var transaction = this.db.transaction(["versions"], "readwrite");
  3212. // the transaction could abort because of a QuotaExceededError error
  3213. transaction.onabort = function (event) {
  3214. try {
  3215. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3216. _this.hasReachedQuota = true;
  3217. }
  3218. }
  3219. catch (ex) {
  3220. }
  3221. callback(-1);
  3222. };
  3223. transaction.oncomplete = function (event) {
  3224. callback(_this.manifestVersionFound);
  3225. };
  3226. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3227. // Put the scene into the database
  3228. var addRequest = transaction.objectStore("versions").put(newVersion);
  3229. addRequest.onsuccess = function (event) {
  3230. };
  3231. addRequest.onerror = function (event) {
  3232. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3233. };
  3234. }
  3235. catch (ex) {
  3236. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3237. callback(-1);
  3238. }
  3239. }
  3240. else {
  3241. callback(-1);
  3242. }
  3243. };
  3244. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3245. var _this = this;
  3246. var completeUrl = Database.ReturnFullUrlLocation(url);
  3247. var saveAndLoadFile = function (event) {
  3248. // the scene is not yet in the DB, let's try to save it
  3249. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3250. };
  3251. this._checkVersionFromDB(completeUrl, function (version) {
  3252. if (version !== -1) {
  3253. if (!_this.mustUpdateRessources) {
  3254. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3255. }
  3256. else {
  3257. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3258. }
  3259. }
  3260. else {
  3261. errorCallback();
  3262. }
  3263. });
  3264. };
  3265. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3266. if (this.isSupported) {
  3267. var targetStore;
  3268. if (url.indexOf(".babylon") !== -1) {
  3269. targetStore = "scenes";
  3270. }
  3271. else {
  3272. targetStore = "textures";
  3273. }
  3274. var file;
  3275. var transaction = this.db.transaction([targetStore]);
  3276. transaction.oncomplete = function (event) {
  3277. if (file) {
  3278. callback(file.data);
  3279. }
  3280. else {
  3281. notInDBCallback();
  3282. }
  3283. };
  3284. transaction.onabort = function (event) {
  3285. notInDBCallback();
  3286. };
  3287. var getRequest = transaction.objectStore(targetStore).get(url);
  3288. getRequest.onsuccess = function (event) {
  3289. file = (event.target).result;
  3290. };
  3291. getRequest.onerror = function (event) {
  3292. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3293. notInDBCallback();
  3294. };
  3295. }
  3296. else {
  3297. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3298. callback();
  3299. }
  3300. };
  3301. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3302. var _this = this;
  3303. if (this.isSupported) {
  3304. var targetStore;
  3305. if (url.indexOf(".babylon") !== -1) {
  3306. targetStore = "scenes";
  3307. }
  3308. else {
  3309. targetStore = "textures";
  3310. }
  3311. // Create XHR
  3312. var xhr = new XMLHttpRequest(), fileData;
  3313. xhr.open("GET", url, true);
  3314. if (useArrayBuffer) {
  3315. xhr.responseType = "arraybuffer";
  3316. }
  3317. xhr.onprogress = progressCallback;
  3318. xhr.addEventListener("load", function () {
  3319. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3320. // Blob as response (XHR2)
  3321. //fileData = xhr.responseText;
  3322. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3323. if (!_this.hasReachedQuota) {
  3324. // Open a transaction to the database
  3325. var transaction = _this.db.transaction([targetStore], "readwrite");
  3326. // the transaction could abort because of a QuotaExceededError error
  3327. transaction.onabort = function (event) {
  3328. try {
  3329. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3330. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3331. this.hasReachedQuota = true;
  3332. }
  3333. }
  3334. catch (ex) {
  3335. }
  3336. callback(fileData);
  3337. };
  3338. transaction.oncomplete = function (event) {
  3339. callback(fileData);
  3340. };
  3341. var newFile;
  3342. if (targetStore === "scenes") {
  3343. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3344. }
  3345. else {
  3346. newFile = { textureUrl: url, data: fileData };
  3347. }
  3348. try {
  3349. // Put the scene into the database
  3350. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3351. addRequest.onsuccess = function (event) {
  3352. };
  3353. addRequest.onerror = function (event) {
  3354. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3355. };
  3356. }
  3357. catch (ex) {
  3358. callback(fileData);
  3359. }
  3360. }
  3361. else {
  3362. callback(fileData);
  3363. }
  3364. }
  3365. else {
  3366. callback();
  3367. }
  3368. }, false);
  3369. xhr.addEventListener("error", function (event) {
  3370. BABYLON.Tools.Error("error on XHR request.");
  3371. callback();
  3372. }, false);
  3373. xhr.send();
  3374. }
  3375. else {
  3376. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3377. callback();
  3378. }
  3379. };
  3380. Database.isUASupportingBlobStorage = true;
  3381. Database.parseURL = function (url) {
  3382. var a = document.createElement('a');
  3383. a.href = url;
  3384. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3385. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3386. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3387. return absLocation;
  3388. };
  3389. Database.ReturnFullUrlLocation = function (url) {
  3390. if (url.indexOf("http:/") === -1) {
  3391. return (BABYLON.Database.parseURL(window.location.href) + url);
  3392. }
  3393. else {
  3394. return url;
  3395. }
  3396. };
  3397. return Database;
  3398. })();
  3399. BABYLON.Database = Database;
  3400. })(BABYLON || (BABYLON = {}));
  3401. //# sourceMappingURL=babylon.database.js.map
  3402. var BABYLON;
  3403. (function (BABYLON) {
  3404. var Internals;
  3405. (function (Internals) {
  3406. /*
  3407. * Based on jsTGALoader - Javascript loader for TGA file
  3408. * By Vincent Thibault
  3409. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3410. */
  3411. var TGATools = (function () {
  3412. function TGATools() {
  3413. }
  3414. TGATools.GetTGAHeader = function (data) {
  3415. var offset = 0;
  3416. var header = {
  3417. id_length: data[offset++],
  3418. colormap_type: data[offset++],
  3419. image_type: data[offset++],
  3420. colormap_index: data[offset++] | data[offset++] << 8,
  3421. colormap_length: data[offset++] | data[offset++] << 8,
  3422. colormap_size: data[offset++],
  3423. origin: [
  3424. data[offset++] | data[offset++] << 8,
  3425. data[offset++] | data[offset++] << 8
  3426. ],
  3427. width: data[offset++] | data[offset++] << 8,
  3428. height: data[offset++] | data[offset++] << 8,
  3429. pixel_size: data[offset++],
  3430. flags: data[offset++]
  3431. };
  3432. return header;
  3433. };
  3434. TGATools.UploadContent = function (gl, data) {
  3435. // Not enough data to contain header ?
  3436. if (data.length < 19) {
  3437. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3438. return;
  3439. }
  3440. // Read Header
  3441. var offset = 18;
  3442. var header = TGATools.GetTGAHeader(data);
  3443. // Assume it's a valid Targa file.
  3444. if (header.id_length + offset > data.length) {
  3445. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3446. return;
  3447. }
  3448. // Skip not needed data
  3449. offset += header.id_length;
  3450. var use_rle = false;
  3451. var use_pal = false;
  3452. var use_rgb = false;
  3453. var use_grey = false;
  3454. switch (header.image_type) {
  3455. case TGATools._TYPE_RLE_INDEXED:
  3456. use_rle = true;
  3457. case TGATools._TYPE_INDEXED:
  3458. use_pal = true;
  3459. break;
  3460. case TGATools._TYPE_RLE_RGB:
  3461. use_rle = true;
  3462. case TGATools._TYPE_RGB:
  3463. use_rgb = true;
  3464. break;
  3465. case TGATools._TYPE_RLE_GREY:
  3466. use_rle = true;
  3467. case TGATools._TYPE_GREY:
  3468. use_grey = true;
  3469. break;
  3470. }
  3471. var pixel_data;
  3472. var numAlphaBits = header.flags & 0xf;
  3473. var pixel_size = header.pixel_size >> 3;
  3474. var pixel_total = header.width * header.height * pixel_size;
  3475. // Read palettes
  3476. var palettes;
  3477. if (use_pal) {
  3478. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3479. }
  3480. // Read LRE
  3481. if (use_rle) {
  3482. pixel_data = new Uint8Array(pixel_total);
  3483. var c, count, i;
  3484. var localOffset = 0;
  3485. var pixels = new Uint8Array(pixel_size);
  3486. while (offset < pixel_total && localOffset < pixel_total) {
  3487. c = data[offset++];
  3488. count = (c & 0x7f) + 1;
  3489. // RLE pixels
  3490. if (c & 0x80) {
  3491. for (i = 0; i < pixel_size; ++i) {
  3492. pixels[i] = data[offset++];
  3493. }
  3494. for (i = 0; i < count; ++i) {
  3495. pixel_data.set(pixels, localOffset + i * pixel_size);
  3496. }
  3497. localOffset += pixel_size * count;
  3498. }
  3499. else {
  3500. count *= pixel_size;
  3501. for (i = 0; i < count; ++i) {
  3502. pixel_data[localOffset + i] = data[offset++];
  3503. }
  3504. localOffset += count;
  3505. }
  3506. }
  3507. }
  3508. else {
  3509. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3510. }
  3511. // Load to texture
  3512. var x_start, y_start, x_step, y_step, y_end, x_end;
  3513. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3514. default:
  3515. case TGATools._ORIGIN_UL:
  3516. x_start = 0;
  3517. x_step = 1;
  3518. x_end = header.width;
  3519. y_start = 0;
  3520. y_step = 1;
  3521. y_end = header.height;
  3522. break;
  3523. case TGATools._ORIGIN_BL:
  3524. x_start = 0;
  3525. x_step = 1;
  3526. x_end = header.width;
  3527. y_start = header.height - 1;
  3528. y_step = -1;
  3529. y_end = -1;
  3530. break;
  3531. case TGATools._ORIGIN_UR:
  3532. x_start = header.width - 1;
  3533. x_step = -1;
  3534. x_end = -1;
  3535. y_start = 0;
  3536. y_step = 1;
  3537. y_end = header.height;
  3538. break;
  3539. case TGATools._ORIGIN_BR:
  3540. x_start = header.width - 1;
  3541. x_step = -1;
  3542. x_end = -1;
  3543. y_start = header.height - 1;
  3544. y_step = -1;
  3545. y_end = -1;
  3546. break;
  3547. }
  3548. // Load the specify method
  3549. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3550. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3551. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3552. };
  3553. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3554. var image = pixel_data, colormap = palettes;
  3555. var width = header.width, height = header.height;
  3556. var color, i = 0, x, y;
  3557. var imageData = new Uint8Array(width * height * 4);
  3558. for (y = y_start; y !== y_end; y += y_step) {
  3559. for (x = x_start; x !== x_end; x += x_step, i++) {
  3560. color = image[i];
  3561. imageData[(x + width * y) * 4 + 3] = 255;
  3562. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3563. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3564. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3565. }
  3566. }
  3567. return imageData;
  3568. };
  3569. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3570. var image = pixel_data;
  3571. var width = header.width, height = header.height;
  3572. var color, i = 0, x, y;
  3573. var imageData = new Uint8Array(width * height * 4);
  3574. for (y = y_start; y !== y_end; y += y_step) {
  3575. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3576. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3577. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3578. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3579. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3580. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3581. }
  3582. }
  3583. return imageData;
  3584. };
  3585. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3586. var image = pixel_data;
  3587. var width = header.width, height = header.height;
  3588. var i = 0, x, y;
  3589. var imageData = new Uint8Array(width * height * 4);
  3590. for (y = y_start; y !== y_end; y += y_step) {
  3591. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3592. imageData[(x + width * y) * 4 + 3] = 255;
  3593. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3594. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3595. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3596. }
  3597. }
  3598. return imageData;
  3599. };
  3600. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3601. var image = pixel_data;
  3602. var width = header.width, height = header.height;
  3603. var i = 0, x, y;
  3604. var imageData = new Uint8Array(width * height * 4);
  3605. for (y = y_start; y !== y_end; y += y_step) {
  3606. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3607. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3608. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3609. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3610. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3611. }
  3612. }
  3613. return imageData;
  3614. };
  3615. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3616. var image = pixel_data;
  3617. var width = header.width, height = header.height;
  3618. var color, i = 0, x, y;
  3619. var imageData = new Uint8Array(width * height * 4);
  3620. for (y = y_start; y !== y_end; y += y_step) {
  3621. for (x = x_start; x !== x_end; x += x_step, i++) {
  3622. color = image[i];
  3623. imageData[(x + width * y) * 4 + 0] = color;
  3624. imageData[(x + width * y) * 4 + 1] = color;
  3625. imageData[(x + width * y) * 4 + 2] = color;
  3626. imageData[(x + width * y) * 4 + 3] = 255;
  3627. }
  3628. }
  3629. return imageData;
  3630. };
  3631. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3632. var image = pixel_data;
  3633. var width = header.width, height = header.height;
  3634. var i = 0, x, y;
  3635. var imageData = new Uint8Array(width * height * 4);
  3636. for (y = y_start; y !== y_end; y += y_step) {
  3637. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3638. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3639. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3640. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3641. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3642. }
  3643. }
  3644. return imageData;
  3645. };
  3646. TGATools._TYPE_NO_DATA = 0;
  3647. TGATools._TYPE_INDEXED = 1;
  3648. TGATools._TYPE_RGB = 2;
  3649. TGATools._TYPE_GREY = 3;
  3650. TGATools._TYPE_RLE_INDEXED = 9;
  3651. TGATools._TYPE_RLE_RGB = 10;
  3652. TGATools._TYPE_RLE_GREY = 11;
  3653. TGATools._ORIGIN_MASK = 0x30;
  3654. TGATools._ORIGIN_SHIFT = 0x04;
  3655. TGATools._ORIGIN_BL = 0x00;
  3656. TGATools._ORIGIN_BR = 0x01;
  3657. TGATools._ORIGIN_UL = 0x02;
  3658. TGATools._ORIGIN_UR = 0x03;
  3659. return TGATools;
  3660. })();
  3661. Internals.TGATools = TGATools;
  3662. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3663. })(BABYLON || (BABYLON = {}));
  3664. //# sourceMappingURL=babylon.tools.tga.js.map
  3665. var BABYLON;
  3666. (function (BABYLON) {
  3667. var Internals;
  3668. (function (Internals) {
  3669. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3670. // All values and structures referenced from:
  3671. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3672. var DDS_MAGIC = 0x20534444;
  3673. 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;
  3674. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3675. 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;
  3676. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3677. function FourCCToInt32(value) {
  3678. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  3679. }
  3680. function Int32ToFourCC(value) {
  3681. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3682. }
  3683. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3684. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3685. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3686. var headerLengthInt = 31; // The header length in 32 bit ints
  3687. // Offsets into the header array
  3688. var off_magic = 0;
  3689. var off_size = 1;
  3690. var off_flags = 2;
  3691. var off_height = 3;
  3692. var off_width = 4;
  3693. var off_mipmapCount = 7;
  3694. var off_pfFlags = 20;
  3695. var off_pfFourCC = 21;
  3696. var off_RGBbpp = 22;
  3697. var off_RMask = 23;
  3698. var off_GMask = 24;
  3699. var off_BMask = 25;
  3700. var off_AMask = 26;
  3701. var off_caps1 = 27;
  3702. var off_caps2 = 28;
  3703. ;
  3704. var DDSTools = (function () {
  3705. function DDSTools() {
  3706. }
  3707. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3708. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3709. var mipmapCount = 1;
  3710. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3711. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3712. }
  3713. return {
  3714. width: header[off_width],
  3715. height: header[off_height],
  3716. mipmapCount: mipmapCount,
  3717. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3718. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3719. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3720. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3721. };
  3722. };
  3723. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3724. var byteArray = new Uint8Array(dataLength);
  3725. var srcData = new Uint8Array(arrayBuffer);
  3726. var index = 0;
  3727. for (var y = height - 1; y >= 0; y--) {
  3728. for (var x = 0; x < width; x++) {
  3729. var srcPos = dataOffset + (x + y * width) * 4;
  3730. byteArray[index + 2] = srcData[srcPos];
  3731. byteArray[index + 1] = srcData[srcPos + 1];
  3732. byteArray[index] = srcData[srcPos + 2];
  3733. byteArray[index + 3] = srcData[srcPos + 3];
  3734. index += 4;
  3735. }
  3736. }
  3737. return byteArray;
  3738. };
  3739. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3740. var byteArray = new Uint8Array(dataLength);
  3741. var srcData = new Uint8Array(arrayBuffer);
  3742. var index = 0;
  3743. for (var y = height - 1; y >= 0; y--) {
  3744. for (var x = 0; x < width; x++) {
  3745. var srcPos = dataOffset + (x + y * width) * 3;
  3746. byteArray[index + 2] = srcData[srcPos];
  3747. byteArray[index + 1] = srcData[srcPos + 1];
  3748. byteArray[index] = srcData[srcPos + 2];
  3749. index += 3;
  3750. }
  3751. }
  3752. return byteArray;
  3753. };
  3754. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3755. var byteArray = new Uint8Array(dataLength);
  3756. var srcData = new Uint8Array(arrayBuffer);
  3757. var index = 0;
  3758. for (var y = height - 1; y >= 0; y--) {
  3759. for (var x = 0; x < width; x++) {
  3760. var srcPos = dataOffset + (x + y * width);
  3761. byteArray[index] = srcData[srcPos];
  3762. index++;
  3763. }
  3764. }
  3765. return byteArray;
  3766. };
  3767. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  3768. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  3769. if (header[off_magic] != DDS_MAGIC) {
  3770. BABYLON.Tools.Error("Invalid magic number in DDS header");
  3771. return;
  3772. }
  3773. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  3774. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  3775. return;
  3776. }
  3777. if (info.isFourCC) {
  3778. fourCC = header[off_pfFourCC];
  3779. switch (fourCC) {
  3780. case FOURCC_DXT1:
  3781. blockBytes = 8;
  3782. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3783. break;
  3784. case FOURCC_DXT3:
  3785. blockBytes = 16;
  3786. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3787. break;
  3788. case FOURCC_DXT5:
  3789. blockBytes = 16;
  3790. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  3791. break;
  3792. default:
  3793. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  3794. return;
  3795. }
  3796. }
  3797. mipmapCount = 1;
  3798. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  3799. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3800. }
  3801. var bpp = header[off_RGBbpp];
  3802. for (var face = 0; face < faces; face++) {
  3803. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  3804. width = header[off_width];
  3805. height = header[off_height];
  3806. dataOffset = header[off_size] + 4;
  3807. for (i = 0; i < mipmapCount; ++i) {
  3808. if (info.isRGB) {
  3809. if (bpp == 24) {
  3810. dataLength = width * height * 3;
  3811. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3812. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  3813. }
  3814. else {
  3815. dataLength = width * height * 4;
  3816. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3817. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  3818. }
  3819. }
  3820. else if (info.isLuminance) {
  3821. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  3822. var unpaddedRowSize = width;
  3823. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  3824. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  3825. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3826. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  3827. }
  3828. else {
  3829. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  3830. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  3831. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  3832. }
  3833. dataOffset += dataLength;
  3834. width *= 0.5;
  3835. height *= 0.5;
  3836. width = Math.max(1.0, width);
  3837. height = Math.max(1.0, height);
  3838. }
  3839. }
  3840. };
  3841. return DDSTools;
  3842. })();
  3843. Internals.DDSTools = DDSTools;
  3844. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3845. })(BABYLON || (BABYLON = {}));
  3846. //# sourceMappingURL=babylon.tools.dds.js.map
  3847. var BABYLON;
  3848. (function (BABYLON) {
  3849. var SmartArray = (function () {
  3850. function SmartArray(capacity) {
  3851. this.length = 0;
  3852. this._duplicateId = 0;
  3853. this.data = new Array(capacity);
  3854. this._id = SmartArray._GlobalId++;
  3855. }
  3856. SmartArray.prototype.push = function (value) {
  3857. this.data[this.length++] = value;
  3858. if (this.length > this.data.length) {
  3859. this.data.length *= 2;
  3860. }
  3861. if (!value.__smartArrayFlags) {
  3862. value.__smartArrayFlags = {};
  3863. }
  3864. value.__smartArrayFlags[this._id] = this._duplicateId;
  3865. };
  3866. SmartArray.prototype.pushNoDuplicate = function (value) {
  3867. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3868. return;
  3869. }
  3870. this.push(value);
  3871. };
  3872. SmartArray.prototype.sort = function (compareFn) {
  3873. this.data.sort(compareFn);
  3874. };
  3875. SmartArray.prototype.reset = function () {
  3876. this.length = 0;
  3877. this._duplicateId++;
  3878. };
  3879. SmartArray.prototype.concat = function (array) {
  3880. if (array.length === 0) {
  3881. return;
  3882. }
  3883. if (this.length + array.length > this.data.length) {
  3884. this.data.length = (this.length + array.length) * 2;
  3885. }
  3886. for (var index = 0; index < array.length; index++) {
  3887. this.data[this.length++] = (array.data || array)[index];
  3888. }
  3889. };
  3890. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3891. if (array.length === 0) {
  3892. return;
  3893. }
  3894. if (this.length + array.length > this.data.length) {
  3895. this.data.length = (this.length + array.length) * 2;
  3896. }
  3897. for (var index = 0; index < array.length; index++) {
  3898. var item = (array.data || array)[index];
  3899. this.pushNoDuplicate(item);
  3900. }
  3901. };
  3902. SmartArray.prototype.indexOf = function (value) {
  3903. var position = this.data.indexOf(value);
  3904. if (position >= this.length) {
  3905. return -1;
  3906. }
  3907. return position;
  3908. };
  3909. // Statics
  3910. SmartArray._GlobalId = 0;
  3911. return SmartArray;
  3912. })();
  3913. BABYLON.SmartArray = SmartArray;
  3914. })(BABYLON || (BABYLON = {}));
  3915. //# sourceMappingURL=babylon.smartArray.js.map
  3916. var BABYLON;
  3917. (function (BABYLON) {
  3918. var SmartCollection = (function () {
  3919. function SmartCollection(capacity) {
  3920. if (capacity === void 0) { capacity = 10; }
  3921. this.count = 0;
  3922. this._initialCapacity = capacity;
  3923. this.items = {};
  3924. this._keys = new Array(this._initialCapacity);
  3925. }
  3926. SmartCollection.prototype.add = function (key, item) {
  3927. if (this.items[key] != undefined) {
  3928. return -1;
  3929. }
  3930. this.items[key] = item;
  3931. //literal keys are always strings, but we keep source type of key in _keys array
  3932. this._keys[this.count++] = key;
  3933. if (this.count > this._keys.length) {
  3934. this._keys.length *= 2;
  3935. }
  3936. return this.count;
  3937. };
  3938. SmartCollection.prototype.remove = function (key) {
  3939. if (this.items[key] == undefined) {
  3940. return -1;
  3941. }
  3942. return this.removeItemOfIndex(this.indexOf(key));
  3943. };
  3944. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3945. if (index < this.count && index > -1) {
  3946. delete this.items[this._keys[index]];
  3947. while (index < this.count) {
  3948. this._keys[index] = this._keys[index + 1];
  3949. index++;
  3950. }
  3951. }
  3952. else {
  3953. return -1;
  3954. }
  3955. return --this.count;
  3956. };
  3957. SmartCollection.prototype.indexOf = function (key) {
  3958. for (var i = 0; i !== this.count; i++) {
  3959. if (this._keys[i] === key) {
  3960. return i;
  3961. }
  3962. }
  3963. return -1;
  3964. };
  3965. SmartCollection.prototype.item = function (key) {
  3966. return this.items[key];
  3967. };
  3968. SmartCollection.prototype.getAllKeys = function () {
  3969. if (this.count > 0) {
  3970. var keys = new Array(this.count);
  3971. for (var i = 0; i < this.count; i++) {
  3972. keys[i] = this._keys[i];
  3973. }
  3974. return keys;
  3975. }
  3976. else {
  3977. return undefined;
  3978. }
  3979. };
  3980. SmartCollection.prototype.getKeyByIndex = function (index) {
  3981. if (index < this.count && index > -1) {
  3982. return this._keys[index];
  3983. }
  3984. else {
  3985. return undefined;
  3986. }
  3987. };
  3988. SmartCollection.prototype.getItemByIndex = function (index) {
  3989. if (index < this.count && index > -1) {
  3990. return this.items[this._keys[index]];
  3991. }
  3992. else {
  3993. return undefined;
  3994. }
  3995. };
  3996. SmartCollection.prototype.empty = function () {
  3997. if (this.count > 0) {
  3998. this.count = 0;
  3999. this.items = {};
  4000. this._keys = new Array(this._initialCapacity);
  4001. }
  4002. };
  4003. SmartCollection.prototype.forEach = function (block) {
  4004. var key;
  4005. for (key in this.items) {
  4006. if (this.items.hasOwnProperty(key)) {
  4007. block(this.items[key]);
  4008. }
  4009. }
  4010. };
  4011. return SmartCollection;
  4012. })();
  4013. BABYLON.SmartCollection = SmartCollection;
  4014. })(BABYLON || (BABYLON = {}));
  4015. //# sourceMappingURL=babylon.smartCollection.js.map
  4016. var BABYLON;
  4017. (function (BABYLON) {
  4018. // Screenshots
  4019. var screenshotCanvas;
  4020. var cloneValue = function (source, destinationObject) {
  4021. if (!source)
  4022. return null;
  4023. if (source instanceof BABYLON.Mesh) {
  4024. return null;
  4025. }
  4026. if (source instanceof BABYLON.SubMesh) {
  4027. return source.clone(destinationObject);
  4028. }
  4029. else if (source.clone) {
  4030. return source.clone();
  4031. }
  4032. return null;
  4033. };
  4034. var Tools = (function () {
  4035. function Tools() {
  4036. }
  4037. Tools.GetFilename = function (path) {
  4038. var index = path.lastIndexOf("/");
  4039. if (index < 0)
  4040. return path;
  4041. return path.substring(index + 1);
  4042. };
  4043. Tools.GetDOMTextContent = function (element) {
  4044. var result = "";
  4045. var child = element.firstChild;
  4046. while (child) {
  4047. if (child.nodeType === 3) {
  4048. result += child.textContent;
  4049. }
  4050. child = child.nextSibling;
  4051. }
  4052. return result;
  4053. };
  4054. Tools.ToDegrees = function (angle) {
  4055. return angle * 180 / Math.PI;
  4056. };
  4057. Tools.ToRadians = function (angle) {
  4058. return angle * Math.PI / 180;
  4059. };
  4060. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4061. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4062. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4063. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4064. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4065. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4066. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4067. }
  4068. return {
  4069. minimum: minimum,
  4070. maximum: maximum
  4071. };
  4072. };
  4073. Tools.ExtractMinAndMax = function (positions, start, count) {
  4074. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4075. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4076. for (var index = start; index < start + count; index++) {
  4077. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4078. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4079. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4080. }
  4081. return {
  4082. minimum: minimum,
  4083. maximum: maximum
  4084. };
  4085. };
  4086. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4087. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4088. return undefined;
  4089. return Array.isArray(obj) ? obj : [obj];
  4090. };
  4091. // Misc.
  4092. Tools.GetPointerPrefix = function () {
  4093. var eventPrefix = "pointer";
  4094. // Check if hand.js is referenced or if the browser natively supports pointer events
  4095. if (!navigator.pointerEnabled) {
  4096. eventPrefix = "mouse";
  4097. }
  4098. return eventPrefix;
  4099. };
  4100. Tools.QueueNewFrame = function (func) {
  4101. if (window.requestAnimationFrame)
  4102. window.requestAnimationFrame(func);
  4103. else if (window.msRequestAnimationFrame)
  4104. window.msRequestAnimationFrame(func);
  4105. else if (window.webkitRequestAnimationFrame)
  4106. window.webkitRequestAnimationFrame(func);
  4107. else if (window.mozRequestAnimationFrame)
  4108. window.mozRequestAnimationFrame(func);
  4109. else if (window.oRequestAnimationFrame)
  4110. window.oRequestAnimationFrame(func);
  4111. else {
  4112. window.setTimeout(func, 16);
  4113. }
  4114. };
  4115. Tools.RequestFullscreen = function (element) {
  4116. if (element.requestFullscreen)
  4117. element.requestFullscreen();
  4118. else if (element.msRequestFullscreen)
  4119. element.msRequestFullscreen();
  4120. else if (element.webkitRequestFullscreen)
  4121. element.webkitRequestFullscreen();
  4122. else if (element.mozRequestFullScreen)
  4123. element.mozRequestFullScreen();
  4124. };
  4125. Tools.ExitFullscreen = function () {
  4126. if (document.exitFullscreen) {
  4127. document.exitFullscreen();
  4128. }
  4129. else if (document.mozCancelFullScreen) {
  4130. document.mozCancelFullScreen();
  4131. }
  4132. else if (document.webkitCancelFullScreen) {
  4133. document.webkitCancelFullScreen();
  4134. }
  4135. else if (document.msCancelFullScreen) {
  4136. document.msCancelFullScreen();
  4137. }
  4138. };
  4139. // External files
  4140. Tools.CleanUrl = function (url) {
  4141. url = url.replace(/#/mg, "%23");
  4142. return url;
  4143. };
  4144. Tools.LoadImage = function (url, onload, onerror, database) {
  4145. url = Tools.CleanUrl(url);
  4146. var img = new Image();
  4147. if (url.substr(0, 5) !== "data:")
  4148. img.crossOrigin = 'anonymous';
  4149. img.onload = function () {
  4150. onload(img);
  4151. };
  4152. img.onerror = function (err) {
  4153. onerror(img, err);
  4154. };
  4155. var noIndexedDB = function () {
  4156. img.src = url;
  4157. };
  4158. var loadFromIndexedDB = function () {
  4159. database.loadImageFromDB(url, img);
  4160. };
  4161. //ANY database to do!
  4162. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  4163. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4164. }
  4165. else {
  4166. if (url.indexOf("file:") === -1) {
  4167. noIndexedDB();
  4168. }
  4169. else {
  4170. try {
  4171. var textureName = url.substring(5);
  4172. var blobURL;
  4173. try {
  4174. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4175. }
  4176. catch (ex) {
  4177. // Chrome doesn't support oneTimeOnly parameter
  4178. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4179. }
  4180. img.src = blobURL;
  4181. }
  4182. catch (e) {
  4183. Tools.Log("Error while trying to load texture: " + textureName);
  4184. img.src = null;
  4185. }
  4186. }
  4187. }
  4188. return img;
  4189. };
  4190. //ANY
  4191. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4192. url = Tools.CleanUrl(url);
  4193. var noIndexedDB = function () {
  4194. var request = new XMLHttpRequest();
  4195. var loadUrl = Tools.BaseUrl + url;
  4196. request.open('GET', loadUrl, true);
  4197. if (useArrayBuffer) {
  4198. request.responseType = "arraybuffer";
  4199. }
  4200. request.onprogress = progressCallBack;
  4201. request.onreadystatechange = function () {
  4202. if (request.readyState === 4) {
  4203. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4204. callback(!useArrayBuffer ? request.responseText : request.response);
  4205. }
  4206. else {
  4207. if (onError) {
  4208. onError();
  4209. }
  4210. else {
  4211. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4212. }
  4213. }
  4214. }
  4215. };
  4216. request.send(null);
  4217. };
  4218. var loadFromIndexedDB = function () {
  4219. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4220. };
  4221. if (url.indexOf("file:") !== -1) {
  4222. var fileName = url.substring(5);
  4223. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4224. }
  4225. else {
  4226. // Caching all files
  4227. if (database && database.enableSceneOffline) {
  4228. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4229. }
  4230. else {
  4231. noIndexedDB();
  4232. }
  4233. }
  4234. };
  4235. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4236. var reader = new FileReader();
  4237. reader.onload = function (e) {
  4238. //target doesn't have result from ts 1.3
  4239. callback(e.target['result']);
  4240. };
  4241. reader.onprogress = progressCallback;
  4242. reader.readAsDataURL(fileToLoad);
  4243. };
  4244. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4245. var reader = new FileReader();
  4246. reader.onerror = function (e) {
  4247. Tools.Log("Error while reading file: " + fileToLoad.name);
  4248. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  4249. };
  4250. reader.onload = function (e) {
  4251. //target doesn't have result from ts 1.3
  4252. callback(e.target['result']);
  4253. };
  4254. reader.onprogress = progressCallBack;
  4255. if (!useArrayBuffer) {
  4256. // Asynchronous read
  4257. reader.readAsText(fileToLoad);
  4258. }
  4259. else {
  4260. reader.readAsArrayBuffer(fileToLoad);
  4261. }
  4262. };
  4263. // Misc.
  4264. Tools.Clamp = function (value, min, max) {
  4265. if (min === void 0) { min = 0; }
  4266. if (max === void 0) { max = 1; }
  4267. return Math.min(max, Math.max(min, value));
  4268. };
  4269. // Returns -1 when value is a negative number and
  4270. // +1 when value is a positive number.
  4271. Tools.Sign = function (value) {
  4272. value = +value; // convert to a number
  4273. if (value === 0 || isNaN(value))
  4274. return value;
  4275. return value > 0 ? 1 : -1;
  4276. };
  4277. Tools.Format = function (value, decimals) {
  4278. if (decimals === void 0) { decimals = 2; }
  4279. return value.toFixed(decimals);
  4280. };
  4281. Tools.CheckExtends = function (v, min, max) {
  4282. if (v.x < min.x)
  4283. min.x = v.x;
  4284. if (v.y < min.y)
  4285. min.y = v.y;
  4286. if (v.z < min.z)
  4287. min.z = v.z;
  4288. if (v.x > max.x)
  4289. max.x = v.x;
  4290. if (v.y > max.y)
  4291. max.y = v.y;
  4292. if (v.z > max.z)
  4293. max.z = v.z;
  4294. };
  4295. Tools.WithinEpsilon = function (a, b, epsilon) {
  4296. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4297. var num = a - b;
  4298. return -epsilon <= num && num <= epsilon;
  4299. };
  4300. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4301. for (var prop in source) {
  4302. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4303. continue;
  4304. }
  4305. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4306. continue;
  4307. }
  4308. var sourceValue = source[prop];
  4309. var typeOfSourceValue = typeof sourceValue;
  4310. if (typeOfSourceValue === "function") {
  4311. continue;
  4312. }
  4313. if (typeOfSourceValue === "object") {
  4314. if (sourceValue instanceof Array) {
  4315. destination[prop] = [];
  4316. if (sourceValue.length > 0) {
  4317. if (typeof sourceValue[0] == "object") {
  4318. for (var index = 0; index < sourceValue.length; index++) {
  4319. var clonedValue = cloneValue(sourceValue[index], destination);
  4320. if (destination[prop].indexOf(clonedValue) === -1) {
  4321. destination[prop].push(clonedValue);
  4322. }
  4323. }
  4324. }
  4325. else {
  4326. destination[prop] = sourceValue.slice(0);
  4327. }
  4328. }
  4329. }
  4330. else {
  4331. destination[prop] = cloneValue(sourceValue, destination);
  4332. }
  4333. }
  4334. else {
  4335. destination[prop] = sourceValue;
  4336. }
  4337. }
  4338. };
  4339. Tools.IsEmpty = function (obj) {
  4340. for (var i in obj) {
  4341. return false;
  4342. }
  4343. return true;
  4344. };
  4345. Tools.RegisterTopRootEvents = function (events) {
  4346. for (var index = 0; index < events.length; index++) {
  4347. var event = events[index];
  4348. window.addEventListener(event.name, event.handler, false);
  4349. try {
  4350. if (window.parent) {
  4351. window.parent.addEventListener(event.name, event.handler, false);
  4352. }
  4353. }
  4354. catch (e) {
  4355. }
  4356. }
  4357. };
  4358. Tools.UnregisterTopRootEvents = function (events) {
  4359. for (var index = 0; index < events.length; index++) {
  4360. var event = events[index];
  4361. window.removeEventListener(event.name, event.handler);
  4362. try {
  4363. if (window.parent) {
  4364. window.parent.removeEventListener(event.name, event.handler);
  4365. }
  4366. }
  4367. catch (e) {
  4368. }
  4369. }
  4370. };
  4371. Tools.DumpFramebuffer = function (width, height, engine) {
  4372. // Read the contents of the framebuffer
  4373. var numberOfChannelsByLine = width * 4;
  4374. var halfHeight = height / 2;
  4375. //Reading datas from WebGL
  4376. var data = engine.readPixels(0, 0, width, height);
  4377. for (var i = 0; i < halfHeight; i++) {
  4378. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4379. var currentCell = j + i * numberOfChannelsByLine;
  4380. var targetLine = height - i - 1;
  4381. var targetCell = j + targetLine * numberOfChannelsByLine;
  4382. var temp = data[currentCell];
  4383. data[currentCell] = data[targetCell];
  4384. data[targetCell] = temp;
  4385. }
  4386. }
  4387. // Create a 2D canvas to store the result
  4388. if (!screenshotCanvas) {
  4389. screenshotCanvas = document.createElement('canvas');
  4390. }
  4391. screenshotCanvas.width = width;
  4392. screenshotCanvas.height = height;
  4393. var context = screenshotCanvas.getContext('2d');
  4394. // Copy the pixels to a 2D canvas
  4395. var imageData = context.createImageData(width, height);
  4396. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4397. var castData = imageData.data;
  4398. castData.set(data);
  4399. context.putImageData(imageData, 0, 0);
  4400. var base64Image = screenshotCanvas.toDataURL();
  4401. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4402. if (("download" in document.createElement("a"))) {
  4403. var a = window.document.createElement("a");
  4404. a.href = base64Image;
  4405. var date = new Date();
  4406. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  4407. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  4408. window.document.body.appendChild(a);
  4409. a.addEventListener("click", function () {
  4410. a.parentElement.removeChild(a);
  4411. });
  4412. a.click();
  4413. }
  4414. else {
  4415. var newWindow = window.open("");
  4416. var img = newWindow.document.createElement("img");
  4417. img.src = base64Image;
  4418. newWindow.document.body.appendChild(img);
  4419. }
  4420. };
  4421. Tools.CreateScreenshot = function (engine, camera, size) {
  4422. var width;
  4423. var height;
  4424. var scene = camera.getScene();
  4425. var previousCamera = null;
  4426. if (scene.activeCamera !== camera) {
  4427. previousCamera = scene.activeCamera;
  4428. scene.activeCamera = camera;
  4429. }
  4430. //If a precision value is specified
  4431. if (size.precision) {
  4432. width = Math.round(engine.getRenderWidth() * size.precision);
  4433. height = Math.round(width / engine.getAspectRatio(camera));
  4434. size = { width: width, height: height };
  4435. }
  4436. else if (size.width && size.height) {
  4437. width = size.width;
  4438. height = size.height;
  4439. }
  4440. else if (size.width && !size.height) {
  4441. width = size.width;
  4442. height = Math.round(width / engine.getAspectRatio(camera));
  4443. size = { width: width, height: height };
  4444. }
  4445. else if (size.height && !size.width) {
  4446. height = size.height;
  4447. width = Math.round(height * engine.getAspectRatio(camera));
  4448. size = { width: width, height: height };
  4449. }
  4450. else if (!isNaN(size)) {
  4451. height = size;
  4452. width = size;
  4453. }
  4454. else {
  4455. Tools.Error("Invalid 'size' parameter !");
  4456. return;
  4457. }
  4458. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4459. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4460. texture.renderList = scene.meshes;
  4461. texture.onAfterRender = function () {
  4462. Tools.DumpFramebuffer(width, height, engine);
  4463. };
  4464. scene.incrementRenderId();
  4465. texture.render(true);
  4466. texture.dispose();
  4467. if (previousCamera) {
  4468. scene.activeCamera = previousCamera;
  4469. }
  4470. };
  4471. // XHR response validator for local file scenario
  4472. Tools.ValidateXHRData = function (xhr, dataType) {
  4473. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4474. if (dataType === void 0) { dataType = 7; }
  4475. try {
  4476. if (dataType & 1) {
  4477. if (xhr.responseText && xhr.responseText.length > 0) {
  4478. return true;
  4479. }
  4480. else if (dataType === 1) {
  4481. return false;
  4482. }
  4483. }
  4484. if (dataType & 2) {
  4485. // Check header width and height since there is no "TGA" magic number
  4486. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4487. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4488. return true;
  4489. }
  4490. else if (dataType === 2) {
  4491. return false;
  4492. }
  4493. }
  4494. if (dataType & 4) {
  4495. // Check for the "DDS" magic number
  4496. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4497. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4498. return true;
  4499. }
  4500. else {
  4501. return false;
  4502. }
  4503. }
  4504. }
  4505. catch (e) {
  4506. }
  4507. return false;
  4508. };
  4509. Object.defineProperty(Tools, "NoneLogLevel", {
  4510. get: function () {
  4511. return Tools._NoneLogLevel;
  4512. },
  4513. enumerable: true,
  4514. configurable: true
  4515. });
  4516. Object.defineProperty(Tools, "MessageLogLevel", {
  4517. get: function () {
  4518. return Tools._MessageLogLevel;
  4519. },
  4520. enumerable: true,
  4521. configurable: true
  4522. });
  4523. Object.defineProperty(Tools, "WarningLogLevel", {
  4524. get: function () {
  4525. return Tools._WarningLogLevel;
  4526. },
  4527. enumerable: true,
  4528. configurable: true
  4529. });
  4530. Object.defineProperty(Tools, "ErrorLogLevel", {
  4531. get: function () {
  4532. return Tools._ErrorLogLevel;
  4533. },
  4534. enumerable: true,
  4535. configurable: true
  4536. });
  4537. Object.defineProperty(Tools, "AllLogLevel", {
  4538. get: function () {
  4539. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4540. },
  4541. enumerable: true,
  4542. configurable: true
  4543. });
  4544. Tools._AddLogEntry = function (entry) {
  4545. Tools._LogCache = entry + Tools._LogCache;
  4546. if (Tools.OnNewCacheEntry) {
  4547. Tools.OnNewCacheEntry(entry);
  4548. }
  4549. };
  4550. Tools._FormatMessage = function (message) {
  4551. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4552. var date = new Date();
  4553. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4554. };
  4555. Tools._LogDisabled = function (message) {
  4556. // nothing to do
  4557. };
  4558. Tools._LogEnabled = function (message) {
  4559. var formattedMessage = Tools._FormatMessage(message);
  4560. console.log("BJS - " + formattedMessage);
  4561. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4562. Tools._AddLogEntry(entry);
  4563. };
  4564. Tools._WarnDisabled = function (message) {
  4565. // nothing to do
  4566. };
  4567. Tools._WarnEnabled = function (message) {
  4568. var formattedMessage = Tools._FormatMessage(message);
  4569. console.warn("BJS - " + formattedMessage);
  4570. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4571. Tools._AddLogEntry(entry);
  4572. };
  4573. Tools._ErrorDisabled = function (message) {
  4574. // nothing to do
  4575. };
  4576. Tools._ErrorEnabled = function (message) {
  4577. var formattedMessage = Tools._FormatMessage(message);
  4578. console.error("BJS - " + formattedMessage);
  4579. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4580. Tools._AddLogEntry(entry);
  4581. };
  4582. Object.defineProperty(Tools, "LogCache", {
  4583. get: function () {
  4584. return Tools._LogCache;
  4585. },
  4586. enumerable: true,
  4587. configurable: true
  4588. });
  4589. Object.defineProperty(Tools, "LogLevels", {
  4590. set: function (level) {
  4591. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4592. Tools.Log = Tools._LogEnabled;
  4593. }
  4594. else {
  4595. Tools.Log = Tools._LogDisabled;
  4596. }
  4597. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4598. Tools.Warn = Tools._WarnEnabled;
  4599. }
  4600. else {
  4601. Tools.Warn = Tools._WarnDisabled;
  4602. }
  4603. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4604. Tools.Error = Tools._ErrorEnabled;
  4605. }
  4606. else {
  4607. Tools.Error = Tools._ErrorDisabled;
  4608. }
  4609. },
  4610. enumerable: true,
  4611. configurable: true
  4612. });
  4613. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4614. get: function () {
  4615. return Tools._PerformanceNoneLogLevel;
  4616. },
  4617. enumerable: true,
  4618. configurable: true
  4619. });
  4620. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4621. get: function () {
  4622. return Tools._PerformanceUserMarkLogLevel;
  4623. },
  4624. enumerable: true,
  4625. configurable: true
  4626. });
  4627. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4628. get: function () {
  4629. return Tools._PerformanceConsoleLogLevel;
  4630. },
  4631. enumerable: true,
  4632. configurable: true
  4633. });
  4634. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4635. set: function (level) {
  4636. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4637. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4638. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4639. return;
  4640. }
  4641. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4642. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4643. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4644. return;
  4645. }
  4646. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4647. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4648. },
  4649. enumerable: true,
  4650. configurable: true
  4651. });
  4652. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4653. };
  4654. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4655. };
  4656. Tools._StartUserMark = function (counterName, condition) {
  4657. if (condition === void 0) { condition = true; }
  4658. if (!condition || !Tools._performance.mark) {
  4659. return;
  4660. }
  4661. Tools._performance.mark(counterName + "-Begin");
  4662. };
  4663. Tools._EndUserMark = function (counterName, condition) {
  4664. if (condition === void 0) { condition = true; }
  4665. if (!condition || !Tools._performance.mark) {
  4666. return;
  4667. }
  4668. Tools._performance.mark(counterName + "-End");
  4669. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4670. };
  4671. Tools._StartPerformanceConsole = function (counterName, condition) {
  4672. if (condition === void 0) { condition = true; }
  4673. if (!condition) {
  4674. return;
  4675. }
  4676. Tools._StartUserMark(counterName, condition);
  4677. if (console.time) {
  4678. console.time(counterName);
  4679. }
  4680. };
  4681. Tools._EndPerformanceConsole = function (counterName, condition) {
  4682. if (condition === void 0) { condition = true; }
  4683. if (!condition) {
  4684. return;
  4685. }
  4686. Tools._EndUserMark(counterName, condition);
  4687. if (console.time) {
  4688. console.timeEnd(counterName);
  4689. }
  4690. };
  4691. Object.defineProperty(Tools, "Now", {
  4692. get: function () {
  4693. if (window.performance && window.performance.now) {
  4694. return window.performance.now();
  4695. }
  4696. return new Date().getTime();
  4697. },
  4698. enumerable: true,
  4699. configurable: true
  4700. });
  4701. // Deprecated
  4702. Tools.GetFps = function () {
  4703. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4704. return 0;
  4705. };
  4706. Tools.BaseUrl = "";
  4707. Tools.GetExponantOfTwo = function (value, max) {
  4708. var count = 1;
  4709. do {
  4710. count *= 2;
  4711. } while (count < value);
  4712. if (count > max)
  4713. count = max;
  4714. return count;
  4715. };
  4716. // Logs
  4717. Tools._NoneLogLevel = 0;
  4718. Tools._MessageLogLevel = 1;
  4719. Tools._WarningLogLevel = 2;
  4720. Tools._ErrorLogLevel = 4;
  4721. Tools._LogCache = "";
  4722. Tools.Log = Tools._LogEnabled;
  4723. Tools.Warn = Tools._WarnEnabled;
  4724. Tools.Error = Tools._ErrorEnabled;
  4725. // Performances
  4726. Tools._PerformanceNoneLogLevel = 0;
  4727. Tools._PerformanceUserMarkLogLevel = 1;
  4728. Tools._PerformanceConsoleLogLevel = 2;
  4729. Tools._performance = window.performance;
  4730. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4731. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4732. return Tools;
  4733. })();
  4734. BABYLON.Tools = Tools;
  4735. /**
  4736. * An implementation of a loop for asynchronous functions.
  4737. */
  4738. var AsyncLoop = (function () {
  4739. /**
  4740. * Constroctor.
  4741. * @param iterations the number of iterations.
  4742. * @param _fn the function to run each iteration
  4743. * @param _successCallback the callback that will be called upon succesful execution
  4744. * @param offset starting offset.
  4745. */
  4746. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4747. if (offset === void 0) { offset = 0; }
  4748. this.iterations = iterations;
  4749. this._fn = _fn;
  4750. this._successCallback = _successCallback;
  4751. this.index = offset - 1;
  4752. this._done = false;
  4753. }
  4754. /**
  4755. * Execute the next iteration. Must be called after the last iteration was finished.
  4756. */
  4757. AsyncLoop.prototype.executeNext = function () {
  4758. if (!this._done) {
  4759. if (this.index + 1 < this.iterations) {
  4760. ++this.index;
  4761. this._fn(this);
  4762. }
  4763. else {
  4764. this.breakLoop();
  4765. }
  4766. }
  4767. };
  4768. /**
  4769. * Break the loop and run the success callback.
  4770. */
  4771. AsyncLoop.prototype.breakLoop = function () {
  4772. this._done = true;
  4773. this._successCallback();
  4774. };
  4775. /**
  4776. * Helper function
  4777. */
  4778. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4779. if (offset === void 0) { offset = 0; }
  4780. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4781. loop.executeNext();
  4782. return loop;
  4783. };
  4784. /**
  4785. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4786. * @param iterations total number of iterations
  4787. * @param syncedIterations number of synchronous iterations in each async iteration.
  4788. * @param fn the function to call each iteration.
  4789. * @param callback a success call back that will be called when iterating stops.
  4790. * @param breakFunction a break condition (optional)
  4791. * @param timeout timeout settings for the setTimeout function. default - 0.
  4792. * @constructor
  4793. */
  4794. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4795. if (timeout === void 0) { timeout = 0; }
  4796. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4797. if (breakFunction && breakFunction())
  4798. loop.breakLoop();
  4799. else {
  4800. setTimeout(function () {
  4801. for (var i = 0; i < syncedIterations; ++i) {
  4802. var iteration = (loop.index * syncedIterations) + i;
  4803. if (iteration >= iterations)
  4804. break;
  4805. fn(iteration);
  4806. if (breakFunction && breakFunction()) {
  4807. loop.breakLoop();
  4808. break;
  4809. }
  4810. }
  4811. loop.executeNext();
  4812. }, timeout);
  4813. }
  4814. }, callback);
  4815. };
  4816. return AsyncLoop;
  4817. })();
  4818. BABYLON.AsyncLoop = AsyncLoop;
  4819. })(BABYLON || (BABYLON = {}));
  4820. //# sourceMappingURL=babylon.tools.js.map
  4821. var BABYLON;
  4822. (function (BABYLON) {
  4823. var _DepthCullingState = (function () {
  4824. function _DepthCullingState() {
  4825. this._isDepthTestDirty = false;
  4826. this._isDepthMaskDirty = false;
  4827. this._isDepthFuncDirty = false;
  4828. this._isCullFaceDirty = false;
  4829. this._isCullDirty = false;
  4830. this._isZOffsetDirty = false;
  4831. }
  4832. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4833. get: function () {
  4834. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4835. },
  4836. enumerable: true,
  4837. configurable: true
  4838. });
  4839. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4840. get: function () {
  4841. return this._zOffset;
  4842. },
  4843. set: function (value) {
  4844. if (this._zOffset === value) {
  4845. return;
  4846. }
  4847. this._zOffset = value;
  4848. this._isZOffsetDirty = true;
  4849. },
  4850. enumerable: true,
  4851. configurable: true
  4852. });
  4853. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4854. get: function () {
  4855. return this._cullFace;
  4856. },
  4857. set: function (value) {
  4858. if (this._cullFace === value) {
  4859. return;
  4860. }
  4861. this._cullFace = value;
  4862. this._isCullFaceDirty = true;
  4863. },
  4864. enumerable: true,
  4865. configurable: true
  4866. });
  4867. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4868. get: function () {
  4869. return this._cull;
  4870. },
  4871. set: function (value) {
  4872. if (this._cull === value) {
  4873. return;
  4874. }
  4875. this._cull = value;
  4876. this._isCullDirty = true;
  4877. },
  4878. enumerable: true,
  4879. configurable: true
  4880. });
  4881. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4882. get: function () {
  4883. return this._depthFunc;
  4884. },
  4885. set: function (value) {
  4886. if (this._depthFunc === value) {
  4887. return;
  4888. }
  4889. this._depthFunc = value;
  4890. this._isDepthFuncDirty = true;
  4891. },
  4892. enumerable: true,
  4893. configurable: true
  4894. });
  4895. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4896. get: function () {
  4897. return this._depthMask;
  4898. },
  4899. set: function (value) {
  4900. if (this._depthMask === value) {
  4901. return;
  4902. }
  4903. this._depthMask = value;
  4904. this._isDepthMaskDirty = true;
  4905. },
  4906. enumerable: true,
  4907. configurable: true
  4908. });
  4909. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4910. get: function () {
  4911. return this._depthTest;
  4912. },
  4913. set: function (value) {
  4914. if (this._depthTest === value) {
  4915. return;
  4916. }
  4917. this._depthTest = value;
  4918. this._isDepthTestDirty = true;
  4919. },
  4920. enumerable: true,
  4921. configurable: true
  4922. });
  4923. _DepthCullingState.prototype.reset = function () {
  4924. this._depthMask = true;
  4925. this._depthTest = true;
  4926. this._depthFunc = null;
  4927. this._cull = null;
  4928. this._cullFace = null;
  4929. this._zOffset = 0;
  4930. this._isDepthTestDirty = true;
  4931. this._isDepthMaskDirty = true;
  4932. this._isDepthFuncDirty = false;
  4933. this._isCullFaceDirty = false;
  4934. this._isCullDirty = false;
  4935. this._isZOffsetDirty = false;
  4936. };
  4937. _DepthCullingState.prototype.apply = function (gl) {
  4938. if (!this.isDirty) {
  4939. return;
  4940. }
  4941. // Cull
  4942. if (this._isCullDirty) {
  4943. if (this.cull) {
  4944. gl.enable(gl.CULL_FACE);
  4945. }
  4946. else {
  4947. gl.disable(gl.CULL_FACE);
  4948. }
  4949. this._isCullDirty = false;
  4950. }
  4951. // Cull face
  4952. if (this._isCullFaceDirty) {
  4953. gl.cullFace(this.cullFace);
  4954. this._isCullFaceDirty = false;
  4955. }
  4956. // Depth mask
  4957. if (this._isDepthMaskDirty) {
  4958. gl.depthMask(this.depthMask);
  4959. this._isDepthMaskDirty = false;
  4960. }
  4961. // Depth test
  4962. if (this._isDepthTestDirty) {
  4963. if (this.depthTest) {
  4964. gl.enable(gl.DEPTH_TEST);
  4965. }
  4966. else {
  4967. gl.disable(gl.DEPTH_TEST);
  4968. }
  4969. this._isDepthTestDirty = false;
  4970. }
  4971. // Depth func
  4972. if (this._isDepthFuncDirty) {
  4973. gl.depthFunc(this.depthFunc);
  4974. this._isDepthFuncDirty = false;
  4975. }
  4976. // zOffset
  4977. if (this._isZOffsetDirty) {
  4978. if (this.zOffset) {
  4979. gl.enable(gl.POLYGON_OFFSET_FILL);
  4980. gl.polygonOffset(this.zOffset, 0);
  4981. }
  4982. else {
  4983. gl.disable(gl.POLYGON_OFFSET_FILL);
  4984. }
  4985. this._isZOffsetDirty = false;
  4986. }
  4987. };
  4988. return _DepthCullingState;
  4989. })();
  4990. BABYLON._DepthCullingState = _DepthCullingState;
  4991. var _AlphaState = (function () {
  4992. function _AlphaState() {
  4993. this._isAlphaBlendDirty = false;
  4994. this._isBlendFunctionParametersDirty = false;
  4995. this._alphaBlend = false;
  4996. this._blendFunctionParameters = new Array(4);
  4997. }
  4998. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4999. get: function () {
  5000. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5001. },
  5002. enumerable: true,
  5003. configurable: true
  5004. });
  5005. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5006. get: function () {
  5007. return this._alphaBlend;
  5008. },
  5009. set: function (value) {
  5010. if (this._alphaBlend === value) {
  5011. return;
  5012. }
  5013. this._alphaBlend = value;
  5014. this._isAlphaBlendDirty = true;
  5015. },
  5016. enumerable: true,
  5017. configurable: true
  5018. });
  5019. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5020. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  5021. return;
  5022. }
  5023. this._blendFunctionParameters[0] = value0;
  5024. this._blendFunctionParameters[1] = value1;
  5025. this._blendFunctionParameters[2] = value2;
  5026. this._blendFunctionParameters[3] = value3;
  5027. this._isBlendFunctionParametersDirty = true;
  5028. };
  5029. _AlphaState.prototype.reset = function () {
  5030. this._alphaBlend = false;
  5031. this._blendFunctionParameters[0] = null;
  5032. this._blendFunctionParameters[1] = null;
  5033. this._blendFunctionParameters[2] = null;
  5034. this._blendFunctionParameters[3] = null;
  5035. this._isAlphaBlendDirty = true;
  5036. this._isBlendFunctionParametersDirty = false;
  5037. };
  5038. _AlphaState.prototype.apply = function (gl) {
  5039. if (!this.isDirty) {
  5040. return;
  5041. }
  5042. // Alpha blend
  5043. if (this._isAlphaBlendDirty) {
  5044. if (this._alphaBlend) {
  5045. gl.enable(gl.BLEND);
  5046. }
  5047. else {
  5048. gl.disable(gl.BLEND);
  5049. }
  5050. this._isAlphaBlendDirty = false;
  5051. }
  5052. // Alpha function
  5053. if (this._isBlendFunctionParametersDirty) {
  5054. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5055. this._isBlendFunctionParametersDirty = false;
  5056. }
  5057. };
  5058. return _AlphaState;
  5059. })();
  5060. BABYLON._AlphaState = _AlphaState;
  5061. var compileShader = function (gl, source, type, defines) {
  5062. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5063. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5064. gl.compileShader(shader);
  5065. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5066. throw new Error(gl.getShaderInfoLog(shader));
  5067. }
  5068. return shader;
  5069. };
  5070. var getWebGLTextureType = function (gl, type) {
  5071. var textureType = gl.UNSIGNED_BYTE;
  5072. if (type === Engine.TEXTURETYPE_FLOAT)
  5073. textureType = gl.FLOAT;
  5074. return textureType;
  5075. };
  5076. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5077. var magFilter = gl.NEAREST;
  5078. var minFilter = gl.NEAREST;
  5079. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5080. magFilter = gl.LINEAR;
  5081. if (generateMipMaps) {
  5082. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5083. }
  5084. else {
  5085. minFilter = gl.LINEAR;
  5086. }
  5087. }
  5088. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5089. magFilter = gl.LINEAR;
  5090. if (generateMipMaps) {
  5091. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5092. }
  5093. else {
  5094. minFilter = gl.LINEAR;
  5095. }
  5096. }
  5097. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5098. magFilter = gl.NEAREST;
  5099. if (generateMipMaps) {
  5100. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5101. }
  5102. else {
  5103. minFilter = gl.NEAREST;
  5104. }
  5105. }
  5106. return {
  5107. min: minFilter,
  5108. mag: magFilter
  5109. };
  5110. };
  5111. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5112. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5113. var engine = scene.getEngine();
  5114. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5115. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5116. gl.bindTexture(gl.TEXTURE_2D, texture);
  5117. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5118. texture._baseWidth = width;
  5119. texture._baseHeight = height;
  5120. texture._width = potWidth;
  5121. texture._height = potHeight;
  5122. texture.isReady = true;
  5123. processFunction(potWidth, potHeight);
  5124. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5125. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5126. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5127. if (!noMipmap && !isCompressed) {
  5128. gl.generateMipmap(gl.TEXTURE_2D);
  5129. }
  5130. gl.bindTexture(gl.TEXTURE_2D, null);
  5131. engine._activeTexturesCache = [];
  5132. scene._removePendingData(texture);
  5133. };
  5134. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5135. var onload = function () {
  5136. loadedImages[index] = img;
  5137. loadedImages._internalCount++;
  5138. scene._removePendingData(img);
  5139. if (loadedImages._internalCount === 6) {
  5140. onfinish(loadedImages);
  5141. }
  5142. };
  5143. var onerror = function () {
  5144. scene._removePendingData(img);
  5145. };
  5146. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5147. scene._addPendingData(img);
  5148. };
  5149. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5150. var loadedImages = [];
  5151. loadedImages._internalCount = 0;
  5152. for (var index = 0; index < 6; index++) {
  5153. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5154. }
  5155. };
  5156. var EngineCapabilities = (function () {
  5157. function EngineCapabilities() {
  5158. }
  5159. return EngineCapabilities;
  5160. })();
  5161. BABYLON.EngineCapabilities = EngineCapabilities;
  5162. /**
  5163. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5164. */
  5165. var Engine = (function () {
  5166. /**
  5167. * @constructor
  5168. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5169. * @param {boolean} [antialias] - enable antialias
  5170. * @param options - further options to be sent to the getContext function
  5171. */
  5172. function Engine(canvas, antialias, options) {
  5173. var _this = this;
  5174. // Public members
  5175. this.isFullscreen = false;
  5176. this.isPointerLock = false;
  5177. this.cullBackFaces = true;
  5178. this.renderEvenInBackground = true;
  5179. this.scenes = new Array();
  5180. this._windowIsBackground = false;
  5181. this._loadingDivBackgroundColor = "black";
  5182. this._drawCalls = 0;
  5183. this._renderingQueueLaunched = false;
  5184. this._activeRenderLoops = [];
  5185. // FPS
  5186. this.fpsRange = 60;
  5187. this.previousFramesDuration = [];
  5188. this.fps = 60;
  5189. this.deltaTime = 0;
  5190. // States
  5191. this._depthCullingState = new _DepthCullingState();
  5192. this._alphaState = new _AlphaState();
  5193. this._alphaMode = Engine.ALPHA_DISABLE;
  5194. // Cache
  5195. this._loadedTexturesCache = new Array();
  5196. this._activeTexturesCache = new Array();
  5197. this._compiledEffects = {};
  5198. this._uintIndicesCurrentlySet = false;
  5199. this._renderingCanvas = canvas;
  5200. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5201. options = options || {};
  5202. options.antialias = antialias;
  5203. try {
  5204. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  5205. }
  5206. catch (e) {
  5207. throw new Error("WebGL not supported");
  5208. }
  5209. if (!this._gl) {
  5210. throw new Error("WebGL not supported");
  5211. }
  5212. this._onBlur = function () {
  5213. _this._windowIsBackground = true;
  5214. };
  5215. this._onFocus = function () {
  5216. _this._windowIsBackground = false;
  5217. };
  5218. window.addEventListener("blur", this._onBlur);
  5219. window.addEventListener("focus", this._onFocus);
  5220. // Viewport
  5221. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5222. this.resize();
  5223. // Caps
  5224. this._caps = new EngineCapabilities();
  5225. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5226. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5227. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5228. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5229. // Infos
  5230. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5231. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5232. if (rendererInfo != null) {
  5233. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5234. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5235. }
  5236. if (!this._glVendor) {
  5237. this._glVendor = "Unknown vendor";
  5238. }
  5239. if (!this._glRenderer) {
  5240. this._glRenderer = "Unknown renderer";
  5241. }
  5242. // Extensions
  5243. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5244. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5245. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5246. 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');
  5247. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5248. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5249. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5250. this._caps.highPrecisionShaderSupported = true;
  5251. if (this._gl.getShaderPrecisionFormat) {
  5252. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5253. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5254. }
  5255. // Depth buffer
  5256. this.setDepthBuffer(true);
  5257. this.setDepthFunctionToLessOrEqual();
  5258. this.setDepthWrite(true);
  5259. // Fullscreen
  5260. this._onFullscreenChange = function () {
  5261. if (document.fullscreen !== undefined) {
  5262. _this.isFullscreen = document.fullscreen;
  5263. }
  5264. else if (document.mozFullScreen !== undefined) {
  5265. _this.isFullscreen = document.mozFullScreen;
  5266. }
  5267. else if (document.webkitIsFullScreen !== undefined) {
  5268. _this.isFullscreen = document.webkitIsFullScreen;
  5269. }
  5270. else if (document.msIsFullScreen !== undefined) {
  5271. _this.isFullscreen = document.msIsFullScreen;
  5272. }
  5273. // Pointer lock
  5274. if (_this.isFullscreen && _this._pointerLockRequested) {
  5275. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  5276. if (canvas.requestPointerLock) {
  5277. canvas.requestPointerLock();
  5278. }
  5279. }
  5280. };
  5281. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5282. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5283. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5284. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5285. // Pointer lock
  5286. this._onPointerLockChange = function () {
  5287. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  5288. };
  5289. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5290. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5291. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5292. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5293. if (!Engine.audioEngine) {
  5294. Engine.audioEngine = new BABYLON.AudioEngine();
  5295. }
  5296. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5297. }
  5298. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5299. get: function () {
  5300. return Engine._ALPHA_DISABLE;
  5301. },
  5302. enumerable: true,
  5303. configurable: true
  5304. });
  5305. Object.defineProperty(Engine, "ALPHA_ADD", {
  5306. get: function () {
  5307. return Engine._ALPHA_ADD;
  5308. },
  5309. enumerable: true,
  5310. configurable: true
  5311. });
  5312. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5313. get: function () {
  5314. return Engine._ALPHA_COMBINE;
  5315. },
  5316. enumerable: true,
  5317. configurable: true
  5318. });
  5319. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5320. get: function () {
  5321. return Engine._DELAYLOADSTATE_NONE;
  5322. },
  5323. enumerable: true,
  5324. configurable: true
  5325. });
  5326. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5327. get: function () {
  5328. return Engine._DELAYLOADSTATE_LOADED;
  5329. },
  5330. enumerable: true,
  5331. configurable: true
  5332. });
  5333. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5334. get: function () {
  5335. return Engine._DELAYLOADSTATE_LOADING;
  5336. },
  5337. enumerable: true,
  5338. configurable: true
  5339. });
  5340. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5341. get: function () {
  5342. return Engine._DELAYLOADSTATE_NOTLOADED;
  5343. },
  5344. enumerable: true,
  5345. configurable: true
  5346. });
  5347. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5348. get: function () {
  5349. return Engine._TEXTUREFORMAT_ALPHA;
  5350. },
  5351. enumerable: true,
  5352. configurable: true
  5353. });
  5354. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5355. get: function () {
  5356. return Engine._TEXTUREFORMAT_LUMINANCE;
  5357. },
  5358. enumerable: true,
  5359. configurable: true
  5360. });
  5361. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5362. get: function () {
  5363. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5364. },
  5365. enumerable: true,
  5366. configurable: true
  5367. });
  5368. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5369. get: function () {
  5370. return Engine._TEXTUREFORMAT_RGB;
  5371. },
  5372. enumerable: true,
  5373. configurable: true
  5374. });
  5375. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5376. get: function () {
  5377. return Engine._TEXTUREFORMAT_RGBA;
  5378. },
  5379. enumerable: true,
  5380. configurable: true
  5381. });
  5382. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5383. get: function () {
  5384. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5385. },
  5386. enumerable: true,
  5387. configurable: true
  5388. });
  5389. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5390. get: function () {
  5391. return Engine._TEXTURETYPE_FLOAT;
  5392. },
  5393. enumerable: true,
  5394. configurable: true
  5395. });
  5396. Object.defineProperty(Engine, "Version", {
  5397. get: function () {
  5398. return "2.1.0 beta";
  5399. },
  5400. enumerable: true,
  5401. configurable: true
  5402. });
  5403. Engine.prototype._prepareWorkingCanvas = function () {
  5404. if (this._workingCanvas) {
  5405. return;
  5406. }
  5407. this._workingCanvas = document.createElement("canvas");
  5408. this._workingContext = this._workingCanvas.getContext("2d");
  5409. };
  5410. Engine.prototype.getGlInfo = function () {
  5411. return {
  5412. vendor: this._glVendor,
  5413. renderer: this._glRenderer,
  5414. version: this._glVersion
  5415. };
  5416. };
  5417. Engine.prototype.getAspectRatio = function (camera) {
  5418. var viewport = camera.viewport;
  5419. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5420. };
  5421. Engine.prototype.getRenderWidth = function () {
  5422. if (this._currentRenderTarget) {
  5423. return this._currentRenderTarget._width;
  5424. }
  5425. return this._renderingCanvas.width;
  5426. };
  5427. Engine.prototype.getRenderHeight = function () {
  5428. if (this._currentRenderTarget) {
  5429. return this._currentRenderTarget._height;
  5430. }
  5431. return this._renderingCanvas.height;
  5432. };
  5433. Engine.prototype.getRenderingCanvas = function () {
  5434. return this._renderingCanvas;
  5435. };
  5436. Engine.prototype.getRenderingCanvasClientRect = function () {
  5437. return this._renderingCanvas.getBoundingClientRect();
  5438. };
  5439. Engine.prototype.setHardwareScalingLevel = function (level) {
  5440. this._hardwareScalingLevel = level;
  5441. this.resize();
  5442. };
  5443. Engine.prototype.getHardwareScalingLevel = function () {
  5444. return this._hardwareScalingLevel;
  5445. };
  5446. Engine.prototype.getLoadedTexturesCache = function () {
  5447. return this._loadedTexturesCache;
  5448. };
  5449. Engine.prototype.getCaps = function () {
  5450. return this._caps;
  5451. };
  5452. Object.defineProperty(Engine.prototype, "drawCalls", {
  5453. get: function () {
  5454. return this._drawCalls;
  5455. },
  5456. enumerable: true,
  5457. configurable: true
  5458. });
  5459. // Methods
  5460. Engine.prototype.resetDrawCalls = function () {
  5461. this._drawCalls = 0;
  5462. };
  5463. Engine.prototype.setDepthFunctionToGreater = function () {
  5464. this._depthCullingState.depthFunc = this._gl.GREATER;
  5465. };
  5466. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5467. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5468. };
  5469. Engine.prototype.setDepthFunctionToLess = function () {
  5470. this._depthCullingState.depthFunc = this._gl.LESS;
  5471. };
  5472. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5473. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5474. };
  5475. /**
  5476. * stop executing a render loop function and remove it from the execution array
  5477. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5478. */
  5479. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5480. if (!renderFunction) {
  5481. this._activeRenderLoops = [];
  5482. return;
  5483. }
  5484. var index = this._activeRenderLoops.indexOf(renderFunction);
  5485. if (index >= 0) {
  5486. this._activeRenderLoops.splice(index, 1);
  5487. }
  5488. };
  5489. Engine.prototype._renderLoop = function () {
  5490. var _this = this;
  5491. var shouldRender = true;
  5492. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5493. shouldRender = false;
  5494. }
  5495. if (shouldRender) {
  5496. // Start new frame
  5497. this.beginFrame();
  5498. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5499. var renderFunction = this._activeRenderLoops[index];
  5500. renderFunction();
  5501. }
  5502. // Present
  5503. this.endFrame();
  5504. }
  5505. if (this._activeRenderLoops.length > 0) {
  5506. // Register new frame
  5507. BABYLON.Tools.QueueNewFrame(function () {
  5508. _this._renderLoop();
  5509. });
  5510. }
  5511. else {
  5512. this._renderingQueueLaunched = false;
  5513. }
  5514. };
  5515. /**
  5516. * Register and execute a render loop. The engine can have more than one render function.
  5517. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5518. * @example
  5519. * engine.runRenderLoop(function () {
  5520. * scene.render()
  5521. * })
  5522. */
  5523. Engine.prototype.runRenderLoop = function (renderFunction) {
  5524. var _this = this;
  5525. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5526. return;
  5527. }
  5528. this._activeRenderLoops.push(renderFunction);
  5529. if (!this._renderingQueueLaunched) {
  5530. this._renderingQueueLaunched = true;
  5531. BABYLON.Tools.QueueNewFrame(function () {
  5532. _this._renderLoop();
  5533. });
  5534. }
  5535. };
  5536. /**
  5537. * Toggle full screen mode.
  5538. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5539. */
  5540. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5541. if (this.isFullscreen) {
  5542. BABYLON.Tools.ExitFullscreen();
  5543. }
  5544. else {
  5545. this._pointerLockRequested = requestPointerLock;
  5546. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5547. }
  5548. };
  5549. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5550. this.applyStates();
  5551. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5552. if (this._depthCullingState.depthMask) {
  5553. this._gl.clearDepth(1.0);
  5554. }
  5555. var mode = 0;
  5556. if (backBuffer)
  5557. mode |= this._gl.COLOR_BUFFER_BIT;
  5558. if (depthStencil && this._depthCullingState.depthMask)
  5559. mode |= this._gl.DEPTH_BUFFER_BIT;
  5560. this._gl.clear(mode);
  5561. };
  5562. /**
  5563. * Set the WebGL's viewport
  5564. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5565. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5566. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5567. */
  5568. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5569. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5570. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5571. var x = viewport.x || 0;
  5572. var y = viewport.y || 0;
  5573. this._cachedViewport = viewport;
  5574. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5575. };
  5576. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5577. this._cachedViewport = null;
  5578. this._gl.viewport(x, y, width, height);
  5579. };
  5580. Engine.prototype.beginFrame = function () {
  5581. this._measureFps();
  5582. };
  5583. Engine.prototype.endFrame = function () {
  5584. //this.flushFramebuffer();
  5585. };
  5586. /**
  5587. * resize the view according to the canvas' size.
  5588. * @example
  5589. * window.addEventListener("resize", function () {
  5590. * engine.resize();
  5591. * });
  5592. */
  5593. Engine.prototype.resize = function () {
  5594. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5595. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5596. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5597. };
  5598. /**
  5599. * force a specific size of the canvas
  5600. * @param {number} width - the new canvas' width
  5601. * @param {number} height - the new canvas' height
  5602. */
  5603. Engine.prototype.setSize = function (width, height) {
  5604. this._renderingCanvas.width = width;
  5605. this._renderingCanvas.height = height;
  5606. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5607. for (var index = 0; index < this.scenes.length; index++) {
  5608. var scene = this.scenes[index];
  5609. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5610. var cam = scene.cameras[camIndex];
  5611. cam._currentRenderId = 0;
  5612. }
  5613. }
  5614. };
  5615. Engine.prototype.bindFramebuffer = function (texture) {
  5616. this._currentRenderTarget = texture;
  5617. var gl = this._gl;
  5618. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5619. this._gl.viewport(0, 0, texture._width, texture._height);
  5620. this.wipeCaches();
  5621. };
  5622. Engine.prototype.unBindFramebuffer = function (texture) {
  5623. this._currentRenderTarget = null;
  5624. if (texture.generateMipMaps) {
  5625. var gl = this._gl;
  5626. gl.bindTexture(gl.TEXTURE_2D, texture);
  5627. gl.generateMipmap(gl.TEXTURE_2D);
  5628. gl.bindTexture(gl.TEXTURE_2D, null);
  5629. }
  5630. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5631. };
  5632. Engine.prototype.flushFramebuffer = function () {
  5633. this._gl.flush();
  5634. };
  5635. Engine.prototype.restoreDefaultFramebuffer = function () {
  5636. this._currentRenderTarget = null;
  5637. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5638. this.setViewport(this._cachedViewport);
  5639. this.wipeCaches();
  5640. };
  5641. // VBOs
  5642. Engine.prototype._resetVertexBufferBinding = function () {
  5643. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5644. this._cachedVertexBuffers = null;
  5645. };
  5646. Engine.prototype.createVertexBuffer = function (vertices) {
  5647. var vbo = this._gl.createBuffer();
  5648. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5649. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5650. this._resetVertexBufferBinding();
  5651. vbo.references = 1;
  5652. return vbo;
  5653. };
  5654. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5655. var vbo = this._gl.createBuffer();
  5656. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5657. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5658. this._resetVertexBufferBinding();
  5659. vbo.references = 1;
  5660. return vbo;
  5661. };
  5662. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5663. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5664. if (offset === undefined) {
  5665. offset = 0;
  5666. }
  5667. if (vertices instanceof Float32Array) {
  5668. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5669. }
  5670. else {
  5671. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5672. }
  5673. this._resetVertexBufferBinding();
  5674. };
  5675. Engine.prototype._resetIndexBufferBinding = function () {
  5676. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5677. this._cachedIndexBuffer = null;
  5678. };
  5679. Engine.prototype.createIndexBuffer = function (indices) {
  5680. var vbo = this._gl.createBuffer();
  5681. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5682. // Check for 32 bits indices
  5683. var arrayBuffer;
  5684. var need32Bits = false;
  5685. if (this._caps.uintIndices) {
  5686. for (var index = 0; index < indices.length; index++) {
  5687. if (indices[index] > 65535) {
  5688. need32Bits = true;
  5689. break;
  5690. }
  5691. }
  5692. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5693. }
  5694. else {
  5695. arrayBuffer = new Uint16Array(indices);
  5696. }
  5697. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5698. this._resetIndexBufferBinding();
  5699. vbo.references = 1;
  5700. vbo.is32Bits = need32Bits;
  5701. return vbo;
  5702. };
  5703. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5704. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5705. this._cachedVertexBuffers = vertexBuffer;
  5706. this._cachedEffectForVertexBuffers = effect;
  5707. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5708. var offset = 0;
  5709. for (var index = 0; index < vertexDeclaration.length; index++) {
  5710. var order = effect.getAttributeLocation(index);
  5711. if (order >= 0) {
  5712. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5713. }
  5714. offset += vertexDeclaration[index] * 4;
  5715. }
  5716. }
  5717. if (this._cachedIndexBuffer !== indexBuffer) {
  5718. this._cachedIndexBuffer = indexBuffer;
  5719. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5720. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5721. }
  5722. };
  5723. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5724. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5725. this._cachedVertexBuffers = vertexBuffers;
  5726. this._cachedEffectForVertexBuffers = effect;
  5727. var attributes = effect.getAttributesNames();
  5728. for (var index = 0; index < attributes.length; index++) {
  5729. var order = effect.getAttributeLocation(index);
  5730. if (order >= 0) {
  5731. var vertexBuffer = vertexBuffers[attributes[index]];
  5732. if (!vertexBuffer) {
  5733. continue;
  5734. }
  5735. var stride = vertexBuffer.getStrideSize();
  5736. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5737. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5738. }
  5739. }
  5740. }
  5741. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5742. this._cachedIndexBuffer = indexBuffer;
  5743. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5744. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5745. }
  5746. };
  5747. Engine.prototype._releaseBuffer = function (buffer) {
  5748. buffer.references--;
  5749. if (buffer.references === 0) {
  5750. this._gl.deleteBuffer(buffer);
  5751. return true;
  5752. }
  5753. return false;
  5754. };
  5755. Engine.prototype.createInstancesBuffer = function (capacity) {
  5756. var buffer = this._gl.createBuffer();
  5757. buffer.capacity = capacity;
  5758. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5759. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5760. return buffer;
  5761. };
  5762. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5763. this._gl.deleteBuffer(buffer);
  5764. };
  5765. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5766. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5767. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5768. for (var index = 0; index < 4; index++) {
  5769. var offsetLocation = offsetLocations[index];
  5770. this._gl.enableVertexAttribArray(offsetLocation);
  5771. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5772. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5773. }
  5774. };
  5775. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5776. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5777. for (var index = 0; index < 4; index++) {
  5778. var offsetLocation = offsetLocations[index];
  5779. this._gl.disableVertexAttribArray(offsetLocation);
  5780. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5781. }
  5782. };
  5783. Engine.prototype.applyStates = function () {
  5784. this._depthCullingState.apply(this._gl);
  5785. this._alphaState.apply(this._gl);
  5786. };
  5787. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5788. // Apply states
  5789. this.applyStates();
  5790. this._drawCalls++;
  5791. // Render
  5792. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5793. if (instancesCount) {
  5794. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  5795. return;
  5796. }
  5797. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  5798. };
  5799. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5800. // Apply states
  5801. this.applyStates();
  5802. this._drawCalls++;
  5803. if (instancesCount) {
  5804. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5805. return;
  5806. }
  5807. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5808. };
  5809. // Shaders
  5810. Engine.prototype._releaseEffect = function (effect) {
  5811. if (this._compiledEffects[effect._key]) {
  5812. delete this._compiledEffects[effect._key];
  5813. if (effect.getProgram()) {
  5814. this._gl.deleteProgram(effect.getProgram());
  5815. }
  5816. }
  5817. };
  5818. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5819. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5820. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5821. var name = vertex + "+" + fragment + "@" + defines;
  5822. if (this._compiledEffects[name]) {
  5823. return this._compiledEffects[name];
  5824. }
  5825. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5826. effect._key = name;
  5827. this._compiledEffects[name] = effect;
  5828. return effect;
  5829. };
  5830. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5831. if (uniformsNames === void 0) { uniformsNames = []; }
  5832. if (samplers === void 0) { samplers = []; }
  5833. if (defines === void 0) { defines = ""; }
  5834. return this.createEffect({
  5835. vertex: "particles",
  5836. fragmentElement: fragmentName
  5837. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5838. };
  5839. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5840. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5841. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5842. var shaderProgram = this._gl.createProgram();
  5843. this._gl.attachShader(shaderProgram, vertexShader);
  5844. this._gl.attachShader(shaderProgram, fragmentShader);
  5845. this._gl.linkProgram(shaderProgram);
  5846. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5847. if (!linked) {
  5848. var error = this._gl.getProgramInfoLog(shaderProgram);
  5849. if (error) {
  5850. throw new Error(error);
  5851. }
  5852. }
  5853. this._gl.deleteShader(vertexShader);
  5854. this._gl.deleteShader(fragmentShader);
  5855. return shaderProgram;
  5856. };
  5857. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5858. var results = [];
  5859. for (var index = 0; index < uniformsNames.length; index++) {
  5860. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5861. }
  5862. return results;
  5863. };
  5864. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5865. var results = [];
  5866. for (var index = 0; index < attributesNames.length; index++) {
  5867. try {
  5868. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5869. }
  5870. catch (e) {
  5871. results.push(-1);
  5872. }
  5873. }
  5874. return results;
  5875. };
  5876. Engine.prototype.enableEffect = function (effect) {
  5877. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5878. if (effect && effect.onBind) {
  5879. effect.onBind(effect);
  5880. }
  5881. return;
  5882. }
  5883. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5884. // Use program
  5885. this._gl.useProgram(effect.getProgram());
  5886. for (var i in this._vertexAttribArrays) {
  5887. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5888. continue;
  5889. }
  5890. this._vertexAttribArrays[i] = false;
  5891. this._gl.disableVertexAttribArray(i);
  5892. }
  5893. var attributesCount = effect.getAttributesCount();
  5894. for (var index = 0; index < attributesCount; index++) {
  5895. // Attributes
  5896. var order = effect.getAttributeLocation(index);
  5897. if (order >= 0) {
  5898. this._vertexAttribArrays[order] = true;
  5899. this._gl.enableVertexAttribArray(order);
  5900. }
  5901. }
  5902. this._currentEffect = effect;
  5903. if (effect.onBind) {
  5904. effect.onBind(effect);
  5905. }
  5906. };
  5907. Engine.prototype.setArray = function (uniform, array) {
  5908. if (!uniform)
  5909. return;
  5910. this._gl.uniform1fv(uniform, array);
  5911. };
  5912. Engine.prototype.setArray2 = function (uniform, array) {
  5913. if (!uniform || array.length % 2 !== 0)
  5914. return;
  5915. this._gl.uniform2fv(uniform, array);
  5916. };
  5917. Engine.prototype.setArray3 = function (uniform, array) {
  5918. if (!uniform || array.length % 3 !== 0)
  5919. return;
  5920. this._gl.uniform3fv(uniform, array);
  5921. };
  5922. Engine.prototype.setArray4 = function (uniform, array) {
  5923. if (!uniform || array.length % 4 !== 0)
  5924. return;
  5925. this._gl.uniform4fv(uniform, array);
  5926. };
  5927. Engine.prototype.setMatrices = function (uniform, matrices) {
  5928. if (!uniform)
  5929. return;
  5930. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5931. };
  5932. Engine.prototype.setMatrix = function (uniform, matrix) {
  5933. if (!uniform)
  5934. return;
  5935. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5936. };
  5937. Engine.prototype.setFloat = function (uniform, value) {
  5938. if (!uniform)
  5939. return;
  5940. this._gl.uniform1f(uniform, value);
  5941. };
  5942. Engine.prototype.setFloat2 = function (uniform, x, y) {
  5943. if (!uniform)
  5944. return;
  5945. this._gl.uniform2f(uniform, x, y);
  5946. };
  5947. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  5948. if (!uniform)
  5949. return;
  5950. this._gl.uniform3f(uniform, x, y, z);
  5951. };
  5952. Engine.prototype.setBool = function (uniform, bool) {
  5953. if (!uniform)
  5954. return;
  5955. this._gl.uniform1i(uniform, bool);
  5956. };
  5957. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  5958. if (!uniform)
  5959. return;
  5960. this._gl.uniform4f(uniform, x, y, z, w);
  5961. };
  5962. Engine.prototype.setColor3 = function (uniform, color3) {
  5963. if (!uniform)
  5964. return;
  5965. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  5966. };
  5967. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  5968. if (!uniform)
  5969. return;
  5970. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  5971. };
  5972. // States
  5973. Engine.prototype.setState = function (culling, zOffset, force) {
  5974. if (zOffset === void 0) { zOffset = 0; }
  5975. // Culling
  5976. if (this._depthCullingState.cull !== culling || force) {
  5977. if (culling) {
  5978. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  5979. this._depthCullingState.cull = true;
  5980. }
  5981. else {
  5982. this._depthCullingState.cull = false;
  5983. }
  5984. }
  5985. // Z offset
  5986. this._depthCullingState.zOffset = zOffset;
  5987. };
  5988. Engine.prototype.setDepthBuffer = function (enable) {
  5989. this._depthCullingState.depthTest = enable;
  5990. };
  5991. Engine.prototype.getDepthWrite = function () {
  5992. return this._depthCullingState.depthMask;
  5993. };
  5994. Engine.prototype.setDepthWrite = function (enable) {
  5995. this._depthCullingState.depthMask = enable;
  5996. };
  5997. Engine.prototype.setColorWrite = function (enable) {
  5998. this._gl.colorMask(enable, enable, enable, enable);
  5999. };
  6000. Engine.prototype.setAlphaMode = function (mode) {
  6001. switch (mode) {
  6002. case Engine.ALPHA_DISABLE:
  6003. this.setDepthWrite(true);
  6004. this._alphaState.alphaBlend = false;
  6005. break;
  6006. case Engine.ALPHA_COMBINE:
  6007. this.setDepthWrite(false);
  6008. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6009. this._alphaState.alphaBlend = true;
  6010. break;
  6011. case Engine.ALPHA_ADD:
  6012. this.setDepthWrite(false);
  6013. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6014. this._alphaState.alphaBlend = true;
  6015. break;
  6016. }
  6017. this._alphaMode = mode;
  6018. };
  6019. Engine.prototype.getAlphaMode = function () {
  6020. return this._alphaMode;
  6021. };
  6022. Engine.prototype.setAlphaTesting = function (enable) {
  6023. this._alphaTest = enable;
  6024. };
  6025. Engine.prototype.getAlphaTesting = function () {
  6026. return this._alphaTest;
  6027. };
  6028. // Textures
  6029. Engine.prototype.wipeCaches = function () {
  6030. this._activeTexturesCache = [];
  6031. this._currentEffect = null;
  6032. this._depthCullingState.reset();
  6033. this._alphaState.reset();
  6034. this._cachedVertexBuffers = null;
  6035. this._cachedIndexBuffer = null;
  6036. this._cachedEffectForVertexBuffers = null;
  6037. };
  6038. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6039. var gl = this._gl;
  6040. gl.bindTexture(gl.TEXTURE_2D, texture);
  6041. var magFilter = gl.NEAREST;
  6042. var minFilter = gl.NEAREST;
  6043. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6044. magFilter = gl.LINEAR;
  6045. minFilter = gl.LINEAR;
  6046. }
  6047. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6048. magFilter = gl.LINEAR;
  6049. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6050. }
  6051. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6052. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6053. gl.bindTexture(gl.TEXTURE_2D, null);
  6054. texture.samplingMode = samplingMode;
  6055. };
  6056. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6057. var _this = this;
  6058. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6059. if (onLoad === void 0) { onLoad = null; }
  6060. if (onError === void 0) { onError = null; }
  6061. if (buffer === void 0) { buffer = null; }
  6062. var texture = this._gl.createTexture();
  6063. var extension;
  6064. var fromData = false;
  6065. if (url.substr(0, 5) === "data:") {
  6066. fromData = true;
  6067. }
  6068. if (!fromData)
  6069. extension = url.substr(url.length - 4, 4).toLowerCase();
  6070. else {
  6071. var oldUrl = url;
  6072. fromData = oldUrl.split(':');
  6073. url = oldUrl;
  6074. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6075. }
  6076. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6077. var isTGA = (extension === ".tga");
  6078. scene._addPendingData(texture);
  6079. texture.url = url;
  6080. texture.noMipmap = noMipmap;
  6081. texture.references = 1;
  6082. texture.samplingMode = samplingMode;
  6083. this._loadedTexturesCache.push(texture);
  6084. var onerror = function () {
  6085. scene._removePendingData(texture);
  6086. if (onError) {
  6087. onError();
  6088. }
  6089. };
  6090. if (isTGA) {
  6091. var callback = function (arrayBuffer) {
  6092. var data = new Uint8Array(arrayBuffer);
  6093. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6094. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6095. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6096. if (onLoad) {
  6097. onLoad();
  6098. }
  6099. }, samplingMode);
  6100. };
  6101. if (!(fromData instanceof Array))
  6102. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6103. callback(arrayBuffer);
  6104. }, onerror, scene.database, true);
  6105. else
  6106. callback(buffer);
  6107. }
  6108. else if (isDDS) {
  6109. callback = function (data) {
  6110. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6111. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6112. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6113. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6114. if (onLoad) {
  6115. onLoad();
  6116. }
  6117. }, samplingMode);
  6118. };
  6119. if (!(fromData instanceof Array))
  6120. BABYLON.Tools.LoadFile(url, function (data) {
  6121. callback(data);
  6122. }, onerror, scene.database, true);
  6123. else
  6124. callback(buffer);
  6125. }
  6126. else {
  6127. var onload = function (img) {
  6128. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6129. var isPot = (img.width === potWidth && img.height === potHeight);
  6130. if (!isPot) {
  6131. _this._prepareWorkingCanvas();
  6132. _this._workingCanvas.width = potWidth;
  6133. _this._workingCanvas.height = potHeight;
  6134. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6135. _this._workingContext.imageSmoothingEnabled = false;
  6136. _this._workingContext.mozImageSmoothingEnabled = false;
  6137. _this._workingContext.oImageSmoothingEnabled = false;
  6138. _this._workingContext.webkitImageSmoothingEnabled = false;
  6139. _this._workingContext.msImageSmoothingEnabled = false;
  6140. }
  6141. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6142. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6143. _this._workingContext.imageSmoothingEnabled = true;
  6144. _this._workingContext.mozImageSmoothingEnabled = true;
  6145. _this._workingContext.oImageSmoothingEnabled = true;
  6146. _this._workingContext.webkitImageSmoothingEnabled = true;
  6147. _this._workingContext.msImageSmoothingEnabled = true;
  6148. }
  6149. }
  6150. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6151. if (onLoad) {
  6152. onLoad();
  6153. }
  6154. }, samplingMode);
  6155. };
  6156. if (!(fromData instanceof Array))
  6157. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6158. else
  6159. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6160. }
  6161. return texture;
  6162. };
  6163. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  6164. var texture = this._gl.createTexture();
  6165. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6166. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6167. // Format
  6168. var internalFormat = this._gl.RGBA;
  6169. switch (format) {
  6170. case Engine.TEXTUREFORMAT_ALPHA:
  6171. internalFormat = this._gl.ALPHA;
  6172. break;
  6173. case Engine.TEXTUREFORMAT_LUMINANCE:
  6174. internalFormat = this._gl.LUMINANCE;
  6175. break;
  6176. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6177. internalFormat = this._gl.LUMINANCE_ALPHA;
  6178. break;
  6179. case Engine.TEXTUREFORMAT_RGB:
  6180. internalFormat = this._gl.RGB;
  6181. break;
  6182. case Engine.TEXTUREFORMAT_RGBA:
  6183. internalFormat = this._gl.RGBA;
  6184. break;
  6185. }
  6186. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6187. if (generateMipMaps) {
  6188. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6189. }
  6190. // Filters
  6191. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6192. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6193. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6194. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6195. this._activeTexturesCache = [];
  6196. texture._baseWidth = width;
  6197. texture._baseHeight = height;
  6198. texture._width = width;
  6199. texture._height = height;
  6200. texture.isReady = true;
  6201. texture.references = 1;
  6202. texture.samplingMode = samplingMode;
  6203. this._loadedTexturesCache.push(texture);
  6204. return texture;
  6205. };
  6206. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  6207. var texture = this._gl.createTexture();
  6208. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6209. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6210. this._activeTexturesCache = [];
  6211. texture._baseWidth = width;
  6212. texture._baseHeight = height;
  6213. texture._width = width;
  6214. texture._height = height;
  6215. texture.isReady = false;
  6216. texture.generateMipMaps = generateMipMaps;
  6217. texture.references = 1;
  6218. texture.samplingMode = samplingMode;
  6219. this.updateTextureSamplingMode(samplingMode, texture);
  6220. this._loadedTexturesCache.push(texture);
  6221. return texture;
  6222. };
  6223. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6224. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6225. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6226. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6227. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6228. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6229. };
  6230. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6231. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6232. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6233. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6234. if (texture.generateMipMaps) {
  6235. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6236. }
  6237. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6238. this._activeTexturesCache = [];
  6239. texture.isReady = true;
  6240. };
  6241. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6242. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6243. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6244. // Scale the video if it is a NPOT using the current working canvas
  6245. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  6246. if (!texture._workingCanvas) {
  6247. texture._workingCanvas = document.createElement("canvas");
  6248. texture._workingContext = texture._workingCanvas.getContext("2d");
  6249. texture._workingCanvas.width = texture._width;
  6250. texture._workingCanvas.height = texture._height;
  6251. }
  6252. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6253. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6254. }
  6255. else {
  6256. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6257. }
  6258. if (texture.generateMipMaps) {
  6259. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6260. }
  6261. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6262. this._activeTexturesCache = [];
  6263. texture.isReady = true;
  6264. };
  6265. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6266. // old version had a "generateMipMaps" arg instead of options.
  6267. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6268. // in the same way, generateDepthBuffer is defaulted to true
  6269. var generateMipMaps = false;
  6270. var generateDepthBuffer = true;
  6271. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6272. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6273. if (options !== undefined) {
  6274. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6275. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6276. type = options.type === undefined ? type : options.type;
  6277. if (options.samplingMode !== undefined) {
  6278. samplingMode = options.samplingMode;
  6279. }
  6280. if (type === Engine.TEXTURETYPE_FLOAT) {
  6281. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6282. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6283. }
  6284. }
  6285. var gl = this._gl;
  6286. var texture = gl.createTexture();
  6287. gl.bindTexture(gl.TEXTURE_2D, texture);
  6288. var width = size.width || size;
  6289. var height = size.height || size;
  6290. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6291. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6292. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6293. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6294. }
  6295. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6296. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6297. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6298. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6299. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6300. var depthBuffer;
  6301. // Create the depth buffer
  6302. if (generateDepthBuffer) {
  6303. depthBuffer = gl.createRenderbuffer();
  6304. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6305. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6306. }
  6307. // Create the framebuffer
  6308. var framebuffer = gl.createFramebuffer();
  6309. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6310. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6311. if (generateDepthBuffer) {
  6312. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6313. }
  6314. // Unbind
  6315. gl.bindTexture(gl.TEXTURE_2D, null);
  6316. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6317. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6318. texture._framebuffer = framebuffer;
  6319. if (generateDepthBuffer) {
  6320. texture._depthBuffer = depthBuffer;
  6321. }
  6322. texture._width = width;
  6323. texture._height = height;
  6324. texture.isReady = true;
  6325. texture.generateMipMaps = generateMipMaps;
  6326. texture.references = 1;
  6327. texture.samplingMode = samplingMode;
  6328. this._activeTexturesCache = [];
  6329. this._loadedTexturesCache.push(texture);
  6330. return texture;
  6331. };
  6332. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6333. var _this = this;
  6334. var gl = this._gl;
  6335. var texture = gl.createTexture();
  6336. texture.isCube = true;
  6337. texture.url = rootUrl;
  6338. texture.references = 1;
  6339. this._loadedTexturesCache.push(texture);
  6340. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6341. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6342. if (isDDS) {
  6343. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6344. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6345. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6346. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6347. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6348. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6349. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6350. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6351. }
  6352. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6353. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6354. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6355. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6356. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6357. _this._activeTexturesCache = [];
  6358. texture._width = info.width;
  6359. texture._height = info.height;
  6360. texture.isReady = true;
  6361. }, null, null, true);
  6362. }
  6363. else {
  6364. cascadeLoad(rootUrl, scene, function (imgs) {
  6365. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6366. var height = width;
  6367. _this._prepareWorkingCanvas();
  6368. _this._workingCanvas.width = width;
  6369. _this._workingCanvas.height = height;
  6370. var faces = [
  6371. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  6372. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  6373. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6374. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  6375. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  6376. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6377. ];
  6378. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6379. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6380. for (var index = 0; index < faces.length; index++) {
  6381. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6382. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6383. }
  6384. if (!noMipmap) {
  6385. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6386. }
  6387. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6388. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6389. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6390. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6391. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6392. _this._activeTexturesCache = [];
  6393. texture._width = width;
  6394. texture._height = height;
  6395. texture.isReady = true;
  6396. }, extensions);
  6397. }
  6398. return texture;
  6399. };
  6400. Engine.prototype._releaseTexture = function (texture) {
  6401. var gl = this._gl;
  6402. if (texture._framebuffer) {
  6403. gl.deleteFramebuffer(texture._framebuffer);
  6404. }
  6405. if (texture._depthBuffer) {
  6406. gl.deleteRenderbuffer(texture._depthBuffer);
  6407. }
  6408. gl.deleteTexture(texture);
  6409. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6410. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6411. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6412. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6413. this._activeTexturesCache[channel] = null;
  6414. }
  6415. var index = this._loadedTexturesCache.indexOf(texture);
  6416. if (index !== -1) {
  6417. this._loadedTexturesCache.splice(index, 1);
  6418. }
  6419. };
  6420. Engine.prototype.bindSamplers = function (effect) {
  6421. this._gl.useProgram(effect.getProgram());
  6422. var samplers = effect.getSamplers();
  6423. for (var index = 0; index < samplers.length; index++) {
  6424. var uniform = effect.getUniform(samplers[index]);
  6425. this._gl.uniform1i(uniform, index);
  6426. }
  6427. this._currentEffect = null;
  6428. };
  6429. Engine.prototype._bindTexture = function (channel, texture) {
  6430. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6431. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6432. this._activeTexturesCache[channel] = null;
  6433. };
  6434. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6435. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6436. };
  6437. Engine.prototype.setTexture = function (channel, texture) {
  6438. if (channel < 0) {
  6439. return;
  6440. }
  6441. // Not ready?
  6442. if (!texture || !texture.isReady()) {
  6443. if (this._activeTexturesCache[channel] != null) {
  6444. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6445. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6446. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6447. this._activeTexturesCache[channel] = null;
  6448. }
  6449. return;
  6450. }
  6451. // Video
  6452. if (texture instanceof BABYLON.VideoTexture) {
  6453. if (texture.update()) {
  6454. this._activeTexturesCache[channel] = null;
  6455. }
  6456. }
  6457. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6458. texture.delayLoad();
  6459. return;
  6460. }
  6461. if (this._activeTexturesCache[channel] === texture) {
  6462. return;
  6463. }
  6464. this._activeTexturesCache[channel] = texture;
  6465. var internalTexture = texture.getInternalTexture();
  6466. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6467. if (internalTexture.isCube) {
  6468. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6469. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6470. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6471. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6472. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6473. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6474. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6475. }
  6476. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6477. }
  6478. else {
  6479. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6480. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6481. internalTexture._cachedWrapU = texture.wrapU;
  6482. switch (texture.wrapU) {
  6483. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6484. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6485. break;
  6486. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6487. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6488. break;
  6489. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6490. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6491. break;
  6492. }
  6493. }
  6494. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6495. internalTexture._cachedWrapV = texture.wrapV;
  6496. switch (texture.wrapV) {
  6497. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6498. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6499. break;
  6500. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6501. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6502. break;
  6503. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6504. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6505. break;
  6506. }
  6507. }
  6508. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6509. }
  6510. };
  6511. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6512. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6513. var value = texture.anisotropicFilteringLevel;
  6514. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6515. value = 1;
  6516. }
  6517. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6518. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6519. texture._cachedAnisotropicFilteringLevel = value;
  6520. }
  6521. };
  6522. Engine.prototype.readPixels = function (x, y, width, height) {
  6523. var data = new Uint8Array(height * width * 4);
  6524. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6525. return data;
  6526. };
  6527. // Dispose
  6528. Engine.prototype.dispose = function () {
  6529. this.hideLoadingUI();
  6530. this.stopRenderLoop();
  6531. while (this.scenes.length) {
  6532. this.scenes[0].dispose();
  6533. }
  6534. // Release audio engine
  6535. Engine.audioEngine.dispose();
  6536. for (var name in this._compiledEffects) {
  6537. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6538. }
  6539. for (var i in this._vertexAttribArrays) {
  6540. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6541. continue;
  6542. }
  6543. this._gl.disableVertexAttribArray(i);
  6544. }
  6545. // Events
  6546. window.removeEventListener("blur", this._onBlur);
  6547. window.removeEventListener("focus", this._onFocus);
  6548. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6549. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6550. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6551. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6552. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6553. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6554. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6555. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6556. };
  6557. // Loading screen
  6558. Engine.prototype.displayLoadingUI = function () {
  6559. var _this = this;
  6560. this._loadingDiv = document.createElement("div");
  6561. this._loadingDiv.style.opacity = "0";
  6562. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6563. // Loading text
  6564. this._loadingTextDiv = document.createElement("div");
  6565. this._loadingTextDiv.style.position = "absolute";
  6566. this._loadingTextDiv.style.left = "0";
  6567. this._loadingTextDiv.style.top = "50%";
  6568. this._loadingTextDiv.style.marginTop = "80px";
  6569. this._loadingTextDiv.style.width = "100%";
  6570. this._loadingTextDiv.style.height = "20px";
  6571. this._loadingTextDiv.style.fontFamily = "Arial";
  6572. this._loadingTextDiv.style.fontSize = "14px";
  6573. this._loadingTextDiv.style.color = "white";
  6574. this._loadingTextDiv.style.textAlign = "center";
  6575. this._loadingTextDiv.innerHTML = "Loading";
  6576. this._loadingDiv.appendChild(this._loadingTextDiv);
  6577. // Loading img
  6578. var imgBack = new Image();
  6579. 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==";
  6580. imgBack.style.position = "absolute";
  6581. imgBack.style.left = "50%";
  6582. imgBack.style.top = "50%";
  6583. imgBack.style.marginLeft = "-50px";
  6584. imgBack.style.marginTop = "-50px";
  6585. imgBack.style.transition = "transform 1.0s ease";
  6586. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6587. var deg = 360;
  6588. var onTransitionEnd = function () {
  6589. deg += 360;
  6590. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6591. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6592. };
  6593. imgBack.addEventListener("transitionend", onTransitionEnd);
  6594. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6595. this._loadingDiv.appendChild(imgBack);
  6596. // front image
  6597. var imgFront = new Image();
  6598. 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=";
  6599. imgFront.style.position = "absolute";
  6600. imgFront.style.left = "50%";
  6601. imgFront.style.top = "50%";
  6602. imgFront.style.marginLeft = "-50px";
  6603. imgFront.style.marginTop = "-50px";
  6604. this._loadingDiv.appendChild(imgFront);
  6605. // Resize
  6606. this._resizeLoadingUI = function () {
  6607. var canvasRect = _this.getRenderingCanvasClientRect();
  6608. _this._loadingDiv.style.position = "absolute";
  6609. _this._loadingDiv.style.left = canvasRect.left + "px";
  6610. _this._loadingDiv.style.top = canvasRect.top + "px";
  6611. _this._loadingDiv.style.width = canvasRect.width + "px";
  6612. _this._loadingDiv.style.height = canvasRect.height + "px";
  6613. };
  6614. this._resizeLoadingUI();
  6615. window.addEventListener("resize", this._resizeLoadingUI);
  6616. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6617. document.body.appendChild(this._loadingDiv);
  6618. setTimeout(function () {
  6619. _this._loadingDiv.style.opacity = "1";
  6620. imgBack.style.transform = "rotateZ(360deg)";
  6621. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6622. }, 0);
  6623. };
  6624. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6625. set: function (text) {
  6626. if (!this._loadingDiv) {
  6627. return;
  6628. }
  6629. this._loadingTextDiv.innerHTML = text;
  6630. },
  6631. enumerable: true,
  6632. configurable: true
  6633. });
  6634. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6635. get: function () {
  6636. return this._loadingDivBackgroundColor;
  6637. },
  6638. set: function (color) {
  6639. this._loadingDivBackgroundColor = color;
  6640. if (!this._loadingDiv) {
  6641. return;
  6642. }
  6643. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6644. },
  6645. enumerable: true,
  6646. configurable: true
  6647. });
  6648. Engine.prototype.hideLoadingUI = function () {
  6649. var _this = this;
  6650. if (!this._loadingDiv) {
  6651. return;
  6652. }
  6653. var onTransitionEnd = function () {
  6654. if (!_this._loadingDiv) {
  6655. return;
  6656. }
  6657. document.body.removeChild(_this._loadingDiv);
  6658. window.removeEventListener("resize", _this._resizeLoadingUI);
  6659. _this._loadingDiv = null;
  6660. };
  6661. this._loadingDiv.style.opacity = "0";
  6662. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  6663. };
  6664. // FPS
  6665. Engine.prototype.getFps = function () {
  6666. return this.fps;
  6667. };
  6668. Engine.prototype.getDeltaTime = function () {
  6669. return this.deltaTime;
  6670. };
  6671. Engine.prototype._measureFps = function () {
  6672. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6673. var length = this.previousFramesDuration.length;
  6674. if (length >= 2) {
  6675. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6676. }
  6677. if (length >= this.fpsRange) {
  6678. if (length > this.fpsRange) {
  6679. this.previousFramesDuration.splice(0, 1);
  6680. length = this.previousFramesDuration.length;
  6681. }
  6682. var sum = 0;
  6683. for (var id = 0; id < length - 1; id++) {
  6684. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6685. }
  6686. this.fps = 1000.0 / (sum / (length - 1));
  6687. }
  6688. };
  6689. // Statics
  6690. Engine.isSupported = function () {
  6691. try {
  6692. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6693. if (navigator.isCocoonJS) {
  6694. return true;
  6695. }
  6696. var tempcanvas = document.createElement("canvas");
  6697. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6698. return gl != null && !!window.WebGLRenderingContext;
  6699. }
  6700. catch (e) {
  6701. return false;
  6702. }
  6703. };
  6704. // Const statics
  6705. Engine._ALPHA_DISABLE = 0;
  6706. Engine._ALPHA_ADD = 1;
  6707. Engine._ALPHA_COMBINE = 2;
  6708. Engine._DELAYLOADSTATE_NONE = 0;
  6709. Engine._DELAYLOADSTATE_LOADED = 1;
  6710. Engine._DELAYLOADSTATE_LOADING = 2;
  6711. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6712. Engine._TEXTUREFORMAT_ALPHA = 0;
  6713. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6714. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6715. Engine._TEXTUREFORMAT_RGB = 4;
  6716. Engine._TEXTUREFORMAT_RGBA = 4;
  6717. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6718. Engine._TEXTURETYPE_FLOAT = 1;
  6719. // Updatable statics so stick with vars here
  6720. Engine.Epsilon = 0.001;
  6721. Engine.CollisionsEpsilon = 0.001;
  6722. Engine.CodeRepository = "Babylon/";
  6723. Engine.ShadersRepository = "Babylon/Shaders/";
  6724. return Engine;
  6725. })();
  6726. BABYLON.Engine = Engine;
  6727. })(BABYLON || (BABYLON = {}));
  6728. //# sourceMappingURL=babylon.engine.js.map
  6729. var BABYLON;
  6730. (function (BABYLON) {
  6731. /**
  6732. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6733. */
  6734. var Node = (function () {
  6735. /**
  6736. * @constructor
  6737. * @param {string} name - the name and id to be given to this node
  6738. * @param {BABYLON.Scene} the scene this node will be added to
  6739. */
  6740. function Node(name, scene) {
  6741. this.state = "";
  6742. this.animations = new Array();
  6743. this._childrenFlag = -1;
  6744. this._isEnabled = true;
  6745. this._isReady = true;
  6746. this._currentRenderId = -1;
  6747. this._parentRenderId = -1;
  6748. this.name = name;
  6749. this.id = name;
  6750. this._scene = scene;
  6751. this._initCache();
  6752. }
  6753. Node.prototype.getScene = function () {
  6754. return this._scene;
  6755. };
  6756. Node.prototype.getEngine = function () {
  6757. return this._scene.getEngine();
  6758. };
  6759. // override it in derived class
  6760. Node.prototype.getWorldMatrix = function () {
  6761. return BABYLON.Matrix.Identity();
  6762. };
  6763. // override it in derived class if you add new variables to the cache
  6764. // and call the parent class method
  6765. Node.prototype._initCache = function () {
  6766. this._cache = {};
  6767. this._cache.parent = undefined;
  6768. };
  6769. Node.prototype.updateCache = function (force) {
  6770. if (!force && this.isSynchronized())
  6771. return;
  6772. this._cache.parent = this.parent;
  6773. this._updateCache();
  6774. };
  6775. // override it in derived class if you add new variables to the cache
  6776. // and call the parent class method if !ignoreParentClass
  6777. Node.prototype._updateCache = function (ignoreParentClass) {
  6778. };
  6779. // override it in derived class if you add new variables to the cache
  6780. Node.prototype._isSynchronized = function () {
  6781. return true;
  6782. };
  6783. Node.prototype._markSyncedWithParent = function () {
  6784. this._parentRenderId = this.parent._currentRenderId;
  6785. };
  6786. Node.prototype.isSynchronizedWithParent = function () {
  6787. if (!this.parent) {
  6788. return true;
  6789. }
  6790. if (this._parentRenderId !== this.parent._currentRenderId) {
  6791. return false;
  6792. }
  6793. return this.parent.isSynchronized();
  6794. };
  6795. Node.prototype.isSynchronized = function (updateCache) {
  6796. var check = this.hasNewParent();
  6797. check = check || !this.isSynchronizedWithParent();
  6798. check = check || !this._isSynchronized();
  6799. if (updateCache)
  6800. this.updateCache(true);
  6801. return !check;
  6802. };
  6803. Node.prototype.hasNewParent = function (update) {
  6804. if (this._cache.parent === this.parent)
  6805. return false;
  6806. if (update)
  6807. this._cache.parent = this.parent;
  6808. return true;
  6809. };
  6810. /**
  6811. * Is this node ready to be used/rendered
  6812. * @return {boolean} is it ready
  6813. */
  6814. Node.prototype.isReady = function () {
  6815. return this._isReady;
  6816. };
  6817. /**
  6818. * Is this node enabled.
  6819. * If the node has a parent and is enabled, the parent will be inspected as well.
  6820. * @return {boolean} whether this node (and its parent) is enabled.
  6821. * @see setEnabled
  6822. */
  6823. Node.prototype.isEnabled = function () {
  6824. if (!this._isEnabled) {
  6825. return false;
  6826. }
  6827. if (this.parent) {
  6828. return this.parent.isEnabled();
  6829. }
  6830. return true;
  6831. };
  6832. /**
  6833. * Set the enabled state of this node.
  6834. * @param {boolean} value - the new enabled state
  6835. * @see isEnabled
  6836. */
  6837. Node.prototype.setEnabled = function (value) {
  6838. this._isEnabled = value;
  6839. };
  6840. /**
  6841. * Is this node a descendant of the given node.
  6842. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6843. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6844. * @see parent
  6845. */
  6846. Node.prototype.isDescendantOf = function (ancestor) {
  6847. if (this.parent) {
  6848. if (this.parent === ancestor) {
  6849. return true;
  6850. }
  6851. return this.parent.isDescendantOf(ancestor);
  6852. }
  6853. return false;
  6854. };
  6855. Node.prototype._getDescendants = function (list, results) {
  6856. for (var index = 0; index < list.length; index++) {
  6857. var item = list[index];
  6858. if (item.isDescendantOf(this)) {
  6859. results.push(item);
  6860. }
  6861. }
  6862. };
  6863. /**
  6864. * Will return all nodes that have this node as parent.
  6865. * @return {BABYLON.Node[]} all children nodes of all types.
  6866. */
  6867. Node.prototype.getDescendants = function () {
  6868. var results = [];
  6869. this._getDescendants(this._scene.meshes, results);
  6870. this._getDescendants(this._scene.lights, results);
  6871. this._getDescendants(this._scene.cameras, results);
  6872. return results;
  6873. };
  6874. Node.prototype._setReady = function (state) {
  6875. if (state == this._isReady) {
  6876. return;
  6877. }
  6878. if (!state) {
  6879. this._isReady = false;
  6880. return;
  6881. }
  6882. this._isReady = true;
  6883. if (this.onReady) {
  6884. this.onReady(this);
  6885. }
  6886. };
  6887. return Node;
  6888. })();
  6889. BABYLON.Node = Node;
  6890. })(BABYLON || (BABYLON = {}));
  6891. //# sourceMappingURL=babylon.node.js.map
  6892. var BABYLON;
  6893. (function (BABYLON) {
  6894. var FilesInput = (function () {
  6895. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  6896. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  6897. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  6898. this._engine = p_engine;
  6899. this._canvas = p_canvas;
  6900. this._currentScene = p_scene;
  6901. this._sceneLoadedCallback = p_sceneLoadedCallback;
  6902. this._progressCallback = p_progressCallback;
  6903. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  6904. this._textureLoadingCallback = p_textureLoadingCallback;
  6905. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  6906. }
  6907. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  6908. var _this = this;
  6909. if (p_elementToMonitor) {
  6910. this._elementToMonitor = p_elementToMonitor;
  6911. this._elementToMonitor.addEventListener("dragenter", function (e) {
  6912. _this.drag(e);
  6913. }, false);
  6914. this._elementToMonitor.addEventListener("dragover", function (e) {
  6915. _this.drag(e);
  6916. }, false);
  6917. this._elementToMonitor.addEventListener("drop", function (e) {
  6918. _this.drop(e);
  6919. }, false);
  6920. }
  6921. };
  6922. FilesInput.prototype.renderFunction = function () {
  6923. if (this._additionnalRenderLoopLogicCallback) {
  6924. this._additionnalRenderLoopLogicCallback();
  6925. }
  6926. if (this._currentScene) {
  6927. if (this._textureLoadingCallback) {
  6928. var remaining = this._currentScene.getWaitingItemsCount();
  6929. if (remaining > 0) {
  6930. this._textureLoadingCallback(remaining);
  6931. }
  6932. }
  6933. this._currentScene.render();
  6934. }
  6935. };
  6936. FilesInput.prototype.drag = function (e) {
  6937. e.stopPropagation();
  6938. e.preventDefault();
  6939. };
  6940. FilesInput.prototype.drop = function (eventDrop) {
  6941. eventDrop.stopPropagation();
  6942. eventDrop.preventDefault();
  6943. this.loadFiles(eventDrop);
  6944. };
  6945. FilesInput.prototype.loadFiles = function (event) {
  6946. if (this._startingProcessingFilesCallback)
  6947. this._startingProcessingFilesCallback();
  6948. // Handling data transfer via drag'n'drop
  6949. if (event && event.dataTransfer && event.dataTransfer.files) {
  6950. this._filesToLoad = event.dataTransfer.files;
  6951. }
  6952. // Handling files from input files
  6953. if (event && event.target && event.target.files) {
  6954. this._filesToLoad = event.target.files;
  6955. }
  6956. if (this._filesToLoad && this._filesToLoad.length > 0) {
  6957. for (var i = 0; i < this._filesToLoad.length; i++) {
  6958. switch (this._filesToLoad[i].type) {
  6959. case "image/jpeg":
  6960. case "image/png":
  6961. case "image/bmp":
  6962. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  6963. break;
  6964. case "image/targa":
  6965. case "image/vnd.ms-dds":
  6966. case "audio/wav":
  6967. case "audio/x-wav":
  6968. case "audio/mp3":
  6969. case "audio/mpeg":
  6970. case "audio/mpeg3":
  6971. case "audio/x-mpeg-3":
  6972. case "audio/ogg":
  6973. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  6974. break;
  6975. default:
  6976. 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) {
  6977. this._sceneFileToLoad = this._filesToLoad[i];
  6978. }
  6979. break;
  6980. }
  6981. }
  6982. this.reload();
  6983. }
  6984. };
  6985. FilesInput.prototype.reload = function () {
  6986. var _this = this;
  6987. var that = this;
  6988. // If a ".babylon" file has been provided
  6989. if (this._sceneFileToLoad) {
  6990. if (this._currentScene) {
  6991. this._engine.stopRenderLoop();
  6992. this._currentScene.dispose();
  6993. }
  6994. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  6995. that._currentScene = newScene;
  6996. // Wait for textures and shaders to be ready
  6997. that._currentScene.executeWhenReady(function () {
  6998. // Attach camera to canvas inputs
  6999. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7000. that._currentScene.createDefaultCameraOrLight();
  7001. }
  7002. that._currentScene.activeCamera.attachControl(that._canvas);
  7003. if (that._sceneLoadedCallback) {
  7004. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7005. }
  7006. that._engine.runRenderLoop(function () {
  7007. that.renderFunction();
  7008. });
  7009. });
  7010. }, function (progress) {
  7011. if (_this._progressCallback) {
  7012. _this._progressCallback(progress);
  7013. }
  7014. });
  7015. }
  7016. else {
  7017. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7018. }
  7019. };
  7020. FilesInput.FilesTextures = new Array();
  7021. FilesInput.FilesToLoad = new Array();
  7022. return FilesInput;
  7023. })();
  7024. BABYLON.FilesInput = FilesInput;
  7025. })(BABYLON || (BABYLON = {}));
  7026. //# sourceMappingURL=babylon.filesInput.js.map
  7027. var BABYLON;
  7028. (function (BABYLON) {
  7029. var IntersectionInfo = (function () {
  7030. function IntersectionInfo(bu, bv, distance) {
  7031. this.bu = bu;
  7032. this.bv = bv;
  7033. this.distance = distance;
  7034. this.faceId = 0;
  7035. this.subMeshId = 0;
  7036. }
  7037. return IntersectionInfo;
  7038. })();
  7039. BABYLON.IntersectionInfo = IntersectionInfo;
  7040. var PickingInfo = (function () {
  7041. function PickingInfo() {
  7042. this.hit = false;
  7043. this.distance = 0;
  7044. this.pickedPoint = null;
  7045. this.pickedMesh = null;
  7046. this.bu = 0;
  7047. this.bv = 0;
  7048. this.faceId = -1;
  7049. this.subMeshId = 0;
  7050. }
  7051. // Methods
  7052. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  7053. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7054. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7055. return null;
  7056. }
  7057. var indices = this.pickedMesh.getIndices();
  7058. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7059. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7060. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7061. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7062. normal0 = normal0.scale(this.bu);
  7063. normal1 = normal1.scale(this.bv);
  7064. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7065. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7066. if (useWorldCoordinates) {
  7067. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7068. }
  7069. return result;
  7070. };
  7071. PickingInfo.prototype.getTextureCoordinates = function () {
  7072. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7073. return null;
  7074. }
  7075. var indices = this.pickedMesh.getIndices();
  7076. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7077. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7078. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7079. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7080. uv0 = uv0.scale(this.bu);
  7081. uv1 = uv1.scale(this.bv);
  7082. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  7083. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7084. };
  7085. return PickingInfo;
  7086. })();
  7087. BABYLON.PickingInfo = PickingInfo;
  7088. })(BABYLON || (BABYLON = {}));
  7089. //# sourceMappingURL=babylon.pickingInfo.js.map
  7090. var BABYLON;
  7091. (function (BABYLON) {
  7092. var BoundingSphere = (function () {
  7093. function BoundingSphere(minimum, maximum) {
  7094. this.minimum = minimum;
  7095. this.maximum = maximum;
  7096. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7097. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7098. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7099. this.radius = distance * 0.5;
  7100. this.centerWorld = BABYLON.Vector3.Zero();
  7101. this._update(BABYLON.Matrix.Identity());
  7102. }
  7103. // Methods
  7104. BoundingSphere.prototype._update = function (world) {
  7105. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7106. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7107. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7108. };
  7109. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7110. for (var i = 0; i < 6; i++) {
  7111. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7112. return false;
  7113. }
  7114. return true;
  7115. };
  7116. BoundingSphere.prototype.intersectsPoint = function (point) {
  7117. var x = this.centerWorld.x - point.x;
  7118. var y = this.centerWorld.y - point.y;
  7119. var z = this.centerWorld.z - point.z;
  7120. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7121. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7122. return false;
  7123. return true;
  7124. };
  7125. // Statics
  7126. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7127. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7128. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7129. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7130. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7131. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7132. return false;
  7133. return true;
  7134. };
  7135. return BoundingSphere;
  7136. })();
  7137. BABYLON.BoundingSphere = BoundingSphere;
  7138. })(BABYLON || (BABYLON = {}));
  7139. //# sourceMappingURL=babylon.boundingSphere.js.map
  7140. var BABYLON;
  7141. (function (BABYLON) {
  7142. var BoundingBox = (function () {
  7143. function BoundingBox(minimum, maximum) {
  7144. this.minimum = minimum;
  7145. this.maximum = maximum;
  7146. this.vectors = new Array();
  7147. this.vectorsWorld = new Array();
  7148. // Bounding vectors
  7149. this.vectors.push(this.minimum.clone());
  7150. this.vectors.push(this.maximum.clone());
  7151. this.vectors.push(this.minimum.clone());
  7152. this.vectors[2].x = this.maximum.x;
  7153. this.vectors.push(this.minimum.clone());
  7154. this.vectors[3].y = this.maximum.y;
  7155. this.vectors.push(this.minimum.clone());
  7156. this.vectors[4].z = this.maximum.z;
  7157. this.vectors.push(this.maximum.clone());
  7158. this.vectors[5].z = this.minimum.z;
  7159. this.vectors.push(this.maximum.clone());
  7160. this.vectors[6].x = this.minimum.x;
  7161. this.vectors.push(this.maximum.clone());
  7162. this.vectors[7].y = this.minimum.y;
  7163. // OBB
  7164. this.center = this.maximum.add(this.minimum).scale(0.5);
  7165. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7166. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7167. for (var index = 0; index < this.vectors.length; index++) {
  7168. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7169. }
  7170. this.minimumWorld = BABYLON.Vector3.Zero();
  7171. this.maximumWorld = BABYLON.Vector3.Zero();
  7172. this._update(BABYLON.Matrix.Identity());
  7173. }
  7174. // Methods
  7175. BoundingBox.prototype.getWorldMatrix = function () {
  7176. return this._worldMatrix;
  7177. };
  7178. BoundingBox.prototype._update = function (world) {
  7179. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7180. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7181. for (var index = 0; index < this.vectors.length; index++) {
  7182. var v = this.vectorsWorld[index];
  7183. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7184. if (v.x < this.minimumWorld.x)
  7185. this.minimumWorld.x = v.x;
  7186. if (v.y < this.minimumWorld.y)
  7187. this.minimumWorld.y = v.y;
  7188. if (v.z < this.minimumWorld.z)
  7189. this.minimumWorld.z = v.z;
  7190. if (v.x > this.maximumWorld.x)
  7191. this.maximumWorld.x = v.x;
  7192. if (v.y > this.maximumWorld.y)
  7193. this.maximumWorld.y = v.y;
  7194. if (v.z > this.maximumWorld.z)
  7195. this.maximumWorld.z = v.z;
  7196. }
  7197. // OBB
  7198. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7199. this.center.scaleInPlace(0.5);
  7200. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7201. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7202. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7203. this._worldMatrix = world;
  7204. };
  7205. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7206. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7207. };
  7208. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7209. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7210. };
  7211. BoundingBox.prototype.intersectsPoint = function (point) {
  7212. var delta = -BABYLON.Engine.Epsilon;
  7213. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7214. return false;
  7215. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7216. return false;
  7217. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7218. return false;
  7219. return true;
  7220. };
  7221. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7222. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7223. };
  7224. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7225. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7226. return false;
  7227. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7228. return false;
  7229. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7230. return false;
  7231. return true;
  7232. };
  7233. // Statics
  7234. BoundingBox.Intersects = function (box0, box1) {
  7235. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7236. return false;
  7237. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7238. return false;
  7239. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7240. return false;
  7241. return true;
  7242. };
  7243. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7244. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7245. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7246. return (num <= (sphereRadius * sphereRadius));
  7247. };
  7248. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7249. for (var p = 0; p < 6; p++) {
  7250. for (var i = 0; i < 8; i++) {
  7251. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7252. return false;
  7253. }
  7254. }
  7255. }
  7256. return true;
  7257. };
  7258. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7259. for (var p = 0; p < 6; p++) {
  7260. var inCount = 8;
  7261. for (var i = 0; i < 8; i++) {
  7262. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7263. --inCount;
  7264. }
  7265. else {
  7266. break;
  7267. }
  7268. }
  7269. if (inCount === 0)
  7270. return false;
  7271. }
  7272. return true;
  7273. };
  7274. return BoundingBox;
  7275. })();
  7276. BABYLON.BoundingBox = BoundingBox;
  7277. })(BABYLON || (BABYLON = {}));
  7278. //# sourceMappingURL=babylon.boundingBox.js.map
  7279. var BABYLON;
  7280. (function (BABYLON) {
  7281. var computeBoxExtents = function (axis, box) {
  7282. var p = BABYLON.Vector3.Dot(box.center, axis);
  7283. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7284. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7285. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7286. var r = r0 + r1 + r2;
  7287. return {
  7288. min: p - r,
  7289. max: p + r
  7290. };
  7291. };
  7292. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7293. var axisOverlap = function (axis, box0, box1) {
  7294. var result0 = computeBoxExtents(axis, box0);
  7295. var result1 = computeBoxExtents(axis, box1);
  7296. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7297. };
  7298. var BoundingInfo = (function () {
  7299. function BoundingInfo(minimum, maximum) {
  7300. this.minimum = minimum;
  7301. this.maximum = maximum;
  7302. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7303. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7304. }
  7305. // Methods
  7306. BoundingInfo.prototype._update = function (world) {
  7307. this.boundingBox._update(world);
  7308. this.boundingSphere._update(world);
  7309. };
  7310. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7311. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7312. return false;
  7313. return this.boundingBox.isInFrustum(frustumPlanes);
  7314. };
  7315. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7316. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7317. };
  7318. BoundingInfo.prototype._checkCollision = function (collider) {
  7319. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7320. };
  7321. BoundingInfo.prototype.intersectsPoint = function (point) {
  7322. if (!this.boundingSphere.centerWorld) {
  7323. return false;
  7324. }
  7325. if (!this.boundingSphere.intersectsPoint(point)) {
  7326. return false;
  7327. }
  7328. if (!this.boundingBox.intersectsPoint(point)) {
  7329. return false;
  7330. }
  7331. return true;
  7332. };
  7333. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7334. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7335. return false;
  7336. }
  7337. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7338. return false;
  7339. }
  7340. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7341. return false;
  7342. }
  7343. if (!precise) {
  7344. return true;
  7345. }
  7346. var box0 = this.boundingBox;
  7347. var box1 = boundingInfo.boundingBox;
  7348. if (!axisOverlap(box0.directions[0], box0, box1))
  7349. return false;
  7350. if (!axisOverlap(box0.directions[1], box0, box1))
  7351. return false;
  7352. if (!axisOverlap(box0.directions[2], box0, box1))
  7353. return false;
  7354. if (!axisOverlap(box1.directions[0], box0, box1))
  7355. return false;
  7356. if (!axisOverlap(box1.directions[1], box0, box1))
  7357. return false;
  7358. if (!axisOverlap(box1.directions[2], box0, box1))
  7359. return false;
  7360. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7361. return false;
  7362. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7363. return false;
  7364. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7365. return false;
  7366. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7367. return false;
  7368. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7369. return false;
  7370. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7371. return false;
  7372. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7373. return false;
  7374. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7375. return false;
  7376. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7377. return false;
  7378. return true;
  7379. };
  7380. return BoundingInfo;
  7381. })();
  7382. BABYLON.BoundingInfo = BoundingInfo;
  7383. })(BABYLON || (BABYLON = {}));
  7384. //# sourceMappingURL=babylon.boundingInfo.js.map
  7385. var __extends = this.__extends || function (d, b) {
  7386. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7387. function __() { this.constructor = d; }
  7388. __.prototype = b.prototype;
  7389. d.prototype = new __();
  7390. };
  7391. var BABYLON;
  7392. (function (BABYLON) {
  7393. var AbstractMesh = (function (_super) {
  7394. __extends(AbstractMesh, _super);
  7395. function AbstractMesh(name, scene) {
  7396. var _this = this;
  7397. _super.call(this, name, scene);
  7398. // Properties
  7399. this.definedFacingForward = true; // orientation for POV movement & rotation
  7400. this.position = new BABYLON.Vector3(0, 0, 0);
  7401. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7402. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7403. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7404. this.visibility = 1.0;
  7405. this.alphaIndex = Number.MAX_VALUE;
  7406. this.infiniteDistance = false;
  7407. this.isVisible = true;
  7408. this.isPickable = true;
  7409. this.showBoundingBox = false;
  7410. this.showSubMeshesBoundingBox = false;
  7411. this.onDispose = null;
  7412. this.checkCollisions = false;
  7413. this.isBlocker = false;
  7414. this.renderingGroupId = 0;
  7415. this.receiveShadows = false;
  7416. this.renderOutline = false;
  7417. this.outlineColor = BABYLON.Color3.Red();
  7418. this.outlineWidth = 0.02;
  7419. this.renderOverlay = false;
  7420. this.overlayColor = BABYLON.Color3.Red();
  7421. this.overlayAlpha = 0.5;
  7422. this.hasVertexAlpha = false;
  7423. this.useVertexColors = true;
  7424. this.applyFog = true;
  7425. this.useOctreeForRenderingSelection = true;
  7426. this.useOctreeForPicking = true;
  7427. this.useOctreeForCollisions = true;
  7428. this.layerMask = 0x0FFFFFFF;
  7429. this.alwaysSelectAsActiveMesh = false;
  7430. // Physics
  7431. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7432. // Collisions
  7433. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7434. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7435. this._collider = new BABYLON.Collider();
  7436. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7437. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7438. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7439. // Cache
  7440. this._localScaling = BABYLON.Matrix.Zero();
  7441. this._localRotation = BABYLON.Matrix.Zero();
  7442. this._localTranslation = BABYLON.Matrix.Zero();
  7443. this._localBillboard = BABYLON.Matrix.Zero();
  7444. this._localPivotScaling = BABYLON.Matrix.Zero();
  7445. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7446. this._localWorld = BABYLON.Matrix.Zero();
  7447. this._worldMatrix = BABYLON.Matrix.Zero();
  7448. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7449. this._absolutePosition = BABYLON.Vector3.Zero();
  7450. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7451. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7452. this._isDirty = false;
  7453. this._pivotMatrix = BABYLON.Matrix.Identity();
  7454. this._isDisposed = false;
  7455. this._renderId = 0;
  7456. this._intersectionsInProgress = new Array();
  7457. this._onAfterWorldMatrixUpdate = new Array();
  7458. this._isWorldMatrixFrozen = false;
  7459. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7460. if (collidedMesh === void 0) { collidedMesh = null; }
  7461. //TODO move this to the collision coordinator!
  7462. if (collisionId != null || collisionId != undefined)
  7463. newPosition.multiplyInPlace(_this._collider.radius);
  7464. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7465. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7466. _this.position.addInPlace(_this._diffPositionForCollisions);
  7467. }
  7468. };
  7469. scene.addMesh(this);
  7470. }
  7471. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7472. get: function () {
  7473. return AbstractMesh._BILLBOARDMODE_NONE;
  7474. },
  7475. enumerable: true,
  7476. configurable: true
  7477. });
  7478. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7479. get: function () {
  7480. return AbstractMesh._BILLBOARDMODE_X;
  7481. },
  7482. enumerable: true,
  7483. configurable: true
  7484. });
  7485. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7486. get: function () {
  7487. return AbstractMesh._BILLBOARDMODE_Y;
  7488. },
  7489. enumerable: true,
  7490. configurable: true
  7491. });
  7492. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7493. get: function () {
  7494. return AbstractMesh._BILLBOARDMODE_Z;
  7495. },
  7496. enumerable: true,
  7497. configurable: true
  7498. });
  7499. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7500. get: function () {
  7501. return AbstractMesh._BILLBOARDMODE_ALL;
  7502. },
  7503. enumerable: true,
  7504. configurable: true
  7505. });
  7506. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7507. // Methods
  7508. get: function () {
  7509. return false;
  7510. },
  7511. enumerable: true,
  7512. configurable: true
  7513. });
  7514. AbstractMesh.prototype.getLOD = function (camera) {
  7515. return this;
  7516. };
  7517. AbstractMesh.prototype.getTotalVertices = function () {
  7518. return 0;
  7519. };
  7520. AbstractMesh.prototype.getIndices = function () {
  7521. return null;
  7522. };
  7523. AbstractMesh.prototype.getVerticesData = function (kind) {
  7524. return null;
  7525. };
  7526. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7527. return false;
  7528. };
  7529. AbstractMesh.prototype.getBoundingInfo = function () {
  7530. if (this._masterMesh) {
  7531. return this._masterMesh.getBoundingInfo();
  7532. }
  7533. if (!this._boundingInfo) {
  7534. this._updateBoundingInfo();
  7535. }
  7536. return this._boundingInfo;
  7537. };
  7538. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7539. get: function () {
  7540. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7541. },
  7542. enumerable: true,
  7543. configurable: true
  7544. });
  7545. AbstractMesh.prototype._preActivate = function () {
  7546. };
  7547. AbstractMesh.prototype._activate = function (renderId) {
  7548. this._renderId = renderId;
  7549. };
  7550. AbstractMesh.prototype.getWorldMatrix = function () {
  7551. if (this._masterMesh) {
  7552. return this._masterMesh.getWorldMatrix();
  7553. }
  7554. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7555. this.computeWorldMatrix();
  7556. }
  7557. return this._worldMatrix;
  7558. };
  7559. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7560. get: function () {
  7561. return this._worldMatrix;
  7562. },
  7563. enumerable: true,
  7564. configurable: true
  7565. });
  7566. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7567. get: function () {
  7568. return this._absolutePosition;
  7569. },
  7570. enumerable: true,
  7571. configurable: true
  7572. });
  7573. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7574. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7575. this.computeWorldMatrix(true);
  7576. this._isWorldMatrixFrozen = true;
  7577. };
  7578. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7579. this._isWorldMatrixFrozen = false;
  7580. this.computeWorldMatrix(true);
  7581. };
  7582. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7583. get: function () {
  7584. return this._isWorldMatrixFrozen;
  7585. },
  7586. enumerable: true,
  7587. configurable: true
  7588. });
  7589. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7590. if (!this.rotationQuaternion) {
  7591. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7592. this.rotation = BABYLON.Vector3.Zero();
  7593. }
  7594. if (!space || space === 0 /* LOCAL */) {
  7595. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7596. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7597. }
  7598. else {
  7599. if (this.parent) {
  7600. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7601. invertParentWorldMatrix.invert();
  7602. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7603. }
  7604. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7605. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7606. }
  7607. };
  7608. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7609. var displacementVector = axis.scale(distance);
  7610. if (!space || space === 0 /* LOCAL */) {
  7611. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7612. this.setPositionWithLocalVector(tempV3);
  7613. }
  7614. else {
  7615. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7616. }
  7617. };
  7618. AbstractMesh.prototype.getAbsolutePosition = function () {
  7619. this.computeWorldMatrix();
  7620. return this._absolutePosition;
  7621. };
  7622. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7623. if (!absolutePosition) {
  7624. return;
  7625. }
  7626. var absolutePositionX;
  7627. var absolutePositionY;
  7628. var absolutePositionZ;
  7629. if (absolutePosition.x === undefined) {
  7630. if (arguments.length < 3) {
  7631. return;
  7632. }
  7633. absolutePositionX = arguments[0];
  7634. absolutePositionY = arguments[1];
  7635. absolutePositionZ = arguments[2];
  7636. }
  7637. else {
  7638. absolutePositionX = absolutePosition.x;
  7639. absolutePositionY = absolutePosition.y;
  7640. absolutePositionZ = absolutePosition.z;
  7641. }
  7642. if (this.parent) {
  7643. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7644. invertParentWorldMatrix.invert();
  7645. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7646. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7647. }
  7648. else {
  7649. this.position.x = absolutePositionX;
  7650. this.position.y = absolutePositionY;
  7651. this.position.z = absolutePositionZ;
  7652. }
  7653. };
  7654. // ================================== Point of View Movement =================================
  7655. /**
  7656. * Perform relative position change from the point of view of behind the front of the mesh.
  7657. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7658. * Supports definition of mesh facing forward or backward.
  7659. * @param {number} amountRight
  7660. * @param {number} amountUp
  7661. * @param {number} amountForward
  7662. */
  7663. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7664. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7665. };
  7666. /**
  7667. * Calculate relative position change from the point of view of behind the front of the mesh.
  7668. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7669. * Supports definition of mesh facing forward or backward.
  7670. * @param {number} amountRight
  7671. * @param {number} amountUp
  7672. * @param {number} amountForward
  7673. */
  7674. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7675. var rotMatrix = new BABYLON.Matrix();
  7676. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7677. rotQuaternion.toRotationMatrix(rotMatrix);
  7678. var translationDelta = BABYLON.Vector3.Zero();
  7679. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7680. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7681. return translationDelta;
  7682. };
  7683. // ================================== Point of View Rotation =================================
  7684. /**
  7685. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7686. * Supports definition of mesh facing forward or backward.
  7687. * @param {number} flipBack
  7688. * @param {number} twirlClockwise
  7689. * @param {number} tiltRight
  7690. */
  7691. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7692. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7693. };
  7694. /**
  7695. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7696. * Supports definition of mesh facing forward or backward.
  7697. * @param {number} flipBack
  7698. * @param {number} twirlClockwise
  7699. * @param {number} tiltRight
  7700. */
  7701. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7702. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7703. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7704. };
  7705. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7706. this._pivotMatrix = matrix;
  7707. this._cache.pivotMatrixUpdated = true;
  7708. };
  7709. AbstractMesh.prototype.getPivotMatrix = function () {
  7710. return this._pivotMatrix;
  7711. };
  7712. AbstractMesh.prototype._isSynchronized = function () {
  7713. if (this._isDirty) {
  7714. return false;
  7715. }
  7716. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7717. return false;
  7718. if (this._cache.pivotMatrixUpdated) {
  7719. return false;
  7720. }
  7721. if (this.infiniteDistance) {
  7722. return false;
  7723. }
  7724. if (!this._cache.position.equals(this.position))
  7725. return false;
  7726. if (this.rotationQuaternion) {
  7727. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7728. return false;
  7729. }
  7730. else {
  7731. if (!this._cache.rotation.equals(this.rotation))
  7732. return false;
  7733. }
  7734. if (!this._cache.scaling.equals(this.scaling))
  7735. return false;
  7736. return true;
  7737. };
  7738. AbstractMesh.prototype._initCache = function () {
  7739. _super.prototype._initCache.call(this);
  7740. this._cache.localMatrixUpdated = false;
  7741. this._cache.position = BABYLON.Vector3.Zero();
  7742. this._cache.scaling = BABYLON.Vector3.Zero();
  7743. this._cache.rotation = BABYLON.Vector3.Zero();
  7744. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7745. };
  7746. AbstractMesh.prototype.markAsDirty = function (property) {
  7747. if (property === "rotation") {
  7748. this.rotationQuaternion = null;
  7749. }
  7750. this._currentRenderId = Number.MAX_VALUE;
  7751. this._isDirty = true;
  7752. };
  7753. AbstractMesh.prototype._updateBoundingInfo = function () {
  7754. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7755. this._boundingInfo._update(this.worldMatrixFromCache);
  7756. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7757. };
  7758. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7759. if (!this.subMeshes) {
  7760. return;
  7761. }
  7762. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7763. var subMesh = this.subMeshes[subIndex];
  7764. subMesh.updateBoundingInfo(matrix);
  7765. }
  7766. };
  7767. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7768. if (this._isWorldMatrixFrozen) {
  7769. return this._worldMatrix;
  7770. }
  7771. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7772. return this._worldMatrix;
  7773. }
  7774. this._cache.position.copyFrom(this.position);
  7775. this._cache.scaling.copyFrom(this.scaling);
  7776. this._cache.pivotMatrixUpdated = false;
  7777. this._currentRenderId = this.getScene().getRenderId();
  7778. this._isDirty = false;
  7779. // Scaling
  7780. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7781. // Rotation
  7782. if (this.rotationQuaternion) {
  7783. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7784. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7785. }
  7786. else {
  7787. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7788. this._cache.rotation.copyFrom(this.rotation);
  7789. }
  7790. // Translation
  7791. if (this.infiniteDistance && !this.parent) {
  7792. var camera = this.getScene().activeCamera;
  7793. var cameraWorldMatrix = camera.getWorldMatrix();
  7794. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7795. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7796. }
  7797. else {
  7798. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7799. }
  7800. // Composing transformations
  7801. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7802. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7803. // Billboarding
  7804. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7805. var localPosition = this.position.clone();
  7806. var zero = this.getScene().activeCamera.globalPosition.clone();
  7807. if (this.parent && this.parent.position) {
  7808. localPosition.addInPlace(this.parent.position);
  7809. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7810. }
  7811. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  7812. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7813. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7814. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7815. zero.y = localPosition.y + 0.001;
  7816. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7817. zero.z = localPosition.z + 0.001;
  7818. }
  7819. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7820. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7821. this._localBillboard.invert();
  7822. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7823. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7824. }
  7825. // Local world
  7826. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7827. // Parent
  7828. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7829. this._markSyncedWithParent();
  7830. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7831. }
  7832. else {
  7833. this._worldMatrix.copyFrom(this._localWorld);
  7834. }
  7835. // Bounding info
  7836. this._updateBoundingInfo();
  7837. // Absolute position
  7838. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7839. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7840. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7841. }
  7842. return this._worldMatrix;
  7843. };
  7844. /**
  7845. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7846. * @param func: callback function to add
  7847. */
  7848. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7849. this._onAfterWorldMatrixUpdate.push(func);
  7850. };
  7851. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7852. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  7853. if (index > -1) {
  7854. this._onAfterWorldMatrixUpdate.splice(index, 1);
  7855. }
  7856. };
  7857. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7858. this.computeWorldMatrix();
  7859. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7860. };
  7861. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7862. this.computeWorldMatrix();
  7863. var invLocalWorldMatrix = this._localWorld.clone();
  7864. invLocalWorldMatrix.invert();
  7865. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7866. };
  7867. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7868. this.computeWorldMatrix();
  7869. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7870. };
  7871. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7872. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  7873. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  7874. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  7875. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  7876. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  7877. /// <returns>Mesh oriented towards targetMesh</returns>
  7878. yawCor = yawCor || 0; // default to zero if undefined
  7879. pitchCor = pitchCor || 0;
  7880. rollCor = rollCor || 0;
  7881. var dv = targetPoint.subtract(this.position);
  7882. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7883. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7884. var pitch = Math.atan2(dv.y, len);
  7885. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7886. };
  7887. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7888. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7889. return false;
  7890. }
  7891. return true;
  7892. };
  7893. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  7894. if (!camera) {
  7895. camera = this.getScene().activeCamera;
  7896. }
  7897. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  7898. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  7899. return false;
  7900. }
  7901. return true;
  7902. };
  7903. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7904. if (!this._boundingInfo || !mesh._boundingInfo) {
  7905. return false;
  7906. }
  7907. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7908. };
  7909. AbstractMesh.prototype.intersectsPoint = function (point) {
  7910. if (!this._boundingInfo) {
  7911. return false;
  7912. }
  7913. return this._boundingInfo.intersectsPoint(point);
  7914. };
  7915. // Physics
  7916. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7917. var physicsEngine = this.getScene().getPhysicsEngine();
  7918. if (!physicsEngine) {
  7919. return;
  7920. }
  7921. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7922. if (impostor.impostor) {
  7923. // Old API
  7924. options = impostor;
  7925. impostor = impostor.impostor;
  7926. }
  7927. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7928. physicsEngine._unregisterMesh(this);
  7929. return;
  7930. }
  7931. if (!options) {
  7932. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  7933. }
  7934. else {
  7935. if (!options.mass && options.mass !== 0)
  7936. options.mass = 0;
  7937. if (!options.friction && options.friction !== 0)
  7938. options.friction = 0.2;
  7939. if (!options.restitution && options.restitution !== 0)
  7940. options.restitution = 0.2;
  7941. }
  7942. this._physicImpostor = impostor;
  7943. this._physicsMass = options.mass;
  7944. this._physicsFriction = options.friction;
  7945. this._physicRestitution = options.restitution;
  7946. return physicsEngine._registerMesh(this, impostor, options);
  7947. };
  7948. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7949. if (!this._physicImpostor) {
  7950. return BABYLON.PhysicsEngine.NoImpostor;
  7951. }
  7952. return this._physicImpostor;
  7953. };
  7954. AbstractMesh.prototype.getPhysicsMass = function () {
  7955. if (!this._physicsMass) {
  7956. return 0;
  7957. }
  7958. return this._physicsMass;
  7959. };
  7960. AbstractMesh.prototype.getPhysicsFriction = function () {
  7961. if (!this._physicsFriction) {
  7962. return 0;
  7963. }
  7964. return this._physicsFriction;
  7965. };
  7966. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7967. if (!this._physicRestitution) {
  7968. return 0;
  7969. }
  7970. return this._physicRestitution;
  7971. };
  7972. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  7973. if (!camera) {
  7974. camera = this.getScene().activeCamera;
  7975. }
  7976. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  7977. };
  7978. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  7979. if (!camera) {
  7980. camera = this.getScene().activeCamera;
  7981. }
  7982. return this.absolutePosition.subtract(camera.position).length();
  7983. };
  7984. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7985. if (!this._physicImpostor) {
  7986. return;
  7987. }
  7988. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7989. };
  7990. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  7991. if (!this._physicImpostor) {
  7992. return;
  7993. }
  7994. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  7995. };
  7996. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  7997. if (!this._physicImpostor) {
  7998. return;
  7999. }
  8000. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8001. };
  8002. // Collisions
  8003. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8004. var globalPosition = this.getAbsolutePosition();
  8005. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8006. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8007. this._collider.radius = this.ellipsoid;
  8008. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8009. };
  8010. // Submeshes octree
  8011. /**
  8012. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8013. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8014. */
  8015. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8016. if (maxCapacity === void 0) { maxCapacity = 64; }
  8017. if (maxDepth === void 0) { maxDepth = 2; }
  8018. if (!this._submeshesOctree) {
  8019. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8020. }
  8021. this.computeWorldMatrix(true);
  8022. // Update octree
  8023. var bbox = this.getBoundingInfo().boundingBox;
  8024. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8025. return this._submeshesOctree;
  8026. };
  8027. // Collisions
  8028. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8029. this._generatePointsArray();
  8030. // Transformation
  8031. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8032. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8033. subMesh._lastColliderWorldVertices = [];
  8034. subMesh._trianglePlanes = [];
  8035. var start = subMesh.verticesStart;
  8036. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8037. for (var i = start; i < end; i++) {
  8038. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8039. }
  8040. }
  8041. // Collide
  8042. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8043. if (collider.collisionFound) {
  8044. collider.collidedMesh = this;
  8045. }
  8046. };
  8047. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8048. var subMeshes;
  8049. var len;
  8050. // Octrees
  8051. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8052. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8053. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8054. len = intersections.length;
  8055. subMeshes = intersections.data;
  8056. }
  8057. else {
  8058. subMeshes = this.subMeshes;
  8059. len = subMeshes.length;
  8060. }
  8061. for (var index = 0; index < len; index++) {
  8062. var subMesh = subMeshes[index];
  8063. // Bounding test
  8064. if (len > 1 && !subMesh._checkCollision(collider))
  8065. continue;
  8066. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8067. }
  8068. };
  8069. AbstractMesh.prototype._checkCollision = function (collider) {
  8070. // Bounding box test
  8071. if (!this._boundingInfo._checkCollision(collider))
  8072. return;
  8073. // Transformation matrix
  8074. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8075. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8076. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8077. };
  8078. // Picking
  8079. AbstractMesh.prototype._generatePointsArray = function () {
  8080. return false;
  8081. };
  8082. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8083. var pickingInfo = new BABYLON.PickingInfo();
  8084. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8085. return pickingInfo;
  8086. }
  8087. if (!this._generatePointsArray()) {
  8088. return pickingInfo;
  8089. }
  8090. var intersectInfo = null;
  8091. // Octrees
  8092. var subMeshes;
  8093. var len;
  8094. if (this._submeshesOctree && this.useOctreeForPicking) {
  8095. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8096. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8097. len = intersections.length;
  8098. subMeshes = intersections.data;
  8099. }
  8100. else {
  8101. subMeshes = this.subMeshes;
  8102. len = subMeshes.length;
  8103. }
  8104. for (var index = 0; index < len; index++) {
  8105. var subMesh = subMeshes[index];
  8106. // Bounding test
  8107. if (len > 1 && !subMesh.canIntersects(ray))
  8108. continue;
  8109. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8110. if (currentIntersectInfo) {
  8111. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8112. intersectInfo = currentIntersectInfo;
  8113. intersectInfo.subMeshId = index;
  8114. if (fastCheck) {
  8115. break;
  8116. }
  8117. }
  8118. }
  8119. }
  8120. if (intersectInfo) {
  8121. // Get picked point
  8122. var world = this.getWorldMatrix();
  8123. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8124. var direction = ray.direction.clone();
  8125. direction = direction.scale(intersectInfo.distance);
  8126. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8127. var pickedPoint = worldOrigin.add(worldDirection);
  8128. // Return result
  8129. pickingInfo.hit = true;
  8130. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8131. pickingInfo.pickedPoint = pickedPoint;
  8132. pickingInfo.pickedMesh = this;
  8133. pickingInfo.bu = intersectInfo.bu;
  8134. pickingInfo.bv = intersectInfo.bv;
  8135. pickingInfo.faceId = intersectInfo.faceId;
  8136. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8137. return pickingInfo;
  8138. }
  8139. return pickingInfo;
  8140. };
  8141. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8142. return null;
  8143. };
  8144. AbstractMesh.prototype.releaseSubMeshes = function () {
  8145. if (this.subMeshes) {
  8146. while (this.subMeshes.length) {
  8147. this.subMeshes[0].dispose();
  8148. }
  8149. }
  8150. else {
  8151. this.subMeshes = new Array();
  8152. }
  8153. };
  8154. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8155. var index;
  8156. // Physics
  8157. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8158. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8159. }
  8160. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8161. var other = this._intersectionsInProgress[index];
  8162. var pos = other._intersectionsInProgress.indexOf(this);
  8163. other._intersectionsInProgress.splice(pos, 1);
  8164. }
  8165. this._intersectionsInProgress = [];
  8166. // SubMeshes
  8167. this.releaseSubMeshes();
  8168. // Remove from scene
  8169. this.getScene().removeMesh(this);
  8170. if (!doNotRecurse) {
  8171. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8172. if (this.getScene().particleSystems[index].emitter === this) {
  8173. this.getScene().particleSystems[index].dispose();
  8174. index--;
  8175. }
  8176. }
  8177. // Children
  8178. var objects = this.getScene().meshes.slice(0);
  8179. for (index = 0; index < objects.length; index++) {
  8180. if (objects[index].parent === this) {
  8181. objects[index].dispose();
  8182. }
  8183. }
  8184. }
  8185. else {
  8186. for (index = 0; index < this.getScene().meshes.length; index++) {
  8187. var obj = this.getScene().meshes[index];
  8188. if (obj.parent === this) {
  8189. obj.parent = null;
  8190. obj.computeWorldMatrix(true);
  8191. }
  8192. }
  8193. }
  8194. this._onAfterWorldMatrixUpdate = [];
  8195. this._isDisposed = true;
  8196. // Callback
  8197. if (this.onDispose) {
  8198. this.onDispose();
  8199. }
  8200. };
  8201. // Statics
  8202. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8203. AbstractMesh._BILLBOARDMODE_X = 1;
  8204. AbstractMesh._BILLBOARDMODE_Y = 2;
  8205. AbstractMesh._BILLBOARDMODE_Z = 4;
  8206. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8207. return AbstractMesh;
  8208. })(BABYLON.Node);
  8209. BABYLON.AbstractMesh = AbstractMesh;
  8210. })(BABYLON || (BABYLON = {}));
  8211. //# sourceMappingURL=babylon.abstractMesh.js.map
  8212. var __extends = this.__extends || function (d, b) {
  8213. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8214. function __() { this.constructor = d; }
  8215. __.prototype = b.prototype;
  8216. d.prototype = new __();
  8217. };
  8218. var BABYLON;
  8219. (function (BABYLON) {
  8220. var Light = (function (_super) {
  8221. __extends(Light, _super);
  8222. function Light(name, scene) {
  8223. _super.call(this, name, scene);
  8224. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8225. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8226. this.intensity = 1.0;
  8227. this.range = Number.MAX_VALUE;
  8228. this.includeOnlyWithLayerMask = 0;
  8229. this.includedOnlyMeshes = new Array();
  8230. this.excludedMeshes = new Array();
  8231. this.excludeWithLayerMask = 0;
  8232. this._excludedMeshesIds = new Array();
  8233. this._includedOnlyMeshesIds = new Array();
  8234. scene.addLight(this);
  8235. }
  8236. Light.prototype.getShadowGenerator = function () {
  8237. return this._shadowGenerator;
  8238. };
  8239. Light.prototype.getAbsolutePosition = function () {
  8240. return BABYLON.Vector3.Zero();
  8241. };
  8242. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8243. };
  8244. Light.prototype._getWorldMatrix = function () {
  8245. return BABYLON.Matrix.Identity();
  8246. };
  8247. Light.prototype.canAffectMesh = function (mesh) {
  8248. if (!mesh) {
  8249. return true;
  8250. }
  8251. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8252. return false;
  8253. }
  8254. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8255. return false;
  8256. }
  8257. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8258. return false;
  8259. }
  8260. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8261. return false;
  8262. }
  8263. return true;
  8264. };
  8265. Light.prototype.getWorldMatrix = function () {
  8266. this._currentRenderId = this.getScene().getRenderId();
  8267. var worldMatrix = this._getWorldMatrix();
  8268. if (this.parent && this.parent.getWorldMatrix) {
  8269. if (!this._parentedWorldMatrix) {
  8270. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8271. }
  8272. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8273. this._markSyncedWithParent();
  8274. return this._parentedWorldMatrix;
  8275. }
  8276. return worldMatrix;
  8277. };
  8278. Light.prototype.dispose = function () {
  8279. if (this._shadowGenerator) {
  8280. this._shadowGenerator.dispose();
  8281. this._shadowGenerator = null;
  8282. }
  8283. // Remove from scene
  8284. this.getScene().removeLight(this);
  8285. };
  8286. return Light;
  8287. })(BABYLON.Node);
  8288. BABYLON.Light = Light;
  8289. })(BABYLON || (BABYLON = {}));
  8290. //# sourceMappingURL=babylon.light.js.map
  8291. var __extends = this.__extends || function (d, b) {
  8292. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8293. function __() { this.constructor = d; }
  8294. __.prototype = b.prototype;
  8295. d.prototype = new __();
  8296. };
  8297. var BABYLON;
  8298. (function (BABYLON) {
  8299. var PointLight = (function (_super) {
  8300. __extends(PointLight, _super);
  8301. function PointLight(name, position, scene) {
  8302. _super.call(this, name, scene);
  8303. this.position = position;
  8304. }
  8305. PointLight.prototype.getAbsolutePosition = function () {
  8306. return this._transformedPosition ? this._transformedPosition : this.position;
  8307. };
  8308. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8309. if (this.parent && this.parent.getWorldMatrix) {
  8310. if (!this._transformedPosition) {
  8311. this._transformedPosition = BABYLON.Vector3.Zero();
  8312. }
  8313. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8314. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8315. return;
  8316. }
  8317. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8318. };
  8319. PointLight.prototype.getShadowGenerator = function () {
  8320. return null;
  8321. };
  8322. PointLight.prototype._getWorldMatrix = function () {
  8323. if (!this._worldMatrix) {
  8324. this._worldMatrix = BABYLON.Matrix.Identity();
  8325. }
  8326. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8327. return this._worldMatrix;
  8328. };
  8329. return PointLight;
  8330. })(BABYLON.Light);
  8331. BABYLON.PointLight = PointLight;
  8332. })(BABYLON || (BABYLON = {}));
  8333. //# sourceMappingURL=babylon.pointLight.js.map
  8334. var __extends = this.__extends || function (d, b) {
  8335. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8336. function __() { this.constructor = d; }
  8337. __.prototype = b.prototype;
  8338. d.prototype = new __();
  8339. };
  8340. var BABYLON;
  8341. (function (BABYLON) {
  8342. var SpotLight = (function (_super) {
  8343. __extends(SpotLight, _super);
  8344. function SpotLight(name, position, direction, angle, exponent, scene) {
  8345. _super.call(this, name, scene);
  8346. this.position = position;
  8347. this.direction = direction;
  8348. this.angle = angle;
  8349. this.exponent = exponent;
  8350. }
  8351. SpotLight.prototype.getAbsolutePosition = function () {
  8352. return this.transformedPosition ? this.transformedPosition : this.position;
  8353. };
  8354. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8355. var activeCamera = this.getScene().activeCamera;
  8356. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8357. };
  8358. SpotLight.prototype.supportsVSM = function () {
  8359. return true;
  8360. };
  8361. SpotLight.prototype.needRefreshPerFrame = function () {
  8362. return false;
  8363. };
  8364. SpotLight.prototype.setDirectionToTarget = function (target) {
  8365. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8366. return this.direction;
  8367. };
  8368. SpotLight.prototype.computeTransformedPosition = function () {
  8369. if (this.parent && this.parent.getWorldMatrix) {
  8370. if (!this.transformedPosition) {
  8371. this.transformedPosition = BABYLON.Vector3.Zero();
  8372. }
  8373. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8374. return true;
  8375. }
  8376. return false;
  8377. };
  8378. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8379. var normalizeDirection;
  8380. if (this.parent && this.parent.getWorldMatrix) {
  8381. if (!this._transformedDirection) {
  8382. this._transformedDirection = BABYLON.Vector3.Zero();
  8383. }
  8384. this.computeTransformedPosition();
  8385. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8386. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8387. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8388. }
  8389. else {
  8390. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8391. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8392. }
  8393. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8394. };
  8395. SpotLight.prototype._getWorldMatrix = function () {
  8396. if (!this._worldMatrix) {
  8397. this._worldMatrix = BABYLON.Matrix.Identity();
  8398. }
  8399. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8400. return this._worldMatrix;
  8401. };
  8402. return SpotLight;
  8403. })(BABYLON.Light);
  8404. BABYLON.SpotLight = SpotLight;
  8405. })(BABYLON || (BABYLON = {}));
  8406. //# sourceMappingURL=babylon.spotLight.js.map
  8407. var __extends = this.__extends || function (d, b) {
  8408. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8409. function __() { this.constructor = d; }
  8410. __.prototype = b.prototype;
  8411. d.prototype = new __();
  8412. };
  8413. var BABYLON;
  8414. (function (BABYLON) {
  8415. var HemisphericLight = (function (_super) {
  8416. __extends(HemisphericLight, _super);
  8417. function HemisphericLight(name, direction, scene) {
  8418. _super.call(this, name, scene);
  8419. this.direction = direction;
  8420. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8421. }
  8422. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8423. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8424. return this.direction;
  8425. };
  8426. HemisphericLight.prototype.getShadowGenerator = function () {
  8427. return null;
  8428. };
  8429. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8430. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8431. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8432. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8433. };
  8434. HemisphericLight.prototype._getWorldMatrix = function () {
  8435. if (!this._worldMatrix) {
  8436. this._worldMatrix = BABYLON.Matrix.Identity();
  8437. }
  8438. return this._worldMatrix;
  8439. };
  8440. return HemisphericLight;
  8441. })(BABYLON.Light);
  8442. BABYLON.HemisphericLight = HemisphericLight;
  8443. })(BABYLON || (BABYLON = {}));
  8444. //# sourceMappingURL=babylon.hemisphericLight.js.map
  8445. var __extends = this.__extends || function (d, b) {
  8446. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8447. function __() { this.constructor = d; }
  8448. __.prototype = b.prototype;
  8449. d.prototype = new __();
  8450. };
  8451. var BABYLON;
  8452. (function (BABYLON) {
  8453. var DirectionalLight = (function (_super) {
  8454. __extends(DirectionalLight, _super);
  8455. function DirectionalLight(name, direction, scene) {
  8456. _super.call(this, name, scene);
  8457. this.direction = direction;
  8458. this.shadowOrthoScale = 0.5;
  8459. this.position = direction.scale(-1);
  8460. }
  8461. DirectionalLight.prototype.getAbsolutePosition = function () {
  8462. return this.transformedPosition ? this.transformedPosition : this.position;
  8463. };
  8464. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8465. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8466. return this.direction;
  8467. };
  8468. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8469. var orthoLeft = Number.MAX_VALUE;
  8470. var orthoRight = Number.MIN_VALUE;
  8471. var orthoTop = Number.MIN_VALUE;
  8472. var orthoBottom = Number.MAX_VALUE;
  8473. var tempVector3 = BABYLON.Vector3.Zero();
  8474. var activeCamera = this.getScene().activeCamera;
  8475. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8476. var mesh = renderList[meshIndex];
  8477. if (!mesh) {
  8478. continue;
  8479. }
  8480. var boundingInfo = mesh.getBoundingInfo();
  8481. if (!boundingInfo) {
  8482. continue;
  8483. }
  8484. var boundingBox = boundingInfo.boundingBox;
  8485. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8486. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8487. if (tempVector3.x < orthoLeft)
  8488. orthoLeft = tempVector3.x;
  8489. if (tempVector3.y < orthoBottom)
  8490. orthoBottom = tempVector3.y;
  8491. if (tempVector3.x > orthoRight)
  8492. orthoRight = tempVector3.x;
  8493. if (tempVector3.y > orthoTop)
  8494. orthoTop = tempVector3.y;
  8495. }
  8496. }
  8497. var xOffset = orthoRight - orthoLeft;
  8498. var yOffset = orthoTop - orthoBottom;
  8499. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8500. };
  8501. DirectionalLight.prototype.supportsVSM = function () {
  8502. return true;
  8503. };
  8504. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8505. return true;
  8506. };
  8507. DirectionalLight.prototype.computeTransformedPosition = function () {
  8508. if (this.parent && this.parent.getWorldMatrix) {
  8509. if (!this.transformedPosition) {
  8510. this.transformedPosition = BABYLON.Vector3.Zero();
  8511. }
  8512. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8513. return true;
  8514. }
  8515. return false;
  8516. };
  8517. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8518. if (this.parent && this.parent.getWorldMatrix) {
  8519. if (!this._transformedDirection) {
  8520. this._transformedDirection = BABYLON.Vector3.Zero();
  8521. }
  8522. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8523. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8524. return;
  8525. }
  8526. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8527. };
  8528. DirectionalLight.prototype._getWorldMatrix = function () {
  8529. if (!this._worldMatrix) {
  8530. this._worldMatrix = BABYLON.Matrix.Identity();
  8531. }
  8532. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8533. return this._worldMatrix;
  8534. };
  8535. return DirectionalLight;
  8536. })(BABYLON.Light);
  8537. BABYLON.DirectionalLight = DirectionalLight;
  8538. })(BABYLON || (BABYLON = {}));
  8539. //# sourceMappingURL=babylon.directionalLight.js.map
  8540. var BABYLON;
  8541. (function (BABYLON) {
  8542. var ShadowGenerator = (function () {
  8543. function ShadowGenerator(mapSize, light) {
  8544. var _this = this;
  8545. // Members
  8546. this._filter = ShadowGenerator.FILTER_NONE;
  8547. this.blurScale = 2;
  8548. this._blurBoxOffset = 0;
  8549. this._bias = 0.00005;
  8550. this._darkness = 0;
  8551. this._transparencyShadow = false;
  8552. this._viewMatrix = BABYLON.Matrix.Zero();
  8553. this._projectionMatrix = BABYLON.Matrix.Zero();
  8554. this._transformMatrix = BABYLON.Matrix.Zero();
  8555. this._worldViewProjection = BABYLON.Matrix.Zero();
  8556. this._light = light;
  8557. this._scene = light.getScene();
  8558. this._mapSize = mapSize;
  8559. light._shadowGenerator = this;
  8560. // Render target
  8561. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8562. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8563. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8564. this._shadowMap.anisotropicFilteringLevel = 1;
  8565. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8566. this._shadowMap.renderParticles = false;
  8567. this._shadowMap.onAfterUnbind = function () {
  8568. if (!_this.useBlurVarianceShadowMap) {
  8569. return;
  8570. }
  8571. if (!_this._shadowMap2) {
  8572. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8573. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8574. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8575. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8576. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8577. _this._downSamplePostprocess.onApply = function (effect) {
  8578. effect.setTexture("textureSampler", _this._shadowMap);
  8579. };
  8580. _this.blurBoxOffset = 1;
  8581. }
  8582. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8583. };
  8584. // Custom render function
  8585. var renderSubMesh = function (subMesh) {
  8586. var mesh = subMesh.getRenderingMesh();
  8587. var scene = _this._scene;
  8588. var engine = scene.getEngine();
  8589. // Culling
  8590. engine.setState(subMesh.getMaterial().backFaceCulling);
  8591. // Managing instances
  8592. var batch = mesh._getInstancesRenderList(subMesh._id);
  8593. if (batch.mustReturn) {
  8594. return;
  8595. }
  8596. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8597. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8598. engine.enableEffect(_this._effect);
  8599. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8600. var material = subMesh.getMaterial();
  8601. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8602. // Alpha test
  8603. if (material && material.needAlphaTesting()) {
  8604. var alphaTexture = material.getAlphaTestTexture();
  8605. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8606. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8607. }
  8608. // Bones
  8609. if (mesh.useBones) {
  8610. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8611. }
  8612. // Draw
  8613. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8614. }
  8615. else {
  8616. // Need to reset refresh rate of the shadowMap
  8617. _this._shadowMap.resetRefreshCounter();
  8618. }
  8619. };
  8620. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8621. var index;
  8622. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8623. renderSubMesh(opaqueSubMeshes.data[index]);
  8624. }
  8625. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8626. renderSubMesh(alphaTestSubMeshes.data[index]);
  8627. }
  8628. if (_this._transparencyShadow) {
  8629. for (index = 0; index < transparentSubMeshes.length; index++) {
  8630. renderSubMesh(transparentSubMeshes.data[index]);
  8631. }
  8632. }
  8633. };
  8634. this._shadowMap.onClear = function (engine) {
  8635. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8636. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8637. }
  8638. else {
  8639. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8640. }
  8641. };
  8642. }
  8643. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8644. // Static
  8645. get: function () {
  8646. return ShadowGenerator._FILTER_NONE;
  8647. },
  8648. enumerable: true,
  8649. configurable: true
  8650. });
  8651. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8652. get: function () {
  8653. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8654. },
  8655. enumerable: true,
  8656. configurable: true
  8657. });
  8658. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8659. get: function () {
  8660. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8661. },
  8662. enumerable: true,
  8663. configurable: true
  8664. });
  8665. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8666. get: function () {
  8667. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8668. },
  8669. enumerable: true,
  8670. configurable: true
  8671. });
  8672. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8673. get: function () {
  8674. return this._bias;
  8675. },
  8676. set: function (bias) {
  8677. this._bias = bias;
  8678. },
  8679. enumerable: true,
  8680. configurable: true
  8681. });
  8682. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8683. get: function () {
  8684. return this._blurBoxOffset;
  8685. },
  8686. set: function (value) {
  8687. var _this = this;
  8688. if (this._blurBoxOffset === value) {
  8689. return;
  8690. }
  8691. this._blurBoxOffset = value;
  8692. if (this._boxBlurPostprocess) {
  8693. this._boxBlurPostprocess.dispose();
  8694. }
  8695. 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);
  8696. this._boxBlurPostprocess.onApply = function (effect) {
  8697. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8698. };
  8699. },
  8700. enumerable: true,
  8701. configurable: true
  8702. });
  8703. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8704. get: function () {
  8705. return this._filter;
  8706. },
  8707. set: function (value) {
  8708. if (this._filter === value) {
  8709. return;
  8710. }
  8711. this._filter = value;
  8712. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8713. this._shadowMap.anisotropicFilteringLevel = 16;
  8714. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8715. }
  8716. else {
  8717. this._shadowMap.anisotropicFilteringLevel = 1;
  8718. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8719. }
  8720. },
  8721. enumerable: true,
  8722. configurable: true
  8723. });
  8724. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8725. get: function () {
  8726. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8727. },
  8728. set: function (value) {
  8729. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8730. },
  8731. enumerable: true,
  8732. configurable: true
  8733. });
  8734. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8735. get: function () {
  8736. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8737. },
  8738. set: function (value) {
  8739. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8740. },
  8741. enumerable: true,
  8742. configurable: true
  8743. });
  8744. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8745. get: function () {
  8746. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8747. },
  8748. set: function (value) {
  8749. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8750. },
  8751. enumerable: true,
  8752. configurable: true
  8753. });
  8754. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8755. var defines = [];
  8756. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8757. defines.push("#define VSM");
  8758. }
  8759. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8760. var mesh = subMesh.getMesh();
  8761. var material = subMesh.getMaterial();
  8762. // Alpha test
  8763. if (material && material.needAlphaTesting()) {
  8764. defines.push("#define ALPHATEST");
  8765. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8766. attribs.push(BABYLON.VertexBuffer.UVKind);
  8767. defines.push("#define UV1");
  8768. }
  8769. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8770. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8771. defines.push("#define UV2");
  8772. }
  8773. }
  8774. // Bones
  8775. if (mesh.useBones) {
  8776. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8777. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8778. defines.push("#define BONES");
  8779. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8780. }
  8781. // Instances
  8782. if (useInstances) {
  8783. defines.push("#define INSTANCES");
  8784. attribs.push("world0");
  8785. attribs.push("world1");
  8786. attribs.push("world2");
  8787. attribs.push("world3");
  8788. }
  8789. // Get correct effect
  8790. var join = defines.join("\n");
  8791. if (this._cachedDefines !== join) {
  8792. this._cachedDefines = join;
  8793. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8794. }
  8795. return this._effect.isReady();
  8796. };
  8797. ShadowGenerator.prototype.getShadowMap = function () {
  8798. return this._shadowMap;
  8799. };
  8800. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8801. if (this._shadowMap2) {
  8802. return this._shadowMap2;
  8803. }
  8804. return this._shadowMap;
  8805. };
  8806. ShadowGenerator.prototype.getLight = function () {
  8807. return this._light;
  8808. };
  8809. // Methods
  8810. ShadowGenerator.prototype.getTransformMatrix = function () {
  8811. var scene = this._scene;
  8812. if (this._currentRenderID === scene.getRenderId()) {
  8813. return this._transformMatrix;
  8814. }
  8815. this._currentRenderID = scene.getRenderId();
  8816. var lightPosition = this._light.position;
  8817. var lightDirection = this._light.direction;
  8818. if (this._light.computeTransformedPosition()) {
  8819. lightPosition = this._light.transformedPosition;
  8820. }
  8821. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  8822. this._cachedPosition = lightPosition.clone();
  8823. this._cachedDirection = lightDirection.clone();
  8824. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8825. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8826. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8827. }
  8828. return this._transformMatrix;
  8829. };
  8830. ShadowGenerator.prototype.getDarkness = function () {
  8831. return this._darkness;
  8832. };
  8833. ShadowGenerator.prototype.setDarkness = function (darkness) {
  8834. if (darkness >= 1.0)
  8835. this._darkness = 1.0;
  8836. else if (darkness <= 0.0)
  8837. this._darkness = 0.0;
  8838. else
  8839. this._darkness = darkness;
  8840. };
  8841. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  8842. this._transparencyShadow = hasShadow;
  8843. };
  8844. ShadowGenerator.prototype._packHalf = function (depth) {
  8845. var scale = depth * 255.0;
  8846. var fract = scale - Math.floor(scale);
  8847. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  8848. };
  8849. ShadowGenerator.prototype.dispose = function () {
  8850. this._shadowMap.dispose();
  8851. if (this._shadowMap2) {
  8852. this._shadowMap2.dispose();
  8853. }
  8854. if (this._downSamplePostprocess) {
  8855. this._downSamplePostprocess.dispose();
  8856. }
  8857. if (this._boxBlurPostprocess) {
  8858. this._boxBlurPostprocess.dispose();
  8859. }
  8860. };
  8861. ShadowGenerator._FILTER_NONE = 0;
  8862. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  8863. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  8864. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  8865. return ShadowGenerator;
  8866. })();
  8867. BABYLON.ShadowGenerator = ShadowGenerator;
  8868. })(BABYLON || (BABYLON = {}));
  8869. //# sourceMappingURL=babylon.shadowGenerator.js.map
  8870. var BABYLON;
  8871. (function (BABYLON) {
  8872. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  8873. if (boxMin.x > sphereCenter.x + sphereRadius)
  8874. return false;
  8875. if (sphereCenter.x - sphereRadius > boxMax.x)
  8876. return false;
  8877. if (boxMin.y > sphereCenter.y + sphereRadius)
  8878. return false;
  8879. if (sphereCenter.y - sphereRadius > boxMax.y)
  8880. return false;
  8881. if (boxMin.z > sphereCenter.z + sphereRadius)
  8882. return false;
  8883. if (sphereCenter.z - sphereRadius > boxMax.z)
  8884. return false;
  8885. return true;
  8886. };
  8887. var getLowestRoot = function (a, b, c, maxR) {
  8888. var determinant = b * b - 4.0 * a * c;
  8889. var result = { root: 0, found: false };
  8890. if (determinant < 0)
  8891. return result;
  8892. var sqrtD = Math.sqrt(determinant);
  8893. var r1 = (-b - sqrtD) / (2.0 * a);
  8894. var r2 = (-b + sqrtD) / (2.0 * a);
  8895. if (r1 > r2) {
  8896. var temp = r2;
  8897. r2 = r1;
  8898. r1 = temp;
  8899. }
  8900. if (r1 > 0 && r1 < maxR) {
  8901. result.root = r1;
  8902. result.found = true;
  8903. return result;
  8904. }
  8905. if (r2 > 0 && r2 < maxR) {
  8906. result.root = r2;
  8907. result.found = true;
  8908. return result;
  8909. }
  8910. return result;
  8911. };
  8912. var Collider = (function () {
  8913. function Collider() {
  8914. this.radius = new BABYLON.Vector3(1, 1, 1);
  8915. this.retry = 0;
  8916. this.basePointWorld = BABYLON.Vector3.Zero();
  8917. this.velocityWorld = BABYLON.Vector3.Zero();
  8918. this.normalizedVelocity = BABYLON.Vector3.Zero();
  8919. this._collisionPoint = BABYLON.Vector3.Zero();
  8920. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  8921. this._tempVector = BABYLON.Vector3.Zero();
  8922. this._tempVector2 = BABYLON.Vector3.Zero();
  8923. this._tempVector3 = BABYLON.Vector3.Zero();
  8924. this._tempVector4 = BABYLON.Vector3.Zero();
  8925. this._edge = BABYLON.Vector3.Zero();
  8926. this._baseToVertex = BABYLON.Vector3.Zero();
  8927. this._destinationPoint = BABYLON.Vector3.Zero();
  8928. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  8929. this._displacementVector = BABYLON.Vector3.Zero();
  8930. }
  8931. // Methods
  8932. Collider.prototype._initialize = function (source, dir, e) {
  8933. this.velocity = dir;
  8934. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  8935. this.basePoint = source;
  8936. source.multiplyToRef(this.radius, this.basePointWorld);
  8937. dir.multiplyToRef(this.radius, this.velocityWorld);
  8938. this.velocityWorldLength = this.velocityWorld.length();
  8939. this.epsilon = e;
  8940. this.collisionFound = false;
  8941. };
  8942. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  8943. pa.subtractToRef(point, this._tempVector);
  8944. pb.subtractToRef(point, this._tempVector2);
  8945. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  8946. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8947. if (d < 0)
  8948. return false;
  8949. pc.subtractToRef(point, this._tempVector3);
  8950. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  8951. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8952. if (d < 0)
  8953. return false;
  8954. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  8955. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8956. return d >= 0;
  8957. };
  8958. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  8959. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  8960. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  8961. if (distance > this.velocityWorldLength + max + sphereRadius) {
  8962. return false;
  8963. }
  8964. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  8965. return false;
  8966. return true;
  8967. };
  8968. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  8969. var t0;
  8970. var embeddedInPlane = false;
  8971. //defensive programming, actually not needed.
  8972. if (!trianglePlaneArray) {
  8973. trianglePlaneArray = [];
  8974. }
  8975. if (!trianglePlaneArray[faceIndex]) {
  8976. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  8977. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  8978. }
  8979. var trianglePlane = trianglePlaneArray[faceIndex];
  8980. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  8981. return;
  8982. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  8983. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  8984. if (normalDotVelocity == 0) {
  8985. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  8986. return;
  8987. embeddedInPlane = true;
  8988. t0 = 0;
  8989. }
  8990. else {
  8991. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  8992. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  8993. if (t0 > t1) {
  8994. var temp = t1;
  8995. t1 = t0;
  8996. t0 = temp;
  8997. }
  8998. if (t0 > 1.0 || t1 < 0.0)
  8999. return;
  9000. if (t0 < 0)
  9001. t0 = 0;
  9002. if (t0 > 1.0)
  9003. t0 = 1.0;
  9004. }
  9005. this._collisionPoint.copyFromFloats(0, 0, 0);
  9006. var found = false;
  9007. var t = 1.0;
  9008. if (!embeddedInPlane) {
  9009. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9010. this.velocity.scaleToRef(t0, this._tempVector);
  9011. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9012. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9013. found = true;
  9014. t = t0;
  9015. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9016. }
  9017. }
  9018. if (!found) {
  9019. var velocitySquaredLength = this.velocity.lengthSquared();
  9020. var a = velocitySquaredLength;
  9021. this.basePoint.subtractToRef(p1, this._tempVector);
  9022. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9023. var c = this._tempVector.lengthSquared() - 1.0;
  9024. var lowestRoot = getLowestRoot(a, b, c, t);
  9025. if (lowestRoot.found) {
  9026. t = lowestRoot.root;
  9027. found = true;
  9028. this._collisionPoint.copyFrom(p1);
  9029. }
  9030. this.basePoint.subtractToRef(p2, this._tempVector);
  9031. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9032. c = this._tempVector.lengthSquared() - 1.0;
  9033. lowestRoot = getLowestRoot(a, b, c, t);
  9034. if (lowestRoot.found) {
  9035. t = lowestRoot.root;
  9036. found = true;
  9037. this._collisionPoint.copyFrom(p2);
  9038. }
  9039. this.basePoint.subtractToRef(p3, this._tempVector);
  9040. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9041. c = this._tempVector.lengthSquared() - 1.0;
  9042. lowestRoot = getLowestRoot(a, b, c, t);
  9043. if (lowestRoot.found) {
  9044. t = lowestRoot.root;
  9045. found = true;
  9046. this._collisionPoint.copyFrom(p3);
  9047. }
  9048. p2.subtractToRef(p1, this._edge);
  9049. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9050. var edgeSquaredLength = this._edge.lengthSquared();
  9051. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9052. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9053. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9054. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9055. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9056. lowestRoot = getLowestRoot(a, b, c, t);
  9057. if (lowestRoot.found) {
  9058. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9059. if (f >= 0.0 && f <= 1.0) {
  9060. t = lowestRoot.root;
  9061. found = true;
  9062. this._edge.scaleInPlace(f);
  9063. p1.addToRef(this._edge, this._collisionPoint);
  9064. }
  9065. }
  9066. p3.subtractToRef(p2, this._edge);
  9067. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9068. edgeSquaredLength = this._edge.lengthSquared();
  9069. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9070. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9071. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9072. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9073. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9074. lowestRoot = getLowestRoot(a, b, c, t);
  9075. if (lowestRoot.found) {
  9076. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9077. if (f >= 0.0 && f <= 1.0) {
  9078. t = lowestRoot.root;
  9079. found = true;
  9080. this._edge.scaleInPlace(f);
  9081. p2.addToRef(this._edge, this._collisionPoint);
  9082. }
  9083. }
  9084. p1.subtractToRef(p3, this._edge);
  9085. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9086. edgeSquaredLength = this._edge.lengthSquared();
  9087. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9088. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9089. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9090. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9091. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9092. lowestRoot = getLowestRoot(a, b, c, t);
  9093. if (lowestRoot.found) {
  9094. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9095. if (f >= 0.0 && f <= 1.0) {
  9096. t = lowestRoot.root;
  9097. found = true;
  9098. this._edge.scaleInPlace(f);
  9099. p3.addToRef(this._edge, this._collisionPoint);
  9100. }
  9101. }
  9102. }
  9103. if (found) {
  9104. var distToCollision = t * this.velocity.length();
  9105. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9106. if (!this.intersectionPoint) {
  9107. this.intersectionPoint = this._collisionPoint.clone();
  9108. }
  9109. else {
  9110. this.intersectionPoint.copyFrom(this._collisionPoint);
  9111. }
  9112. this.nearestDistance = distToCollision;
  9113. this.collisionFound = true;
  9114. }
  9115. }
  9116. };
  9117. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9118. for (var i = indexStart; i < indexEnd; i += 3) {
  9119. var p1 = pts[indices[i] - decal];
  9120. var p2 = pts[indices[i + 1] - decal];
  9121. var p3 = pts[indices[i + 2] - decal];
  9122. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9123. }
  9124. };
  9125. Collider.prototype._getResponse = function (pos, vel) {
  9126. pos.addToRef(vel, this._destinationPoint);
  9127. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9128. this.basePoint.addToRef(vel, pos);
  9129. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9130. this._slidePlaneNormal.normalize();
  9131. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9132. pos.addInPlace(this._displacementVector);
  9133. this.intersectionPoint.addInPlace(this._displacementVector);
  9134. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9135. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9136. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9137. };
  9138. return Collider;
  9139. })();
  9140. BABYLON.Collider = Collider;
  9141. })(BABYLON || (BABYLON = {}));
  9142. //# sourceMappingURL=babylon.collider.js.map
  9143. var BABYLON;
  9144. (function (BABYLON) {
  9145. //WebWorker code will be inserted to this variable.
  9146. BABYLON.CollisionWorker = "";
  9147. (function (WorkerTaskType) {
  9148. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9149. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9150. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9151. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9152. var WorkerTaskType = BABYLON.WorkerTaskType;
  9153. (function (WorkerReplyType) {
  9154. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9155. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9156. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9157. var WorkerReplyType = BABYLON.WorkerReplyType;
  9158. var CollisionCoordinatorWorker = (function () {
  9159. function CollisionCoordinatorWorker() {
  9160. var _this = this;
  9161. this._scaledPosition = BABYLON.Vector3.Zero();
  9162. this._scaledVelocity = BABYLON.Vector3.Zero();
  9163. this.onMeshUpdated = function (mesh) {
  9164. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9165. };
  9166. this.onGeometryUpdated = function (geometry) {
  9167. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9168. };
  9169. this._afterRender = function () {
  9170. if (!_this._init)
  9171. return;
  9172. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9173. return;
  9174. }
  9175. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9176. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9177. if (_this._runningUpdated > 4) {
  9178. return;
  9179. }
  9180. ++_this._runningUpdated;
  9181. var payload = {
  9182. updatedMeshes: _this._addUpdateMeshesList,
  9183. updatedGeometries: _this._addUpdateGeometriesList,
  9184. removedGeometries: _this._toRemoveGeometryArray,
  9185. removedMeshes: _this._toRemoveMeshesArray
  9186. };
  9187. var message = {
  9188. payload: payload,
  9189. taskType: 1 /* UPDATE */
  9190. };
  9191. var serializable = [];
  9192. for (var id in payload.updatedGeometries) {
  9193. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9194. //prepare transferables
  9195. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9196. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9197. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9198. }
  9199. }
  9200. _this._worker.postMessage(message, serializable);
  9201. _this._addUpdateMeshesList = {};
  9202. _this._addUpdateGeometriesList = {};
  9203. _this._toRemoveGeometryArray = [];
  9204. _this._toRemoveMeshesArray = [];
  9205. };
  9206. this._onMessageFromWorker = function (e) {
  9207. var returnData = e.data;
  9208. if (returnData.error != 0 /* SUCCESS */) {
  9209. //TODO what errors can be returned from the worker?
  9210. BABYLON.Tools.Warn("error returned from worker!");
  9211. return;
  9212. }
  9213. switch (returnData.taskType) {
  9214. case 0 /* INIT */:
  9215. _this._init = true;
  9216. //Update the worked with ALL of the scene's current state
  9217. _this._scene.meshes.forEach(function (mesh) {
  9218. _this.onMeshAdded(mesh);
  9219. });
  9220. _this._scene.getGeometries().forEach(function (geometry) {
  9221. _this.onGeometryAdded(geometry);
  9222. });
  9223. break;
  9224. case 1 /* UPDATE */:
  9225. _this._runningUpdated--;
  9226. break;
  9227. case 2 /* COLLIDE */:
  9228. _this._runningCollisionTask = false;
  9229. var returnPayload = returnData.payload;
  9230. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9231. return;
  9232. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9233. //cleanup
  9234. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9235. break;
  9236. }
  9237. };
  9238. this._collisionsCallbackArray = [];
  9239. this._init = false;
  9240. this._runningUpdated = 0;
  9241. this._runningCollisionTask = false;
  9242. this._addUpdateMeshesList = {};
  9243. this._addUpdateGeometriesList = {};
  9244. this._toRemoveGeometryArray = [];
  9245. this._toRemoveMeshesArray = [];
  9246. }
  9247. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9248. if (!this._init)
  9249. ;
  9250. if (this._collisionsCallbackArray[collisionIndex])
  9251. return;
  9252. position.divideToRef(collider.radius, this._scaledPosition);
  9253. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9254. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9255. var payload = {
  9256. collider: {
  9257. position: this._scaledPosition.asArray(),
  9258. velocity: this._scaledVelocity.asArray(),
  9259. radius: collider.radius.asArray()
  9260. },
  9261. collisionId: collisionIndex,
  9262. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9263. maximumRetry: maximumRetry
  9264. };
  9265. var message = {
  9266. payload: payload,
  9267. taskType: 2 /* COLLIDE */
  9268. };
  9269. this._worker.postMessage(message);
  9270. };
  9271. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9272. this._scene = scene;
  9273. this._scene.registerAfterRender(this._afterRender);
  9274. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9275. this._worker = new Worker(workerUrl);
  9276. this._worker.onmessage = this._onMessageFromWorker;
  9277. var message = {
  9278. payload: {},
  9279. taskType: 0 /* INIT */
  9280. };
  9281. this._worker.postMessage(message);
  9282. };
  9283. CollisionCoordinatorWorker.prototype.destroy = function () {
  9284. this._scene.unregisterAfterRender(this._afterRender);
  9285. this._worker.terminate();
  9286. };
  9287. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9288. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9289. this.onMeshUpdated(mesh);
  9290. };
  9291. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9292. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9293. };
  9294. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9295. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9296. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9297. this.onGeometryUpdated(geometry);
  9298. };
  9299. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9300. this._toRemoveGeometryArray.push(geometry.id);
  9301. };
  9302. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9303. var submeshes = [];
  9304. if (mesh.subMeshes) {
  9305. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9306. return {
  9307. position: idx,
  9308. verticesStart: sm.verticesStart,
  9309. verticesCount: sm.verticesCount,
  9310. indexStart: sm.indexStart,
  9311. indexCount: sm.indexCount,
  9312. hasMaterial: !!sm.getMaterial(),
  9313. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9314. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9315. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9316. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9317. };
  9318. });
  9319. }
  9320. var geometryId = mesh.geometry ? mesh.geometry.id : null;
  9321. return {
  9322. uniqueId: mesh.uniqueId,
  9323. id: mesh.id,
  9324. name: mesh.name,
  9325. geometryId: geometryId,
  9326. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9327. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9328. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9329. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9330. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9331. subMeshes: submeshes,
  9332. checkCollisions: mesh.checkCollisions
  9333. };
  9334. };
  9335. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9336. return {
  9337. id: geometry.id,
  9338. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9339. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9340. indices: new Int32Array(geometry.getIndices() || []),
  9341. };
  9342. };
  9343. return CollisionCoordinatorWorker;
  9344. })();
  9345. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9346. var CollisionCoordinatorLegacy = (function () {
  9347. function CollisionCoordinatorLegacy() {
  9348. this._scaledPosition = BABYLON.Vector3.Zero();
  9349. this._scaledVelocity = BABYLON.Vector3.Zero();
  9350. this._finalPosition = BABYLON.Vector3.Zero();
  9351. }
  9352. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9353. position.divideToRef(collider.radius, this._scaledPosition);
  9354. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9355. collider.retry = 0;
  9356. collider.initialVelocity = this._scaledVelocity;
  9357. collider.initialPosition = this._scaledPosition;
  9358. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9359. this._finalPosition.multiplyInPlace(collider.radius);
  9360. //run the callback
  9361. onNewPosition(null, this._finalPosition, collider.collidedMesh);
  9362. };
  9363. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9364. this._scene = scene;
  9365. };
  9366. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9367. //Legacy need no destruction method.
  9368. };
  9369. //No update in legacy mode
  9370. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) {
  9371. };
  9372. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) {
  9373. };
  9374. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) {
  9375. };
  9376. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) {
  9377. };
  9378. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) {
  9379. };
  9380. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) {
  9381. };
  9382. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9383. if (excludedMesh === void 0) { excludedMesh = null; }
  9384. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9385. if (collider.retry >= maximumRetry) {
  9386. finalPosition.copyFrom(position);
  9387. return;
  9388. }
  9389. collider._initialize(position, velocity, closeDistance);
  9390. for (var index = 0; index < this._scene.meshes.length; index++) {
  9391. var mesh = this._scene.meshes[index];
  9392. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9393. mesh._checkCollision(collider);
  9394. }
  9395. }
  9396. if (!collider.collisionFound) {
  9397. position.addToRef(velocity, finalPosition);
  9398. return;
  9399. }
  9400. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9401. collider._getResponse(position, velocity);
  9402. }
  9403. if (velocity.length() <= closeDistance) {
  9404. finalPosition.copyFrom(position);
  9405. return;
  9406. }
  9407. collider.retry++;
  9408. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9409. };
  9410. return CollisionCoordinatorLegacy;
  9411. })();
  9412. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9413. })(BABYLON || (BABYLON = {}));
  9414. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  9415. var __extends = this.__extends || function (d, b) {
  9416. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9417. function __() { this.constructor = d; }
  9418. __.prototype = b.prototype;
  9419. d.prototype = new __();
  9420. };
  9421. var BABYLON;
  9422. (function (BABYLON) {
  9423. var Camera = (function (_super) {
  9424. __extends(Camera, _super);
  9425. function Camera(name, position, scene) {
  9426. _super.call(this, name, scene);
  9427. this.position = position;
  9428. // Members
  9429. this.upVector = BABYLON.Vector3.Up();
  9430. this.orthoLeft = null;
  9431. this.orthoRight = null;
  9432. this.orthoBottom = null;
  9433. this.orthoTop = null;
  9434. this.fov = 0.8;
  9435. this.minZ = 1.0;
  9436. this.maxZ = 10000.0;
  9437. this.inertia = 0.9;
  9438. this.mode = Camera.PERSPECTIVE_CAMERA;
  9439. this.isIntermediate = false;
  9440. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9441. this.subCameras = [];
  9442. this.layerMask = 0xFFFFFFFF;
  9443. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9444. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9445. this._projectionMatrix = new BABYLON.Matrix();
  9446. this._postProcesses = new Array();
  9447. this._postProcessesTakenIndices = [];
  9448. this._activeMeshes = new BABYLON.SmartArray(256);
  9449. this._globalPosition = BABYLON.Vector3.Zero();
  9450. scene.addCamera(this);
  9451. if (!scene.activeCamera) {
  9452. scene.activeCamera = this;
  9453. }
  9454. }
  9455. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9456. get: function () {
  9457. return Camera._PERSPECTIVE_CAMERA;
  9458. },
  9459. enumerable: true,
  9460. configurable: true
  9461. });
  9462. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9463. get: function () {
  9464. return Camera._ORTHOGRAPHIC_CAMERA;
  9465. },
  9466. enumerable: true,
  9467. configurable: true
  9468. });
  9469. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9470. get: function () {
  9471. return Camera._FOVMODE_VERTICAL_FIXED;
  9472. },
  9473. enumerable: true,
  9474. configurable: true
  9475. });
  9476. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9477. get: function () {
  9478. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9479. },
  9480. enumerable: true,
  9481. configurable: true
  9482. });
  9483. Object.defineProperty(Camera.prototype, "globalPosition", {
  9484. get: function () {
  9485. return this._globalPosition;
  9486. },
  9487. enumerable: true,
  9488. configurable: true
  9489. });
  9490. Camera.prototype.getActiveMeshes = function () {
  9491. return this._activeMeshes;
  9492. };
  9493. Camera.prototype.isActiveMesh = function (mesh) {
  9494. return (this._activeMeshes.indexOf(mesh) !== -1);
  9495. };
  9496. //Cache
  9497. Camera.prototype._initCache = function () {
  9498. _super.prototype._initCache.call(this);
  9499. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9500. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9501. this._cache.mode = undefined;
  9502. this._cache.minZ = undefined;
  9503. this._cache.maxZ = undefined;
  9504. this._cache.fov = undefined;
  9505. this._cache.aspectRatio = undefined;
  9506. this._cache.orthoLeft = undefined;
  9507. this._cache.orthoRight = undefined;
  9508. this._cache.orthoBottom = undefined;
  9509. this._cache.orthoTop = undefined;
  9510. this._cache.renderWidth = undefined;
  9511. this._cache.renderHeight = undefined;
  9512. };
  9513. Camera.prototype._updateCache = function (ignoreParentClass) {
  9514. if (!ignoreParentClass) {
  9515. _super.prototype._updateCache.call(this);
  9516. }
  9517. var engine = this.getEngine();
  9518. this._cache.position.copyFrom(this.position);
  9519. this._cache.upVector.copyFrom(this.upVector);
  9520. this._cache.mode = this.mode;
  9521. this._cache.minZ = this.minZ;
  9522. this._cache.maxZ = this.maxZ;
  9523. this._cache.fov = this.fov;
  9524. this._cache.aspectRatio = engine.getAspectRatio(this);
  9525. this._cache.orthoLeft = this.orthoLeft;
  9526. this._cache.orthoRight = this.orthoRight;
  9527. this._cache.orthoBottom = this.orthoBottom;
  9528. this._cache.orthoTop = this.orthoTop;
  9529. this._cache.renderWidth = engine.getRenderWidth();
  9530. this._cache.renderHeight = engine.getRenderHeight();
  9531. };
  9532. Camera.prototype._updateFromScene = function () {
  9533. this.updateCache();
  9534. this._update();
  9535. };
  9536. // Synchronized
  9537. Camera.prototype._isSynchronized = function () {
  9538. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9539. };
  9540. Camera.prototype._isSynchronizedViewMatrix = function () {
  9541. if (!_super.prototype._isSynchronized.call(this))
  9542. return false;
  9543. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  9544. };
  9545. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9546. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  9547. if (!check) {
  9548. return false;
  9549. }
  9550. var engine = this.getEngine();
  9551. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9552. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  9553. }
  9554. else {
  9555. 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();
  9556. }
  9557. return check;
  9558. };
  9559. // Controls
  9560. Camera.prototype.attachControl = function (element) {
  9561. };
  9562. Camera.prototype.detachControl = function (element) {
  9563. };
  9564. Camera.prototype._update = function () {
  9565. };
  9566. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9567. if (insertAt === void 0) { insertAt = null; }
  9568. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9569. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9570. return 0;
  9571. }
  9572. if (insertAt == null || insertAt < 0) {
  9573. this._postProcesses.push(postProcess);
  9574. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9575. return this._postProcesses.length - 1;
  9576. }
  9577. var add = 0;
  9578. if (this._postProcesses[insertAt]) {
  9579. var start = this._postProcesses.length - 1;
  9580. for (var i = start; i >= insertAt + 1; --i) {
  9581. this._postProcesses[i + 1] = this._postProcesses[i];
  9582. }
  9583. add = 1;
  9584. }
  9585. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9586. if (this._postProcessesTakenIndices[i] < insertAt) {
  9587. continue;
  9588. }
  9589. start = this._postProcessesTakenIndices.length - 1;
  9590. for (var j = start; j >= i; --j) {
  9591. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9592. }
  9593. this._postProcessesTakenIndices[i] = insertAt;
  9594. break;
  9595. }
  9596. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  9597. this._postProcessesTakenIndices.push(insertAt);
  9598. }
  9599. var result = insertAt + add;
  9600. this._postProcesses[result] = postProcess;
  9601. return result;
  9602. };
  9603. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9604. if (atIndices === void 0) { atIndices = null; }
  9605. var result = [];
  9606. if (!atIndices) {
  9607. var length = this._postProcesses.length;
  9608. for (var i = 0; i < length; i++) {
  9609. if (this._postProcesses[i] !== postProcess) {
  9610. continue;
  9611. }
  9612. delete this._postProcesses[i];
  9613. var index = this._postProcessesTakenIndices.indexOf(i);
  9614. this._postProcessesTakenIndices.splice(index, 1);
  9615. }
  9616. }
  9617. else {
  9618. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9619. for (i = 0; i < atIndices.length; i++) {
  9620. var foundPostProcess = this._postProcesses[atIndices[i]];
  9621. if (foundPostProcess !== postProcess) {
  9622. result.push(i);
  9623. continue;
  9624. }
  9625. delete this._postProcesses[atIndices[i]];
  9626. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9627. this._postProcessesTakenIndices.splice(index, 1);
  9628. }
  9629. }
  9630. return result;
  9631. };
  9632. Camera.prototype.getWorldMatrix = function () {
  9633. if (!this._worldMatrix) {
  9634. this._worldMatrix = BABYLON.Matrix.Identity();
  9635. }
  9636. var viewMatrix = this.getViewMatrix();
  9637. viewMatrix.invertToRef(this._worldMatrix);
  9638. return this._worldMatrix;
  9639. };
  9640. Camera.prototype._getViewMatrix = function () {
  9641. return BABYLON.Matrix.Identity();
  9642. };
  9643. Camera.prototype.getViewMatrix = function (force) {
  9644. this._computedViewMatrix = this._computeViewMatrix(force);
  9645. if (!force && this._isSynchronizedViewMatrix()) {
  9646. return this._computedViewMatrix;
  9647. }
  9648. if (!this.parent || !this.parent.getWorldMatrix) {
  9649. this._globalPosition.copyFrom(this.position);
  9650. }
  9651. else {
  9652. if (!this._worldMatrix) {
  9653. this._worldMatrix = BABYLON.Matrix.Identity();
  9654. }
  9655. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9656. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9657. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9658. this._computedViewMatrix.invert();
  9659. this._markSyncedWithParent();
  9660. }
  9661. this._currentRenderId = this.getScene().getRenderId();
  9662. return this._computedViewMatrix;
  9663. };
  9664. Camera.prototype._computeViewMatrix = function (force) {
  9665. if (!force && this._isSynchronizedViewMatrix()) {
  9666. return this._computedViewMatrix;
  9667. }
  9668. this._computedViewMatrix = this._getViewMatrix();
  9669. this._currentRenderId = this.getScene().getRenderId();
  9670. return this._computedViewMatrix;
  9671. };
  9672. Camera.prototype.getProjectionMatrix = function (force) {
  9673. if (!force && this._isSynchronizedProjectionMatrix()) {
  9674. return this._projectionMatrix;
  9675. }
  9676. var engine = this.getEngine();
  9677. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9678. if (this.minZ <= 0) {
  9679. this.minZ = 0.1;
  9680. }
  9681. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9682. return this._projectionMatrix;
  9683. }
  9684. var halfWidth = engine.getRenderWidth() / 2.0;
  9685. var halfHeight = engine.getRenderHeight() / 2.0;
  9686. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9687. return this._projectionMatrix;
  9688. };
  9689. Camera.prototype.dispose = function () {
  9690. // Remove from scene
  9691. this.getScene().removeCamera(this);
  9692. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9693. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9694. }
  9695. };
  9696. // Statics
  9697. Camera._PERSPECTIVE_CAMERA = 0;
  9698. Camera._ORTHOGRAPHIC_CAMERA = 1;
  9699. Camera._FOVMODE_VERTICAL_FIXED = 0;
  9700. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  9701. return Camera;
  9702. })(BABYLON.Node);
  9703. BABYLON.Camera = Camera;
  9704. })(BABYLON || (BABYLON = {}));
  9705. //# sourceMappingURL=babylon.camera.js.map
  9706. var __extends = this.__extends || function (d, b) {
  9707. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9708. function __() { this.constructor = d; }
  9709. __.prototype = b.prototype;
  9710. d.prototype = new __();
  9711. };
  9712. var BABYLON;
  9713. (function (BABYLON) {
  9714. var TargetCamera = (function (_super) {
  9715. __extends(TargetCamera, _super);
  9716. function TargetCamera(name, position, scene) {
  9717. _super.call(this, name, position, scene);
  9718. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  9719. this.cameraRotation = new BABYLON.Vector2(0, 0);
  9720. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9721. this.speed = 2.0;
  9722. this.noRotationConstraint = false;
  9723. this.lockedTarget = null;
  9724. this._currentTarget = BABYLON.Vector3.Zero();
  9725. this._viewMatrix = BABYLON.Matrix.Zero();
  9726. this._camMatrix = BABYLON.Matrix.Zero();
  9727. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  9728. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  9729. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  9730. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  9731. this._lookAtTemp = BABYLON.Matrix.Zero();
  9732. this._tempMatrix = BABYLON.Matrix.Zero();
  9733. }
  9734. TargetCamera.prototype._getLockedTargetPosition = function () {
  9735. if (!this.lockedTarget) {
  9736. return null;
  9737. }
  9738. return this.lockedTarget.position || this.lockedTarget;
  9739. };
  9740. // Cache
  9741. TargetCamera.prototype._initCache = function () {
  9742. _super.prototype._initCache.call(this);
  9743. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9744. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9745. };
  9746. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  9747. if (!ignoreParentClass) {
  9748. _super.prototype._updateCache.call(this);
  9749. }
  9750. var lockedTargetPosition = this._getLockedTargetPosition();
  9751. if (!lockedTargetPosition) {
  9752. this._cache.lockedTarget = null;
  9753. }
  9754. else {
  9755. if (!this._cache.lockedTarget) {
  9756. this._cache.lockedTarget = lockedTargetPosition.clone();
  9757. }
  9758. else {
  9759. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  9760. }
  9761. }
  9762. this._cache.rotation.copyFrom(this.rotation);
  9763. };
  9764. // Synchronized
  9765. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  9766. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  9767. return false;
  9768. }
  9769. var lockedTargetPosition = this._getLockedTargetPosition();
  9770. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  9771. };
  9772. // Methods
  9773. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  9774. var engine = this.getEngine();
  9775. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  9776. };
  9777. // Target
  9778. TargetCamera.prototype.setTarget = function (target) {
  9779. this.upVector.normalize();
  9780. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  9781. this._camMatrix.invert();
  9782. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  9783. var vDir = target.subtract(this.position);
  9784. if (vDir.x >= 0.0) {
  9785. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  9786. }
  9787. else {
  9788. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  9789. }
  9790. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  9791. if (isNaN(this.rotation.x)) {
  9792. this.rotation.x = 0;
  9793. }
  9794. if (isNaN(this.rotation.y)) {
  9795. this.rotation.y = 0;
  9796. }
  9797. if (isNaN(this.rotation.z)) {
  9798. this.rotation.z = 0;
  9799. }
  9800. };
  9801. TargetCamera.prototype.getTarget = function () {
  9802. return this._currentTarget;
  9803. };
  9804. TargetCamera.prototype._decideIfNeedsToMove = function () {
  9805. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  9806. };
  9807. TargetCamera.prototype._updatePosition = function () {
  9808. this.position.addInPlace(this.cameraDirection);
  9809. };
  9810. TargetCamera.prototype._update = function () {
  9811. var needToMove = this._decideIfNeedsToMove();
  9812. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  9813. // Move
  9814. if (needToMove) {
  9815. this._updatePosition();
  9816. }
  9817. // Rotate
  9818. if (needToRotate) {
  9819. this.rotation.x += this.cameraRotation.x;
  9820. this.rotation.y += this.cameraRotation.y;
  9821. if (!this.noRotationConstraint) {
  9822. var limit = (Math.PI / 2) * 0.95;
  9823. if (this.rotation.x > limit)
  9824. this.rotation.x = limit;
  9825. if (this.rotation.x < -limit)
  9826. this.rotation.x = -limit;
  9827. }
  9828. }
  9829. // Inertia
  9830. if (needToMove) {
  9831. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  9832. this.cameraDirection.x = 0;
  9833. }
  9834. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  9835. this.cameraDirection.y = 0;
  9836. }
  9837. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  9838. this.cameraDirection.z = 0;
  9839. }
  9840. this.cameraDirection.scaleInPlace(this.inertia);
  9841. }
  9842. if (needToRotate) {
  9843. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  9844. this.cameraRotation.x = 0;
  9845. }
  9846. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  9847. this.cameraRotation.y = 0;
  9848. }
  9849. this.cameraRotation.scaleInPlace(this.inertia);
  9850. }
  9851. };
  9852. TargetCamera.prototype._getViewMatrix = function () {
  9853. if (!this.lockedTarget) {
  9854. // Compute
  9855. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  9856. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  9857. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  9858. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  9859. this._lookAtTemp.invert();
  9860. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  9861. }
  9862. else {
  9863. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  9864. }
  9865. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  9866. // Computing target and final matrix
  9867. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  9868. }
  9869. else {
  9870. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  9871. }
  9872. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  9873. return this._viewMatrix;
  9874. };
  9875. return TargetCamera;
  9876. })(BABYLON.Camera);
  9877. BABYLON.TargetCamera = TargetCamera;
  9878. })(BABYLON || (BABYLON = {}));
  9879. //# sourceMappingURL=babylon.targetCamera.js.map
  9880. var __extends = this.__extends || function (d, b) {
  9881. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9882. function __() { this.constructor = d; }
  9883. __.prototype = b.prototype;
  9884. d.prototype = new __();
  9885. };
  9886. var BABYLON;
  9887. (function (BABYLON) {
  9888. var FreeCamera = (function (_super) {
  9889. __extends(FreeCamera, _super);
  9890. function FreeCamera(name, position, scene) {
  9891. var _this = this;
  9892. _super.call(this, name, position, scene);
  9893. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9894. this.keysUp = [38];
  9895. this.keysDown = [40];
  9896. this.keysLeft = [37];
  9897. this.keysRight = [39];
  9898. this.checkCollisions = false;
  9899. this.applyGravity = false;
  9900. this.angularSensibility = 2000.0;
  9901. this._keys = [];
  9902. this._collider = new BABYLON.Collider();
  9903. this._needMoveForGravity = true;
  9904. this._oldPosition = BABYLON.Vector3.Zero();
  9905. this._diffPosition = BABYLON.Vector3.Zero();
  9906. this._newPosition = BABYLON.Vector3.Zero();
  9907. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9908. if (collidedMesh === void 0) { collidedMesh = null; }
  9909. //TODO move this to the collision coordinator!
  9910. if (collisionId != null || collisionId != undefined)
  9911. newPosition.multiplyInPlace(_this._collider.radius);
  9912. _this._newPosition.copyFrom(newPosition);
  9913. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  9914. var oldPosition = _this.position.clone();
  9915. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  9916. _this.position.addInPlace(_this._diffPosition);
  9917. if (_this.onCollide && collidedMesh) {
  9918. _this.onCollide(collidedMesh);
  9919. }
  9920. }
  9921. //check if it is the gravity inspection
  9922. if (collisionId != _this.uniqueId) {
  9923. _this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, _this.position) != 0);
  9924. }
  9925. };
  9926. }
  9927. // Controls
  9928. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  9929. var _this = this;
  9930. var previousPosition;
  9931. var engine = this.getEngine();
  9932. if (this._attachedElement) {
  9933. return;
  9934. }
  9935. this._attachedElement = element;
  9936. if (this._onMouseDown === undefined) {
  9937. this._onMouseDown = function (evt) {
  9938. previousPosition = {
  9939. x: evt.clientX,
  9940. y: evt.clientY
  9941. };
  9942. if (!noPreventDefault) {
  9943. evt.preventDefault();
  9944. }
  9945. };
  9946. this._onMouseUp = function (evt) {
  9947. previousPosition = null;
  9948. if (!noPreventDefault) {
  9949. evt.preventDefault();
  9950. }
  9951. };
  9952. this._onMouseOut = function (evt) {
  9953. previousPosition = null;
  9954. _this._keys = [];
  9955. if (!noPreventDefault) {
  9956. evt.preventDefault();
  9957. }
  9958. };
  9959. this._onMouseMove = function (evt) {
  9960. if (!previousPosition && !engine.isPointerLock) {
  9961. return;
  9962. }
  9963. var offsetX;
  9964. var offsetY;
  9965. if (!engine.isPointerLock) {
  9966. offsetX = evt.clientX - previousPosition.x;
  9967. offsetY = evt.clientY - previousPosition.y;
  9968. }
  9969. else {
  9970. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  9971. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  9972. }
  9973. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  9974. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  9975. previousPosition = {
  9976. x: evt.clientX,
  9977. y: evt.clientY
  9978. };
  9979. if (!noPreventDefault) {
  9980. evt.preventDefault();
  9981. }
  9982. };
  9983. this._onKeyDown = function (evt) {
  9984. 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) {
  9985. var index = _this._keys.indexOf(evt.keyCode);
  9986. if (index === -1) {
  9987. _this._keys.push(evt.keyCode);
  9988. }
  9989. if (!noPreventDefault) {
  9990. evt.preventDefault();
  9991. }
  9992. }
  9993. };
  9994. this._onKeyUp = function (evt) {
  9995. 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) {
  9996. var index = _this._keys.indexOf(evt.keyCode);
  9997. if (index >= 0) {
  9998. _this._keys.splice(index, 1);
  9999. }
  10000. if (!noPreventDefault) {
  10001. evt.preventDefault();
  10002. }
  10003. }
  10004. };
  10005. this._onLostFocus = function () {
  10006. _this._keys = [];
  10007. };
  10008. this._reset = function () {
  10009. _this._keys = [];
  10010. previousPosition = null;
  10011. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10012. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10013. };
  10014. }
  10015. element.addEventListener("mousedown", this._onMouseDown, false);
  10016. element.addEventListener("mouseup", this._onMouseUp, false);
  10017. element.addEventListener("mouseout", this._onMouseOut, false);
  10018. element.addEventListener("mousemove", this._onMouseMove, false);
  10019. BABYLON.Tools.RegisterTopRootEvents([
  10020. { name: "keydown", handler: this._onKeyDown },
  10021. { name: "keyup", handler: this._onKeyUp },
  10022. { name: "blur", handler: this._onLostFocus }
  10023. ]);
  10024. };
  10025. FreeCamera.prototype.detachControl = function (element) {
  10026. if (this._attachedElement != element) {
  10027. return;
  10028. }
  10029. element.removeEventListener("mousedown", this._onMouseDown);
  10030. element.removeEventListener("mouseup", this._onMouseUp);
  10031. element.removeEventListener("mouseout", this._onMouseOut);
  10032. element.removeEventListener("mousemove", this._onMouseMove);
  10033. BABYLON.Tools.UnregisterTopRootEvents([
  10034. { name: "keydown", handler: this._onKeyDown },
  10035. { name: "keyup", handler: this._onKeyUp },
  10036. { name: "blur", handler: this._onLostFocus }
  10037. ]);
  10038. this._attachedElement = null;
  10039. if (this._reset) {
  10040. this._reset();
  10041. }
  10042. };
  10043. FreeCamera.prototype._collideWithWorld = function (velocity, gravityInspection) {
  10044. if (gravityInspection === void 0) { gravityInspection = false; }
  10045. var globalPosition;
  10046. if (this.parent) {
  10047. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10048. }
  10049. else {
  10050. globalPosition = this.position;
  10051. }
  10052. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10053. this._collider.radius = this.ellipsoid;
  10054. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, velocity.equals(this.getScene().gravity) ? this.uniqueId + 100000 : this.uniqueId);
  10055. };
  10056. FreeCamera.prototype._checkInputs = function () {
  10057. if (!this._localDirection) {
  10058. this._localDirection = BABYLON.Vector3.Zero();
  10059. this._transformedDirection = BABYLON.Vector3.Zero();
  10060. }
  10061. for (var index = 0; index < this._keys.length; index++) {
  10062. var keyCode = this._keys[index];
  10063. var speed = this._computeLocalCameraSpeed();
  10064. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10065. this._localDirection.copyFromFloats(-speed, 0, 0);
  10066. }
  10067. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10068. this._localDirection.copyFromFloats(0, 0, speed);
  10069. }
  10070. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10071. this._localDirection.copyFromFloats(speed, 0, 0);
  10072. }
  10073. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10074. this._localDirection.copyFromFloats(0, 0, -speed);
  10075. }
  10076. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10077. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10078. this.cameraDirection.addInPlace(this._transformedDirection);
  10079. }
  10080. };
  10081. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10082. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10083. };
  10084. FreeCamera.prototype._updatePosition = function () {
  10085. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10086. this._collideWithWorld(this.cameraDirection, false);
  10087. if (this.applyGravity) {
  10088. this._collideWithWorld(this.getScene().gravity, true);
  10089. }
  10090. }
  10091. else {
  10092. this.position.addInPlace(this.cameraDirection);
  10093. }
  10094. };
  10095. FreeCamera.prototype._update = function () {
  10096. this._checkInputs();
  10097. _super.prototype._update.call(this);
  10098. };
  10099. return FreeCamera;
  10100. })(BABYLON.TargetCamera);
  10101. BABYLON.FreeCamera = FreeCamera;
  10102. })(BABYLON || (BABYLON = {}));
  10103. //# sourceMappingURL=babylon.freeCamera.js.map
  10104. var __extends = this.__extends || function (d, b) {
  10105. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10106. function __() { this.constructor = d; }
  10107. __.prototype = b.prototype;
  10108. d.prototype = new __();
  10109. };
  10110. var BABYLON;
  10111. (function (BABYLON) {
  10112. var FollowCamera = (function (_super) {
  10113. __extends(FollowCamera, _super);
  10114. function FollowCamera(name, position, scene) {
  10115. _super.call(this, name, position, scene);
  10116. this.radius = 12;
  10117. this.rotationOffset = 0;
  10118. this.heightOffset = 4;
  10119. this.cameraAcceleration = 0.05;
  10120. this.maxCameraSpeed = 20;
  10121. }
  10122. FollowCamera.prototype.getRadians = function (degrees) {
  10123. return degrees * Math.PI / 180;
  10124. };
  10125. FollowCamera.prototype.follow = function (cameraTarget) {
  10126. if (!cameraTarget)
  10127. return;
  10128. var yRotation;
  10129. if (cameraTarget.rotationQuaternion) {
  10130. var rotMatrix = new BABYLON.Matrix();
  10131. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10132. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10133. }
  10134. else {
  10135. yRotation = cameraTarget.rotation.y;
  10136. }
  10137. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10138. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10139. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10140. var dx = targetX - this.position.x;
  10141. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10142. var dz = (targetZ) - this.position.z;
  10143. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10144. var vy = dy * this.cameraAcceleration;
  10145. var vz = dz * this.cameraAcceleration * 2;
  10146. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10147. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10148. }
  10149. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10150. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10151. }
  10152. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10153. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10154. }
  10155. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10156. this.setTarget(cameraTarget.position);
  10157. };
  10158. FollowCamera.prototype._update = function () {
  10159. _super.prototype._update.call(this);
  10160. this.follow(this.target);
  10161. };
  10162. return FollowCamera;
  10163. })(BABYLON.TargetCamera);
  10164. BABYLON.FollowCamera = FollowCamera;
  10165. })(BABYLON || (BABYLON = {}));
  10166. //# sourceMappingURL=babylon.followCamera.js.map
  10167. var __extends = this.__extends || function (d, b) {
  10168. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10169. function __() { this.constructor = d; }
  10170. __.prototype = b.prototype;
  10171. d.prototype = new __();
  10172. };
  10173. var BABYLON;
  10174. (function (BABYLON) {
  10175. // We're mainly based on the logic defined into the FreeCamera code
  10176. var TouchCamera = (function (_super) {
  10177. __extends(TouchCamera, _super);
  10178. function TouchCamera(name, position, scene) {
  10179. _super.call(this, name, position, scene);
  10180. this._offsetX = null;
  10181. this._offsetY = null;
  10182. this._pointerCount = 0;
  10183. this._pointerPressed = [];
  10184. this.angularSensibility = 200000.0;
  10185. this.moveSensibility = 500.0;
  10186. }
  10187. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10188. var _this = this;
  10189. var previousPosition;
  10190. if (this._attachedCanvas) {
  10191. return;
  10192. }
  10193. this._attachedCanvas = canvas;
  10194. if (this._onPointerDown === undefined) {
  10195. this._onPointerDown = function (evt) {
  10196. if (!noPreventDefault) {
  10197. evt.preventDefault();
  10198. }
  10199. _this._pointerPressed.push(evt.pointerId);
  10200. if (_this._pointerPressed.length !== 1) {
  10201. return;
  10202. }
  10203. previousPosition = {
  10204. x: evt.clientX,
  10205. y: evt.clientY
  10206. };
  10207. };
  10208. this._onPointerUp = function (evt) {
  10209. if (!noPreventDefault) {
  10210. evt.preventDefault();
  10211. }
  10212. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10213. if (index === -1) {
  10214. return;
  10215. }
  10216. _this._pointerPressed.splice(index, 1);
  10217. if (index != 0) {
  10218. return;
  10219. }
  10220. previousPosition = null;
  10221. _this._offsetX = null;
  10222. _this._offsetY = null;
  10223. };
  10224. this._onPointerMove = function (evt) {
  10225. if (!noPreventDefault) {
  10226. evt.preventDefault();
  10227. }
  10228. if (!previousPosition) {
  10229. return;
  10230. }
  10231. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10232. if (index != 0) {
  10233. return;
  10234. }
  10235. _this._offsetX = evt.clientX - previousPosition.x;
  10236. _this._offsetY = -(evt.clientY - previousPosition.y);
  10237. };
  10238. this._onLostFocus = function () {
  10239. _this._offsetX = null;
  10240. _this._offsetY = null;
  10241. };
  10242. }
  10243. canvas.addEventListener("pointerdown", this._onPointerDown);
  10244. canvas.addEventListener("pointerup", this._onPointerUp);
  10245. canvas.addEventListener("pointerout", this._onPointerUp);
  10246. canvas.addEventListener("pointermove", this._onPointerMove);
  10247. BABYLON.Tools.RegisterTopRootEvents([
  10248. { name: "blur", handler: this._onLostFocus }
  10249. ]);
  10250. };
  10251. TouchCamera.prototype.detachControl = function (canvas) {
  10252. if (this._attachedCanvas != canvas) {
  10253. return;
  10254. }
  10255. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10256. canvas.removeEventListener("pointerup", this._onPointerUp);
  10257. canvas.removeEventListener("pointerout", this._onPointerUp);
  10258. canvas.removeEventListener("pointermove", this._onPointerMove);
  10259. BABYLON.Tools.UnregisterTopRootEvents([
  10260. { name: "blur", handler: this._onLostFocus }
  10261. ]);
  10262. this._attachedCanvas = null;
  10263. };
  10264. TouchCamera.prototype._checkInputs = function () {
  10265. if (!this._offsetX) {
  10266. return;
  10267. }
  10268. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10269. if (this._pointerPressed.length > 1) {
  10270. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10271. }
  10272. else {
  10273. var speed = this._computeLocalCameraSpeed();
  10274. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10275. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10276. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10277. }
  10278. };
  10279. return TouchCamera;
  10280. })(BABYLON.FreeCamera);
  10281. BABYLON.TouchCamera = TouchCamera;
  10282. })(BABYLON || (BABYLON = {}));
  10283. //# sourceMappingURL=babylon.touchCamera.js.map
  10284. var __extends = this.__extends || function (d, b) {
  10285. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10286. function __() { this.constructor = d; }
  10287. __.prototype = b.prototype;
  10288. d.prototype = new __();
  10289. };
  10290. var BABYLON;
  10291. (function (BABYLON) {
  10292. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10293. var ArcRotateCamera = (function (_super) {
  10294. __extends(ArcRotateCamera, _super);
  10295. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10296. var _this = this;
  10297. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10298. this.alpha = alpha;
  10299. this.beta = beta;
  10300. this.radius = radius;
  10301. this.target = target;
  10302. this.inertialAlphaOffset = 0;
  10303. this.inertialBetaOffset = 0;
  10304. this.inertialRadiusOffset = 0;
  10305. this.lowerAlphaLimit = null;
  10306. this.upperAlphaLimit = null;
  10307. this.lowerBetaLimit = 0.01;
  10308. this.upperBetaLimit = Math.PI;
  10309. this.lowerRadiusLimit = null;
  10310. this.upperRadiusLimit = null;
  10311. this.angularSensibility = 1000.0;
  10312. this.wheelPrecision = 3.0;
  10313. this.pinchPrecision = 2.0;
  10314. this.keysUp = [38];
  10315. this.keysDown = [40];
  10316. this.keysLeft = [37];
  10317. this.keysRight = [39];
  10318. this.zoomOnFactor = 1;
  10319. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10320. this.pinchInwards = true;
  10321. this._keys = [];
  10322. this._viewMatrix = new BABYLON.Matrix();
  10323. this.checkCollisions = false;
  10324. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10325. this._collider = new BABYLON.Collider();
  10326. this._previousPosition = BABYLON.Vector3.Zero();
  10327. this._collisionVelocity = BABYLON.Vector3.Zero();
  10328. this._newPosition = BABYLON.Vector3.Zero();
  10329. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10330. if (collidedMesh === void 0) { collidedMesh = null; }
  10331. if (collisionId != null || collisionId != undefined)
  10332. newPosition.multiplyInPlace(_this._collider.radius);
  10333. if (!newPosition.equalsWithEpsilon(_this.position)) {
  10334. _this.position.copyFrom(_this._previousPosition);
  10335. _this.alpha = _this._previousAlpha;
  10336. _this.beta = _this._previousBeta;
  10337. _this.radius = _this._previousRadius;
  10338. if (_this.onCollide && collidedMesh) {
  10339. _this.onCollide(collidedMesh);
  10340. }
  10341. }
  10342. _this._collisionTriggered = false;
  10343. };
  10344. if (!this.target) {
  10345. this.target = BABYLON.Vector3.Zero();
  10346. }
  10347. this.getViewMatrix();
  10348. }
  10349. ArcRotateCamera.prototype._getTargetPosition = function () {
  10350. return this.target.position || this.target;
  10351. };
  10352. // Cache
  10353. ArcRotateCamera.prototype._initCache = function () {
  10354. _super.prototype._initCache.call(this);
  10355. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10356. this._cache.alpha = undefined;
  10357. this._cache.beta = undefined;
  10358. this._cache.radius = undefined;
  10359. this._cache.targetScreenOffset = undefined;
  10360. };
  10361. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10362. if (!ignoreParentClass) {
  10363. _super.prototype._updateCache.call(this);
  10364. }
  10365. this._cache.target.copyFrom(this._getTargetPosition());
  10366. this._cache.alpha = this.alpha;
  10367. this._cache.beta = this.beta;
  10368. this._cache.radius = this.radius;
  10369. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  10370. };
  10371. // Synchronized
  10372. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10373. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10374. return false;
  10375. 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);
  10376. };
  10377. // Methods
  10378. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  10379. var _this = this;
  10380. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10381. var previousPinchDistance = 0;
  10382. var pointers = new BABYLON.SmartCollection();
  10383. if (this._attachedElement) {
  10384. return;
  10385. }
  10386. this._attachedElement = element;
  10387. var engine = this.getEngine();
  10388. if (this._onPointerDown === undefined) {
  10389. this._onPointerDown = function (evt) {
  10390. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10391. cacheSoloPointer = pointers.item(evt.pointerId);
  10392. if (!noPreventDefault) {
  10393. evt.preventDefault();
  10394. }
  10395. };
  10396. this._onPointerUp = function (evt) {
  10397. cacheSoloPointer = null;
  10398. previousPinchDistance = 0;
  10399. pointers.remove(evt.pointerId);
  10400. if (!noPreventDefault) {
  10401. evt.preventDefault();
  10402. }
  10403. };
  10404. this._onPointerMove = function (evt) {
  10405. if (!noPreventDefault) {
  10406. evt.preventDefault();
  10407. }
  10408. switch (pointers.count) {
  10409. case 1:
  10410. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  10411. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  10412. var offsetX = evt.clientX - cacheSoloPointer.x;
  10413. var offsetY = evt.clientY - cacheSoloPointer.y;
  10414. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10415. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10416. //pointers.item(evt.pointerId).x = evt.clientX;
  10417. //pointers.item(evt.pointerId).y = evt.clientY;
  10418. cacheSoloPointer.x = evt.clientX;
  10419. cacheSoloPointer.y = evt.clientY;
  10420. break;
  10421. case 2:
  10422. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10423. pointers.item(evt.pointerId).x = evt.clientX;
  10424. pointers.item(evt.pointerId).y = evt.clientY;
  10425. var direction = _this.pinchInwards ? 1 : -1;
  10426. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10427. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10428. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10429. if (previousPinchDistance === 0) {
  10430. previousPinchDistance = pinchSquaredDistance;
  10431. return;
  10432. }
  10433. if (pinchSquaredDistance !== previousPinchDistance) {
  10434. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility * direction);
  10435. previousPinchDistance = pinchSquaredDistance;
  10436. }
  10437. break;
  10438. default:
  10439. if (pointers.item(evt.pointerId)) {
  10440. pointers.item(evt.pointerId).x = evt.clientX;
  10441. pointers.item(evt.pointerId).y = evt.clientY;
  10442. }
  10443. }
  10444. };
  10445. this._onMouseMove = function (evt) {
  10446. if (!engine.isPointerLock) {
  10447. return;
  10448. }
  10449. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10450. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10451. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10452. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10453. if (!noPreventDefault) {
  10454. evt.preventDefault();
  10455. }
  10456. };
  10457. this._wheel = function (event) {
  10458. var delta = 0;
  10459. if (event.wheelDelta) {
  10460. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10461. }
  10462. else if (event.detail) {
  10463. delta = -event.detail / _this.wheelPrecision;
  10464. }
  10465. if (delta)
  10466. _this.inertialRadiusOffset += delta;
  10467. if (event.preventDefault) {
  10468. if (!noPreventDefault) {
  10469. event.preventDefault();
  10470. }
  10471. }
  10472. };
  10473. this._onKeyDown = function (evt) {
  10474. 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) {
  10475. var index = _this._keys.indexOf(evt.keyCode);
  10476. if (index === -1) {
  10477. _this._keys.push(evt.keyCode);
  10478. }
  10479. if (evt.preventDefault) {
  10480. if (!noPreventDefault) {
  10481. evt.preventDefault();
  10482. }
  10483. }
  10484. }
  10485. };
  10486. this._onKeyUp = function (evt) {
  10487. 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) {
  10488. var index = _this._keys.indexOf(evt.keyCode);
  10489. if (index >= 0) {
  10490. _this._keys.splice(index, 1);
  10491. }
  10492. if (evt.preventDefault) {
  10493. if (!noPreventDefault) {
  10494. evt.preventDefault();
  10495. }
  10496. }
  10497. }
  10498. };
  10499. this._onLostFocus = function () {
  10500. _this._keys = [];
  10501. pointers.empty();
  10502. previousPinchDistance = 0;
  10503. cacheSoloPointer = null;
  10504. };
  10505. this._onGestureStart = function (e) {
  10506. if (window.MSGesture === undefined) {
  10507. return;
  10508. }
  10509. if (!_this._MSGestureHandler) {
  10510. _this._MSGestureHandler = new MSGesture();
  10511. _this._MSGestureHandler.target = element;
  10512. }
  10513. _this._MSGestureHandler.addPointer(e.pointerId);
  10514. };
  10515. this._onGesture = function (e) {
  10516. _this.radius *= e.scale;
  10517. if (e.preventDefault) {
  10518. if (!noPreventDefault) {
  10519. e.stopPropagation();
  10520. e.preventDefault();
  10521. }
  10522. }
  10523. };
  10524. this._reset = function () {
  10525. _this._keys = [];
  10526. _this.inertialAlphaOffset = 0;
  10527. _this.inertialBetaOffset = 0;
  10528. _this.inertialRadiusOffset = 0;
  10529. pointers.empty();
  10530. previousPinchDistance = 0;
  10531. cacheSoloPointer = null;
  10532. };
  10533. }
  10534. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  10535. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  10536. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  10537. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  10538. element.addEventListener("mousemove", this._onMouseMove, false);
  10539. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  10540. element.addEventListener("MSGestureChange", this._onGesture, false);
  10541. element.addEventListener('mousewheel', this._wheel, false);
  10542. element.addEventListener('DOMMouseScroll', this._wheel, false);
  10543. BABYLON.Tools.RegisterTopRootEvents([
  10544. { name: "keydown", handler: this._onKeyDown },
  10545. { name: "keyup", handler: this._onKeyUp },
  10546. { name: "blur", handler: this._onLostFocus }
  10547. ]);
  10548. };
  10549. ArcRotateCamera.prototype.detachControl = function (element) {
  10550. if (this._attachedElement !== element) {
  10551. return;
  10552. }
  10553. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  10554. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  10555. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  10556. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  10557. element.removeEventListener("mousemove", this._onMouseMove);
  10558. element.removeEventListener("MSPointerDown", this._onGestureStart);
  10559. element.removeEventListener("MSGestureChange", this._onGesture);
  10560. element.removeEventListener('mousewheel', this._wheel);
  10561. element.removeEventListener('DOMMouseScroll', this._wheel);
  10562. BABYLON.Tools.UnregisterTopRootEvents([
  10563. { name: "keydown", handler: this._onKeyDown },
  10564. { name: "keyup", handler: this._onKeyUp },
  10565. { name: "blur", handler: this._onLostFocus }
  10566. ]);
  10567. this._MSGestureHandler = null;
  10568. this._attachedElement = null;
  10569. if (this._reset) {
  10570. this._reset();
  10571. }
  10572. };
  10573. ArcRotateCamera.prototype._update = function () {
  10574. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  10575. if (this._collisionTriggered) {
  10576. return;
  10577. }
  10578. for (var index = 0; index < this._keys.length; index++) {
  10579. var keyCode = this._keys[index];
  10580. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10581. this.inertialAlphaOffset -= 0.01;
  10582. }
  10583. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10584. this.inertialBetaOffset -= 0.01;
  10585. }
  10586. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10587. this.inertialAlphaOffset += 0.01;
  10588. }
  10589. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10590. this.inertialBetaOffset += 0.01;
  10591. }
  10592. }
  10593. // Inertia
  10594. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  10595. this.alpha += this.inertialAlphaOffset;
  10596. this.beta += this.inertialBetaOffset;
  10597. this.radius -= this.inertialRadiusOffset;
  10598. this.inertialAlphaOffset *= this.inertia;
  10599. this.inertialBetaOffset *= this.inertia;
  10600. this.inertialRadiusOffset *= this.inertia;
  10601. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  10602. this.inertialAlphaOffset = 0;
  10603. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  10604. this.inertialBetaOffset = 0;
  10605. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  10606. this.inertialRadiusOffset = 0;
  10607. }
  10608. // Limits
  10609. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  10610. this.alpha = this.lowerAlphaLimit;
  10611. }
  10612. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  10613. this.alpha = this.upperAlphaLimit;
  10614. }
  10615. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  10616. this.beta = this.lowerBetaLimit;
  10617. }
  10618. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  10619. this.beta = this.upperBetaLimit;
  10620. }
  10621. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  10622. this.radius = this.lowerRadiusLimit;
  10623. }
  10624. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  10625. this.radius = this.upperRadiusLimit;
  10626. }
  10627. };
  10628. ArcRotateCamera.prototype.setPosition = function (position) {
  10629. var radiusv3 = position.subtract(this._getTargetPosition());
  10630. this.radius = radiusv3.length();
  10631. // Alpha
  10632. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  10633. if (radiusv3.z < 0) {
  10634. this.alpha = 2 * Math.PI - this.alpha;
  10635. }
  10636. // Beta
  10637. this.beta = Math.acos(radiusv3.y / this.radius);
  10638. };
  10639. ArcRotateCamera.prototype._getViewMatrix = function () {
  10640. // Compute
  10641. var cosa = Math.cos(this.alpha);
  10642. var sina = Math.sin(this.alpha);
  10643. var cosb = Math.cos(this.beta);
  10644. var sinb = Math.sin(this.beta);
  10645. var target = this._getTargetPosition();
  10646. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  10647. if (this.checkCollisions) {
  10648. this._collider.radius = this.collisionRadius;
  10649. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  10650. this._collisionTriggered = true;
  10651. this.getScene().collisionCoordinator.getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10652. }
  10653. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  10654. this._previousAlpha = this.alpha;
  10655. this._previousBeta = this.beta;
  10656. this._previousRadius = this.radius;
  10657. this._previousPosition.copyFrom(this.position);
  10658. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  10659. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  10660. return this._viewMatrix;
  10661. };
  10662. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  10663. meshes = meshes || this.getScene().meshes;
  10664. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  10665. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  10666. this.radius = distance * this.zoomOnFactor;
  10667. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  10668. };
  10669. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  10670. var meshesOrMinMaxVector;
  10671. var distance;
  10672. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  10673. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  10674. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  10675. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  10676. }
  10677. else {
  10678. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  10679. distance = meshesOrMinMaxVectorAndDistance.distance;
  10680. }
  10681. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  10682. this.maxZ = distance * 2;
  10683. };
  10684. return ArcRotateCamera;
  10685. })(BABYLON.Camera);
  10686. BABYLON.ArcRotateCamera = ArcRotateCamera;
  10687. })(BABYLON || (BABYLON = {}));
  10688. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  10689. var __extends = this.__extends || function (d, b) {
  10690. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10691. function __() { this.constructor = d; }
  10692. __.prototype = b.prototype;
  10693. d.prototype = new __();
  10694. };
  10695. var BABYLON;
  10696. (function (BABYLON) {
  10697. // We're mainly based on the logic defined into the FreeCamera code
  10698. var DeviceOrientationCamera = (function (_super) {
  10699. __extends(DeviceOrientationCamera, _super);
  10700. function DeviceOrientationCamera(name, position, scene) {
  10701. var _this = this;
  10702. _super.call(this, name, position, scene);
  10703. this._offsetX = null;
  10704. this._offsetY = null;
  10705. this._orientationGamma = 0;
  10706. this._orientationBeta = 0;
  10707. this._initialOrientationGamma = 0;
  10708. this._initialOrientationBeta = 0;
  10709. this.angularSensibility = 10000.0;
  10710. this.moveSensibility = 50.0;
  10711. window.addEventListener("resize", function () {
  10712. _this._initialOrientationGamma = null;
  10713. }, false);
  10714. }
  10715. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10716. var _this = this;
  10717. if (this._attachedCanvas) {
  10718. return;
  10719. }
  10720. this._attachedCanvas = canvas;
  10721. if (!this._orientationChanged) {
  10722. this._orientationChanged = function (evt) {
  10723. if (!_this._initialOrientationGamma) {
  10724. _this._initialOrientationGamma = evt.gamma;
  10725. _this._initialOrientationBeta = evt.beta;
  10726. }
  10727. _this._orientationGamma = evt.gamma;
  10728. _this._orientationBeta = evt.beta;
  10729. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  10730. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  10731. };
  10732. }
  10733. window.addEventListener("deviceorientation", this._orientationChanged);
  10734. };
  10735. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  10736. if (this._attachedCanvas != canvas) {
  10737. return;
  10738. }
  10739. window.removeEventListener("deviceorientation", this._orientationChanged);
  10740. this._attachedCanvas = null;
  10741. this._orientationGamma = 0;
  10742. this._orientationBeta = 0;
  10743. this._initialOrientationGamma = 0;
  10744. this._initialOrientationBeta = 0;
  10745. };
  10746. DeviceOrientationCamera.prototype._checkInputs = function () {
  10747. if (!this._offsetX) {
  10748. return;
  10749. }
  10750. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  10751. var speed = this._computeLocalCameraSpeed();
  10752. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10753. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10754. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10755. };
  10756. return DeviceOrientationCamera;
  10757. })(BABYLON.FreeCamera);
  10758. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  10759. })(BABYLON || (BABYLON = {}));
  10760. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  10761. var BABYLON;
  10762. (function (BABYLON) {
  10763. var RenderingManager = (function () {
  10764. function RenderingManager(scene) {
  10765. this._renderingGroups = new Array();
  10766. this._scene = scene;
  10767. }
  10768. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  10769. if (this._scene._activeParticleSystems.length === 0) {
  10770. return;
  10771. }
  10772. // Particles
  10773. var beforeParticlesDate = BABYLON.Tools.Now;
  10774. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  10775. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  10776. if (particleSystem.renderingGroupId !== index) {
  10777. continue;
  10778. }
  10779. this._clearDepthBuffer();
  10780. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  10781. this._scene._activeParticles += particleSystem.render();
  10782. }
  10783. }
  10784. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  10785. };
  10786. RenderingManager.prototype._renderSprites = function (index) {
  10787. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  10788. return;
  10789. }
  10790. // Sprites
  10791. var beforeSpritessDate = BABYLON.Tools.Now;
  10792. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  10793. var spriteManager = this._scene.spriteManagers[id];
  10794. if (spriteManager.renderingGroupId === index) {
  10795. this._clearDepthBuffer();
  10796. spriteManager.render();
  10797. }
  10798. }
  10799. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  10800. };
  10801. RenderingManager.prototype._clearDepthBuffer = function () {
  10802. if (this._depthBufferAlreadyCleaned) {
  10803. return;
  10804. }
  10805. this._scene.getEngine().clear(0, false, true);
  10806. this._depthBufferAlreadyCleaned = true;
  10807. };
  10808. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  10809. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  10810. this._depthBufferAlreadyCleaned = false;
  10811. var renderingGroup = this._renderingGroups[index];
  10812. var needToStepBack = false;
  10813. if (renderingGroup) {
  10814. this._clearDepthBuffer();
  10815. if (!renderingGroup.render(customRenderFunction)) {
  10816. this._renderingGroups.splice(index, 1);
  10817. needToStepBack = true;
  10818. }
  10819. }
  10820. if (renderSprites) {
  10821. this._renderSprites(index);
  10822. }
  10823. if (renderParticles) {
  10824. this._renderParticles(index, activeMeshes);
  10825. }
  10826. if (needToStepBack) {
  10827. index--;
  10828. }
  10829. }
  10830. };
  10831. RenderingManager.prototype.reset = function () {
  10832. for (var index in this._renderingGroups) {
  10833. var renderingGroup = this._renderingGroups[index];
  10834. renderingGroup.prepare();
  10835. }
  10836. };
  10837. RenderingManager.prototype.dispatch = function (subMesh) {
  10838. var mesh = subMesh.getMesh();
  10839. var renderingGroupId = mesh.renderingGroupId || 0;
  10840. if (!this._renderingGroups[renderingGroupId]) {
  10841. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  10842. }
  10843. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  10844. };
  10845. RenderingManager.MAX_RENDERINGGROUPS = 4;
  10846. return RenderingManager;
  10847. })();
  10848. BABYLON.RenderingManager = RenderingManager;
  10849. })(BABYLON || (BABYLON = {}));
  10850. //# sourceMappingURL=babylon.renderingManager.js.map
  10851. var BABYLON;
  10852. (function (BABYLON) {
  10853. var RenderingGroup = (function () {
  10854. function RenderingGroup(index, scene) {
  10855. this.index = index;
  10856. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  10857. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  10858. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  10859. this._scene = scene;
  10860. }
  10861. RenderingGroup.prototype.render = function (customRenderFunction) {
  10862. if (customRenderFunction) {
  10863. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  10864. return true;
  10865. }
  10866. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  10867. return false;
  10868. }
  10869. var engine = this._scene.getEngine();
  10870. // Opaque
  10871. var subIndex;
  10872. var submesh;
  10873. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  10874. submesh = this._opaqueSubMeshes.data[subIndex];
  10875. submesh.render();
  10876. }
  10877. // Alpha test
  10878. engine.setAlphaTesting(true);
  10879. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  10880. submesh = this._alphaTestSubMeshes.data[subIndex];
  10881. submesh.render();
  10882. }
  10883. engine.setAlphaTesting(false);
  10884. // Transparent
  10885. if (this._transparentSubMeshes.length) {
  10886. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  10887. submesh = this._transparentSubMeshes.data[subIndex];
  10888. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  10889. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  10890. }
  10891. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  10892. sortedArray.sort(function (a, b) {
  10893. // Alpha index first
  10894. if (a._alphaIndex > b._alphaIndex) {
  10895. return 1;
  10896. }
  10897. if (a._alphaIndex < b._alphaIndex) {
  10898. return -1;
  10899. }
  10900. // Then distance to camera
  10901. if (a._distanceToCamera < b._distanceToCamera) {
  10902. return 1;
  10903. }
  10904. if (a._distanceToCamera > b._distanceToCamera) {
  10905. return -1;
  10906. }
  10907. return 0;
  10908. });
  10909. // Rendering
  10910. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10911. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  10912. submesh = sortedArray[subIndex];
  10913. submesh.render();
  10914. }
  10915. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10916. }
  10917. return true;
  10918. };
  10919. RenderingGroup.prototype.prepare = function () {
  10920. this._opaqueSubMeshes.reset();
  10921. this._transparentSubMeshes.reset();
  10922. this._alphaTestSubMeshes.reset();
  10923. };
  10924. RenderingGroup.prototype.dispatch = function (subMesh) {
  10925. var material = subMesh.getMaterial();
  10926. var mesh = subMesh.getMesh();
  10927. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  10928. this._transparentSubMeshes.push(subMesh);
  10929. }
  10930. else if (material.needAlphaTesting()) {
  10931. this._alphaTestSubMeshes.push(subMesh);
  10932. }
  10933. else {
  10934. this._opaqueSubMeshes.push(subMesh); // Opaque
  10935. }
  10936. };
  10937. return RenderingGroup;
  10938. })();
  10939. BABYLON.RenderingGroup = RenderingGroup;
  10940. })(BABYLON || (BABYLON = {}));
  10941. //# sourceMappingURL=babylon.renderingGroup.js.map
  10942. var BABYLON;
  10943. (function (BABYLON) {
  10944. /**
  10945. * Represents a scene to be rendered by the engine.
  10946. * @see http://doc.babylonjs.com/page.php?p=21911
  10947. */
  10948. var Scene = (function () {
  10949. /**
  10950. * @constructor
  10951. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  10952. */
  10953. function Scene(engine) {
  10954. // Members
  10955. this.autoClear = true;
  10956. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  10957. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  10958. this.forceWireframe = false;
  10959. this.forcePointsCloud = false;
  10960. this.forceShowBoundingBoxes = false;
  10961. this.animationsEnabled = true;
  10962. 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
  10963. // Fog
  10964. /**
  10965. * is fog enabled on this scene.
  10966. * @type {boolean}
  10967. */
  10968. this.fogEnabled = true;
  10969. this.fogMode = Scene.FOGMODE_NONE;
  10970. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  10971. this.fogDensity = 0.1;
  10972. this.fogStart = 0;
  10973. this.fogEnd = 1000.0;
  10974. // Lights
  10975. /**
  10976. * is shadow enabled on this scene.
  10977. * @type {boolean}
  10978. */
  10979. this.shadowsEnabled = true;
  10980. /**
  10981. * is light enabled on this scene.
  10982. * @type {boolean}
  10983. */
  10984. this.lightsEnabled = true;
  10985. /**
  10986. * All of the lights added to this scene.
  10987. * @see BABYLON.Light
  10988. * @type {BABYLON.Light[]}
  10989. */
  10990. this.lights = new Array();
  10991. // Cameras
  10992. /**
  10993. * All of the cameras added to this scene.
  10994. * @see BABYLON.Camera
  10995. * @type {BABYLON.Camera[]}
  10996. */
  10997. this.cameras = new Array();
  10998. this.activeCameras = new Array();
  10999. // Meshes
  11000. /**
  11001. * All of the (abstract) meshes added to this scene.
  11002. * @see BABYLON.AbstractMesh
  11003. * @type {BABYLON.AbstractMesh[]}
  11004. */
  11005. this.meshes = new Array();
  11006. // Geometries
  11007. this._geometries = new Array();
  11008. this.materials = new Array();
  11009. this.multiMaterials = new Array();
  11010. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11011. // Textures
  11012. this.texturesEnabled = true;
  11013. this.textures = new Array();
  11014. // Particles
  11015. this.particlesEnabled = true;
  11016. this.particleSystems = new Array();
  11017. // Sprites
  11018. this.spritesEnabled = true;
  11019. this.spriteManagers = new Array();
  11020. // Layers
  11021. this.layers = new Array();
  11022. // Skeletons
  11023. this.skeletonsEnabled = true;
  11024. this.skeletons = new Array();
  11025. // Lens flares
  11026. this.lensFlaresEnabled = true;
  11027. this.lensFlareSystems = new Array();
  11028. // Collisions
  11029. this.collisionsEnabled = true;
  11030. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  11031. // Postprocesses
  11032. this.postProcessesEnabled = true;
  11033. // Customs render targets
  11034. this.renderTargetsEnabled = true;
  11035. this.dumpNextRenderTargets = false;
  11036. this.customRenderTargets = new Array();
  11037. // Imported meshes
  11038. this.importedMeshesFiles = new Array();
  11039. this._actionManagers = new Array();
  11040. this._meshesForIntersections = new BABYLON.SmartArray(256);
  11041. // Procedural textures
  11042. this.proceduralTexturesEnabled = true;
  11043. this._proceduralTextures = new Array();
  11044. this.soundTracks = new Array();
  11045. this._audioEnabled = true;
  11046. this._headphone = false;
  11047. this._totalVertices = 0;
  11048. this._activeIndices = 0;
  11049. this._activeParticles = 0;
  11050. this._lastFrameDuration = 0;
  11051. this._evaluateActiveMeshesDuration = 0;
  11052. this._renderTargetsDuration = 0;
  11053. this._particlesDuration = 0;
  11054. this._renderDuration = 0;
  11055. this._spritesDuration = 0;
  11056. this._animationRatio = 0;
  11057. this._renderId = 0;
  11058. this._executeWhenReadyTimeoutId = -1;
  11059. this._toBeDisposed = new BABYLON.SmartArray(256);
  11060. this._onReadyCallbacks = new Array();
  11061. this._pendingData = []; //ANY
  11062. this._onBeforeRenderCallbacks = new Array();
  11063. this._onAfterRenderCallbacks = new Array();
  11064. this._activeMeshes = new BABYLON.SmartArray(256);
  11065. this._processedMaterials = new BABYLON.SmartArray(256);
  11066. this._renderTargets = new BABYLON.SmartArray(256);
  11067. this._activeParticleSystems = new BABYLON.SmartArray(256);
  11068. this._activeSkeletons = new BABYLON.SmartArray(32);
  11069. this._activeBones = 0;
  11070. this._activeAnimatables = new Array();
  11071. this._transformMatrix = BABYLON.Matrix.Zero();
  11072. this._uniqueIdCounter = 0;
  11073. this._engine = engine;
  11074. engine.scenes.push(this);
  11075. this._renderingManager = new BABYLON.RenderingManager(this);
  11076. this.postProcessManager = new BABYLON.PostProcessManager(this);
  11077. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  11078. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  11079. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  11080. this.attachControl();
  11081. this._debugLayer = new BABYLON.DebugLayer(this);
  11082. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  11083. //simplification queue
  11084. this.simplificationQueue = new BABYLON.SimplificationQueue();
  11085. //collision coordinator initialization. For now legacy per default.
  11086. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  11087. }
  11088. Object.defineProperty(Scene, "FOGMODE_NONE", {
  11089. get: function () {
  11090. return Scene._FOGMODE_NONE;
  11091. },
  11092. enumerable: true,
  11093. configurable: true
  11094. });
  11095. Object.defineProperty(Scene, "FOGMODE_EXP", {
  11096. get: function () {
  11097. return Scene._FOGMODE_EXP;
  11098. },
  11099. enumerable: true,
  11100. configurable: true
  11101. });
  11102. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  11103. get: function () {
  11104. return Scene._FOGMODE_EXP2;
  11105. },
  11106. enumerable: true,
  11107. configurable: true
  11108. });
  11109. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  11110. get: function () {
  11111. return Scene._FOGMODE_LINEAR;
  11112. },
  11113. enumerable: true,
  11114. configurable: true
  11115. });
  11116. Object.defineProperty(Scene.prototype, "debugLayer", {
  11117. // Properties
  11118. get: function () {
  11119. return this._debugLayer;
  11120. },
  11121. enumerable: true,
  11122. configurable: true
  11123. });
  11124. Object.defineProperty(Scene.prototype, "workerCollisions", {
  11125. get: function () {
  11126. return this._workerCollisions;
  11127. },
  11128. set: function (enabled) {
  11129. this._workerCollisions = enabled;
  11130. if (this.collisionCoordinator) {
  11131. this.collisionCoordinator.destroy();
  11132. }
  11133. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  11134. this.collisionCoordinator.init(this);
  11135. },
  11136. enumerable: true,
  11137. configurable: true
  11138. });
  11139. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  11140. /**
  11141. * The mesh that is currently under the pointer.
  11142. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  11143. */
  11144. get: function () {
  11145. return this._meshUnderPointer;
  11146. },
  11147. enumerable: true,
  11148. configurable: true
  11149. });
  11150. Object.defineProperty(Scene.prototype, "pointerX", {
  11151. /**
  11152. * Current on-screen X position of the pointer
  11153. * @return {number} X position of the pointer
  11154. */
  11155. get: function () {
  11156. return this._pointerX;
  11157. },
  11158. enumerable: true,
  11159. configurable: true
  11160. });
  11161. Object.defineProperty(Scene.prototype, "pointerY", {
  11162. /**
  11163. * Current on-screen Y position of the pointer
  11164. * @return {number} Y position of the pointer
  11165. */
  11166. get: function () {
  11167. return this._pointerY;
  11168. },
  11169. enumerable: true,
  11170. configurable: true
  11171. });
  11172. Scene.prototype.getCachedMaterial = function () {
  11173. return this._cachedMaterial;
  11174. };
  11175. Scene.prototype.getBoundingBoxRenderer = function () {
  11176. return this._boundingBoxRenderer;
  11177. };
  11178. Scene.prototype.getOutlineRenderer = function () {
  11179. return this._outlineRenderer;
  11180. };
  11181. Scene.prototype.getEngine = function () {
  11182. return this._engine;
  11183. };
  11184. Scene.prototype.getTotalVertices = function () {
  11185. return this._totalVertices;
  11186. };
  11187. Scene.prototype.getActiveIndices = function () {
  11188. return this._activeIndices;
  11189. };
  11190. Scene.prototype.getActiveParticles = function () {
  11191. return this._activeParticles;
  11192. };
  11193. Scene.prototype.getActiveBones = function () {
  11194. return this._activeBones;
  11195. };
  11196. // Stats
  11197. Scene.prototype.getLastFrameDuration = function () {
  11198. return this._lastFrameDuration;
  11199. };
  11200. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  11201. return this._evaluateActiveMeshesDuration;
  11202. };
  11203. Scene.prototype.getActiveMeshes = function () {
  11204. return this._activeMeshes;
  11205. };
  11206. Scene.prototype.getRenderTargetsDuration = function () {
  11207. return this._renderTargetsDuration;
  11208. };
  11209. Scene.prototype.getRenderDuration = function () {
  11210. return this._renderDuration;
  11211. };
  11212. Scene.prototype.getParticlesDuration = function () {
  11213. return this._particlesDuration;
  11214. };
  11215. Scene.prototype.getSpritesDuration = function () {
  11216. return this._spritesDuration;
  11217. };
  11218. Scene.prototype.getAnimationRatio = function () {
  11219. return this._animationRatio;
  11220. };
  11221. Scene.prototype.getRenderId = function () {
  11222. return this._renderId;
  11223. };
  11224. Scene.prototype.incrementRenderId = function () {
  11225. this._renderId++;
  11226. };
  11227. Scene.prototype._updatePointerPosition = function (evt) {
  11228. var canvasRect = this._engine.getRenderingCanvasClientRect();
  11229. this._pointerX = evt.clientX - canvasRect.left;
  11230. this._pointerY = evt.clientY - canvasRect.top;
  11231. if (this.cameraToUseForPointers) {
  11232. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  11233. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  11234. }
  11235. };
  11236. // Pointers handling
  11237. Scene.prototype.attachControl = function () {
  11238. var _this = this;
  11239. this._onPointerMove = function (evt) {
  11240. var canvas = _this._engine.getRenderingCanvas();
  11241. _this._updatePointerPosition(evt);
  11242. 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);
  11243. if (pickResult.hit) {
  11244. _this._meshUnderPointer = pickResult.pickedMesh;
  11245. _this.setPointerOverMesh(pickResult.pickedMesh);
  11246. canvas.style.cursor = "pointer";
  11247. }
  11248. else {
  11249. _this.setPointerOverMesh(null);
  11250. canvas.style.cursor = "";
  11251. _this._meshUnderPointer = null;
  11252. }
  11253. };
  11254. this._onPointerDown = function (evt) {
  11255. var predicate = null;
  11256. if (!_this.onPointerDown) {
  11257. predicate = function (mesh) {
  11258. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  11259. };
  11260. }
  11261. _this._updatePointerPosition(evt);
  11262. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11263. if (pickResult.hit) {
  11264. if (pickResult.pickedMesh.actionManager) {
  11265. switch (evt.button) {
  11266. case 0:
  11267. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11268. break;
  11269. case 1:
  11270. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11271. break;
  11272. case 2:
  11273. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11274. break;
  11275. }
  11276. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11277. }
  11278. }
  11279. if (_this.onPointerDown) {
  11280. _this.onPointerDown(evt, pickResult);
  11281. }
  11282. };
  11283. this._onPointerUp = function (evt) {
  11284. var predicate = null;
  11285. if (!_this.onPointerUp) {
  11286. predicate = function (mesh) {
  11287. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  11288. };
  11289. }
  11290. _this._updatePointerPosition(evt);
  11291. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11292. if (pickResult.hit) {
  11293. if (pickResult.pickedMesh.actionManager) {
  11294. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11295. }
  11296. }
  11297. if (_this.onPointerUp) {
  11298. _this.onPointerUp(evt, pickResult);
  11299. }
  11300. };
  11301. this._onKeyDown = function (evt) {
  11302. if (_this.actionManager) {
  11303. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11304. }
  11305. };
  11306. this._onKeyUp = function (evt) {
  11307. if (_this.actionManager) {
  11308. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11309. }
  11310. };
  11311. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11312. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11313. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11314. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11315. BABYLON.Tools.RegisterTopRootEvents([
  11316. { name: "keydown", handler: this._onKeyDown },
  11317. { name: "keyup", handler: this._onKeyUp }
  11318. ]);
  11319. };
  11320. Scene.prototype.detachControl = function () {
  11321. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11322. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  11323. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  11324. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  11325. BABYLON.Tools.UnregisterTopRootEvents([
  11326. { name: "keydown", handler: this._onKeyDown },
  11327. { name: "keyup", handler: this._onKeyUp }
  11328. ]);
  11329. };
  11330. // Ready
  11331. Scene.prototype.isReady = function () {
  11332. if (this._pendingData.length > 0) {
  11333. return false;
  11334. }
  11335. for (var index = 0; index < this._geometries.length; index++) {
  11336. var geometry = this._geometries[index];
  11337. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11338. return false;
  11339. }
  11340. }
  11341. for (index = 0; index < this.meshes.length; index++) {
  11342. var mesh = this.meshes[index];
  11343. if (!mesh.isReady()) {
  11344. return false;
  11345. }
  11346. var mat = mesh.material;
  11347. if (mat) {
  11348. if (!mat.isReady(mesh)) {
  11349. return false;
  11350. }
  11351. }
  11352. }
  11353. return true;
  11354. };
  11355. Scene.prototype.resetCachedMaterial = function () {
  11356. this._cachedMaterial = null;
  11357. };
  11358. Scene.prototype.registerBeforeRender = function (func) {
  11359. this._onBeforeRenderCallbacks.push(func);
  11360. };
  11361. Scene.prototype.unregisterBeforeRender = function (func) {
  11362. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11363. if (index > -1) {
  11364. this._onBeforeRenderCallbacks.splice(index, 1);
  11365. }
  11366. };
  11367. Scene.prototype.registerAfterRender = function (func) {
  11368. this._onAfterRenderCallbacks.push(func);
  11369. };
  11370. Scene.prototype.unregisterAfterRender = function (func) {
  11371. var index = this._onAfterRenderCallbacks.indexOf(func);
  11372. if (index > -1) {
  11373. this._onAfterRenderCallbacks.splice(index, 1);
  11374. }
  11375. };
  11376. Scene.prototype._addPendingData = function (data) {
  11377. this._pendingData.push(data);
  11378. };
  11379. Scene.prototype._removePendingData = function (data) {
  11380. var index = this._pendingData.indexOf(data);
  11381. if (index !== -1) {
  11382. this._pendingData.splice(index, 1);
  11383. }
  11384. };
  11385. Scene.prototype.getWaitingItemsCount = function () {
  11386. return this._pendingData.length;
  11387. };
  11388. /**
  11389. * Registers a function to be executed when the scene is ready.
  11390. * @param {Function} func - the function to be executed.
  11391. */
  11392. Scene.prototype.executeWhenReady = function (func) {
  11393. var _this = this;
  11394. this._onReadyCallbacks.push(func);
  11395. if (this._executeWhenReadyTimeoutId !== -1) {
  11396. return;
  11397. }
  11398. this._executeWhenReadyTimeoutId = setTimeout(function () {
  11399. _this._checkIsReady();
  11400. }, 150);
  11401. };
  11402. Scene.prototype._checkIsReady = function () {
  11403. var _this = this;
  11404. if (this.isReady()) {
  11405. this._onReadyCallbacks.forEach(function (func) {
  11406. func();
  11407. });
  11408. this._onReadyCallbacks = [];
  11409. this._executeWhenReadyTimeoutId = -1;
  11410. return;
  11411. }
  11412. this._executeWhenReadyTimeoutId = setTimeout(function () {
  11413. _this._checkIsReady();
  11414. }, 150);
  11415. };
  11416. // Animations
  11417. /**
  11418. * Will start the animation sequence of a given target
  11419. * @param target - the target
  11420. * @param {number} from - from which frame should animation start
  11421. * @param {number} to - till which frame should animation run.
  11422. * @param {boolean} [loop] - should the animation loop
  11423. * @param {number} [speedRatio] - the speed in which to run the animation
  11424. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  11425. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  11426. * @return {BABYLON.Animatable} the animatable object created for this animation
  11427. * @see BABYLON.Animatable
  11428. * @see http://doc.babylonjs.com/page.php?p=22081
  11429. */
  11430. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  11431. if (speedRatio === undefined) {
  11432. speedRatio = 1.0;
  11433. }
  11434. this.stopAnimation(target);
  11435. if (!animatable) {
  11436. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  11437. }
  11438. // Local animations
  11439. if (target.animations) {
  11440. animatable.appendAnimations(target, target.animations);
  11441. }
  11442. // Children animations
  11443. if (target.getAnimatables) {
  11444. var animatables = target.getAnimatables();
  11445. for (var index = 0; index < animatables.length; index++) {
  11446. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  11447. }
  11448. }
  11449. return animatable;
  11450. };
  11451. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  11452. if (speedRatio === undefined) {
  11453. speedRatio = 1.0;
  11454. }
  11455. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  11456. return animatable;
  11457. };
  11458. Scene.prototype.getAnimatableByTarget = function (target) {
  11459. for (var index = 0; index < this._activeAnimatables.length; index++) {
  11460. if (this._activeAnimatables[index].target === target) {
  11461. return this._activeAnimatables[index];
  11462. }
  11463. }
  11464. return null;
  11465. };
  11466. /**
  11467. * Will stop the animation of the given target
  11468. * @param target - the target
  11469. * @see beginAnimation
  11470. */
  11471. Scene.prototype.stopAnimation = function (target) {
  11472. var animatable = this.getAnimatableByTarget(target);
  11473. if (animatable) {
  11474. animatable.stop();
  11475. }
  11476. };
  11477. Scene.prototype._animate = function () {
  11478. if (!this.animationsEnabled) {
  11479. return;
  11480. }
  11481. if (!this._animationStartDate) {
  11482. this._animationStartDate = BABYLON.Tools.Now;
  11483. }
  11484. // Getting time
  11485. var now = BABYLON.Tools.Now;
  11486. var delay = now - this._animationStartDate;
  11487. for (var index = 0; index < this._activeAnimatables.length; index++) {
  11488. this._activeAnimatables[index]._animate(delay);
  11489. }
  11490. };
  11491. // Matrix
  11492. Scene.prototype.getViewMatrix = function () {
  11493. return this._viewMatrix;
  11494. };
  11495. Scene.prototype.getProjectionMatrix = function () {
  11496. return this._projectionMatrix;
  11497. };
  11498. Scene.prototype.getTransformMatrix = function () {
  11499. return this._transformMatrix;
  11500. };
  11501. Scene.prototype.setTransformMatrix = function (view, projection) {
  11502. this._viewMatrix = view;
  11503. this._projectionMatrix = projection;
  11504. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11505. };
  11506. // Methods
  11507. Scene.prototype.addMesh = function (newMesh) {
  11508. newMesh.uniqueId = this._uniqueIdCounter++;
  11509. var position = this.meshes.push(newMesh);
  11510. //notify the collision coordinator
  11511. this.collisionCoordinator.onMeshAdded(newMesh);
  11512. if (this.onNewMeshAdded) {
  11513. this.onNewMeshAdded(newMesh, position, this);
  11514. }
  11515. };
  11516. Scene.prototype.removeMesh = function (toRemove) {
  11517. var index = this.meshes.indexOf(toRemove);
  11518. if (index !== -1) {
  11519. // Remove from the scene if mesh found
  11520. this.meshes.splice(index, 1);
  11521. }
  11522. //notify the collision coordinator
  11523. this.collisionCoordinator.onMeshRemoved(toRemove);
  11524. if (this.onMeshRemoved) {
  11525. this.onMeshRemoved(toRemove);
  11526. }
  11527. return index;
  11528. };
  11529. Scene.prototype.removeLight = function (toRemove) {
  11530. var index = this.lights.indexOf(toRemove);
  11531. if (index !== -1) {
  11532. // Remove from the scene if mesh found
  11533. this.lights.splice(index, 1);
  11534. }
  11535. if (this.onLightRemoved) {
  11536. this.onLightRemoved(toRemove);
  11537. }
  11538. return index;
  11539. };
  11540. Scene.prototype.removeCamera = function (toRemove) {
  11541. var index = this.cameras.indexOf(toRemove);
  11542. if (index !== -1) {
  11543. // Remove from the scene if mesh found
  11544. this.cameras.splice(index, 1);
  11545. }
  11546. // Remove from activeCameras
  11547. var index2 = this.activeCameras.indexOf(toRemove);
  11548. if (index2 !== -1) {
  11549. // Remove from the scene if mesh found
  11550. this.activeCameras.splice(index2, 1);
  11551. }
  11552. // Reset the activeCamera
  11553. if (this.activeCamera === toRemove) {
  11554. if (this.cameras.length > 0) {
  11555. this.activeCamera = this.cameras[0];
  11556. }
  11557. else {
  11558. this.activeCamera = null;
  11559. }
  11560. }
  11561. if (this.onCameraRemoved) {
  11562. this.onCameraRemoved(toRemove);
  11563. }
  11564. return index;
  11565. };
  11566. Scene.prototype.addLight = function (newLight) {
  11567. newLight.uniqueId = this._uniqueIdCounter++;
  11568. var position = this.lights.push(newLight);
  11569. if (this.onNewLightAdded) {
  11570. this.onNewLightAdded(newLight, position, this);
  11571. }
  11572. };
  11573. Scene.prototype.addCamera = function (newCamera) {
  11574. newCamera.uniqueId = this._uniqueIdCounter++;
  11575. var position = this.cameras.push(newCamera);
  11576. if (this.onNewCameraAdded) {
  11577. this.onNewCameraAdded(newCamera, position, this);
  11578. }
  11579. };
  11580. /**
  11581. * sets the active camera of the scene using its ID
  11582. * @param {string} id - the camera's ID
  11583. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  11584. * @see activeCamera
  11585. */
  11586. Scene.prototype.setActiveCameraByID = function (id) {
  11587. var camera = this.getCameraByID(id);
  11588. if (camera) {
  11589. this.activeCamera = camera;
  11590. return camera;
  11591. }
  11592. return null;
  11593. };
  11594. /**
  11595. * sets the active camera of the scene using its name
  11596. * @param {string} name - the camera's name
  11597. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  11598. * @see activeCamera
  11599. */
  11600. Scene.prototype.setActiveCameraByName = function (name) {
  11601. var camera = this.getCameraByName(name);
  11602. if (camera) {
  11603. this.activeCamera = camera;
  11604. return camera;
  11605. }
  11606. return null;
  11607. };
  11608. /**
  11609. * get a material using its id
  11610. * @param {string} the material's ID
  11611. * @return {BABYLON.Material|null} the material or null if none found.
  11612. */
  11613. Scene.prototype.getMaterialByID = function (id) {
  11614. for (var index = 0; index < this.materials.length; index++) {
  11615. if (this.materials[index].id === id) {
  11616. return this.materials[index];
  11617. }
  11618. }
  11619. return null;
  11620. };
  11621. /**
  11622. * get a material using its name
  11623. * @param {string} the material's name
  11624. * @return {BABYLON.Material|null} the material or null if none found.
  11625. */
  11626. Scene.prototype.getMaterialByName = function (name) {
  11627. for (var index = 0; index < this.materials.length; index++) {
  11628. if (this.materials[index].name === name) {
  11629. return this.materials[index];
  11630. }
  11631. }
  11632. return null;
  11633. };
  11634. Scene.prototype.getCameraByID = function (id) {
  11635. for (var index = 0; index < this.cameras.length; index++) {
  11636. if (this.cameras[index].id === id) {
  11637. return this.cameras[index];
  11638. }
  11639. }
  11640. return null;
  11641. };
  11642. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  11643. for (var index = 0; index < this.cameras.length; index++) {
  11644. if (this.cameras[index].uniqueId === uniqueId) {
  11645. return this.cameras[index];
  11646. }
  11647. }
  11648. return null;
  11649. };
  11650. /**
  11651. * get a camera using its name
  11652. * @param {string} the camera's name
  11653. * @return {BABYLON.Camera|null} the camera or null if none found.
  11654. */
  11655. Scene.prototype.getCameraByName = function (name) {
  11656. for (var index = 0; index < this.cameras.length; index++) {
  11657. if (this.cameras[index].name === name) {
  11658. return this.cameras[index];
  11659. }
  11660. }
  11661. return null;
  11662. };
  11663. /**
  11664. * get a light node using its name
  11665. * @param {string} the light's name
  11666. * @return {BABYLON.Light|null} the light or null if none found.
  11667. */
  11668. Scene.prototype.getLightByName = function (name) {
  11669. for (var index = 0; index < this.lights.length; index++) {
  11670. if (this.lights[index].name === name) {
  11671. return this.lights[index];
  11672. }
  11673. }
  11674. return null;
  11675. };
  11676. /**
  11677. * get a light node using its ID
  11678. * @param {string} the light's id
  11679. * @return {BABYLON.Light|null} the light or null if none found.
  11680. */
  11681. Scene.prototype.getLightByID = function (id) {
  11682. for (var index = 0; index < this.lights.length; index++) {
  11683. if (this.lights[index].id === id) {
  11684. return this.lights[index];
  11685. }
  11686. }
  11687. return null;
  11688. };
  11689. /**
  11690. * get a light node using its scene-generated unique ID
  11691. * @param {number} the light's unique id
  11692. * @return {BABYLON.Light|null} the light or null if none found.
  11693. */
  11694. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  11695. for (var index = 0; index < this.lights.length; index++) {
  11696. if (this.lights[index].uniqueId === uniqueId) {
  11697. return this.lights[index];
  11698. }
  11699. }
  11700. return null;
  11701. };
  11702. /**
  11703. * get a geometry using its ID
  11704. * @param {string} the geometry's id
  11705. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  11706. */
  11707. Scene.prototype.getGeometryByID = function (id) {
  11708. for (var index = 0; index < this._geometries.length; index++) {
  11709. if (this._geometries[index].id === id) {
  11710. return this._geometries[index];
  11711. }
  11712. }
  11713. return null;
  11714. };
  11715. /**
  11716. * add a new geometry to this scene.
  11717. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  11718. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  11719. * @return {boolean} was the geometry added or not
  11720. */
  11721. Scene.prototype.pushGeometry = function (geometry, force) {
  11722. if (!force && this.getGeometryByID(geometry.id)) {
  11723. return false;
  11724. }
  11725. this._geometries.push(geometry);
  11726. //notify the collision coordinator
  11727. this.collisionCoordinator.onGeometryAdded(geometry);
  11728. if (this.onGeometryAdded) {
  11729. this.onGeometryAdded(geometry);
  11730. }
  11731. return true;
  11732. };
  11733. /**
  11734. * Removes an existing geometry
  11735. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  11736. * @return {boolean} was the geometry removed or not
  11737. */
  11738. Scene.prototype.removeGeometry = function (geometry) {
  11739. var index = this._geometries.indexOf(geometry);
  11740. if (index > -1) {
  11741. this._geometries.splice(index, 1);
  11742. //notify the collision coordinator
  11743. this.collisionCoordinator.onGeometryDeleted(geometry);
  11744. if (this.onGeometryRemoved) {
  11745. this.onGeometryRemoved(geometry);
  11746. }
  11747. return true;
  11748. }
  11749. return false;
  11750. };
  11751. Scene.prototype.getGeometries = function () {
  11752. return this._geometries;
  11753. };
  11754. /**
  11755. * Get the first added mesh found of a given ID
  11756. * @param {string} id - the id to search for
  11757. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  11758. */
  11759. Scene.prototype.getMeshByID = function (id) {
  11760. for (var index = 0; index < this.meshes.length; index++) {
  11761. if (this.meshes[index].id === id) {
  11762. return this.meshes[index];
  11763. }
  11764. }
  11765. return null;
  11766. };
  11767. /**
  11768. * Get a mesh with its auto-generated unique id
  11769. * @param {number} uniqueId - the unique id to search for
  11770. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  11771. */
  11772. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  11773. for (var index = 0; index < this.meshes.length; index++) {
  11774. if (this.meshes[index].uniqueId === uniqueId) {
  11775. return this.meshes[index];
  11776. }
  11777. }
  11778. return null;
  11779. };
  11780. /**
  11781. * Get a the last added mesh found of a given ID
  11782. * @param {string} id - the id to search for
  11783. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  11784. */
  11785. Scene.prototype.getLastMeshByID = function (id) {
  11786. for (var index = this.meshes.length - 1; index >= 0; index--) {
  11787. if (this.meshes[index].id === id) {
  11788. return this.meshes[index];
  11789. }
  11790. }
  11791. return null;
  11792. };
  11793. /**
  11794. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  11795. * @param {string} id - the id to search for
  11796. * @return {BABYLON.Node|null} the node found or null if not found at all.
  11797. */
  11798. Scene.prototype.getLastEntryByID = function (id) {
  11799. for (var index = this.meshes.length - 1; index >= 0; index--) {
  11800. if (this.meshes[index].id === id) {
  11801. return this.meshes[index];
  11802. }
  11803. }
  11804. for (index = this.cameras.length - 1; index >= 0; index--) {
  11805. if (this.cameras[index].id === id) {
  11806. return this.cameras[index];
  11807. }
  11808. }
  11809. for (index = this.lights.length - 1; index >= 0; index--) {
  11810. if (this.lights[index].id === id) {
  11811. return this.lights[index];
  11812. }
  11813. }
  11814. return null;
  11815. };
  11816. Scene.prototype.getNodeByName = function (name) {
  11817. var mesh = this.getMeshByName(name);
  11818. if (mesh) {
  11819. return mesh;
  11820. }
  11821. var light = this.getLightByName(name);
  11822. if (light) {
  11823. return light;
  11824. }
  11825. return this.getCameraByName(name);
  11826. };
  11827. Scene.prototype.getMeshByName = function (name) {
  11828. for (var index = 0; index < this.meshes.length; index++) {
  11829. if (this.meshes[index].name === name) {
  11830. return this.meshes[index];
  11831. }
  11832. }
  11833. return null;
  11834. };
  11835. Scene.prototype.getSoundByName = function (name) {
  11836. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  11837. if (this.mainSoundTrack.soundCollection[index].name === name) {
  11838. return this.mainSoundTrack.soundCollection[index];
  11839. }
  11840. }
  11841. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  11842. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  11843. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  11844. return this.soundTracks[sdIndex].soundCollection[index];
  11845. }
  11846. }
  11847. }
  11848. return null;
  11849. };
  11850. Scene.prototype.getLastSkeletonByID = function (id) {
  11851. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  11852. if (this.skeletons[index].id === id) {
  11853. return this.skeletons[index];
  11854. }
  11855. }
  11856. return null;
  11857. };
  11858. Scene.prototype.getSkeletonById = function (id) {
  11859. for (var index = 0; index < this.skeletons.length; index++) {
  11860. if (this.skeletons[index].id === id) {
  11861. return this.skeletons[index];
  11862. }
  11863. }
  11864. return null;
  11865. };
  11866. Scene.prototype.getSkeletonByName = function (name) {
  11867. for (var index = 0; index < this.skeletons.length; index++) {
  11868. if (this.skeletons[index].name === name) {
  11869. return this.skeletons[index];
  11870. }
  11871. }
  11872. return null;
  11873. };
  11874. Scene.prototype.isActiveMesh = function (mesh) {
  11875. return (this._activeMeshes.indexOf(mesh) !== -1);
  11876. };
  11877. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  11878. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  11879. var material = subMesh.getMaterial();
  11880. if (mesh.showSubMeshesBoundingBox) {
  11881. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  11882. }
  11883. if (material) {
  11884. // Render targets
  11885. if (material.getRenderTargetTextures) {
  11886. if (this._processedMaterials.indexOf(material) === -1) {
  11887. this._processedMaterials.push(material);
  11888. this._renderTargets.concat(material.getRenderTargetTextures());
  11889. }
  11890. }
  11891. // Dispatch
  11892. this._activeIndices += subMesh.indexCount;
  11893. this._renderingManager.dispatch(subMesh);
  11894. }
  11895. }
  11896. };
  11897. Scene.prototype._evaluateActiveMeshes = function () {
  11898. this.activeCamera._activeMeshes.reset();
  11899. this._activeMeshes.reset();
  11900. this._renderingManager.reset();
  11901. this._processedMaterials.reset();
  11902. this._activeParticleSystems.reset();
  11903. this._activeSkeletons.reset();
  11904. this._boundingBoxRenderer.reset();
  11905. if (!this._frustumPlanes) {
  11906. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  11907. }
  11908. else {
  11909. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  11910. }
  11911. // Meshes
  11912. var meshes;
  11913. var len;
  11914. if (this._selectionOctree) {
  11915. var selection = this._selectionOctree.select(this._frustumPlanes);
  11916. meshes = selection.data;
  11917. len = selection.length;
  11918. }
  11919. else {
  11920. len = this.meshes.length;
  11921. meshes = this.meshes;
  11922. }
  11923. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  11924. var mesh = meshes[meshIndex];
  11925. if (mesh.isBlocked) {
  11926. continue;
  11927. }
  11928. this._totalVertices += mesh.getTotalVertices();
  11929. if (!mesh.isReady() || !mesh.isEnabled()) {
  11930. continue;
  11931. }
  11932. mesh.computeWorldMatrix();
  11933. // Intersections
  11934. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  11935. this._meshesForIntersections.pushNoDuplicate(mesh);
  11936. }
  11937. // Switch to current LOD
  11938. var meshLOD = mesh.getLOD(this.activeCamera);
  11939. if (!meshLOD) {
  11940. continue;
  11941. }
  11942. mesh._preActivate();
  11943. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  11944. this._activeMeshes.push(mesh);
  11945. this.activeCamera._activeMeshes.push(mesh);
  11946. mesh._activate(this._renderId);
  11947. this._activeMesh(meshLOD);
  11948. }
  11949. }
  11950. // Particle systems
  11951. var beforeParticlesDate = BABYLON.Tools.Now;
  11952. if (this.particlesEnabled) {
  11953. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  11954. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  11955. var particleSystem = this.particleSystems[particleIndex];
  11956. if (!particleSystem.isStarted()) {
  11957. continue;
  11958. }
  11959. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  11960. this._activeParticleSystems.push(particleSystem);
  11961. particleSystem.animate();
  11962. }
  11963. }
  11964. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  11965. }
  11966. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11967. };
  11968. Scene.prototype._activeMesh = function (mesh) {
  11969. if (mesh.skeleton && this.skeletonsEnabled) {
  11970. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  11971. }
  11972. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  11973. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  11974. }
  11975. if (mesh && mesh.subMeshes) {
  11976. // Submeshes Octrees
  11977. var len;
  11978. var subMeshes;
  11979. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  11980. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  11981. len = intersections.length;
  11982. subMeshes = intersections.data;
  11983. }
  11984. else {
  11985. subMeshes = mesh.subMeshes;
  11986. len = subMeshes.length;
  11987. }
  11988. for (var subIndex = 0; subIndex < len; subIndex++) {
  11989. var subMesh = subMeshes[subIndex];
  11990. this._evaluateSubMesh(subMesh, mesh);
  11991. }
  11992. }
  11993. };
  11994. Scene.prototype.updateTransformMatrix = function (force) {
  11995. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  11996. };
  11997. Scene.prototype._renderForCamera = function (camera) {
  11998. var engine = this._engine;
  11999. this.activeCamera = camera;
  12000. if (!this.activeCamera)
  12001. throw new Error("Active camera not set");
  12002. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12003. // Viewport
  12004. engine.setViewport(this.activeCamera.viewport);
  12005. // Camera
  12006. this._renderId++;
  12007. this.updateTransformMatrix();
  12008. if (this.beforeCameraRender) {
  12009. this.beforeCameraRender(this.activeCamera);
  12010. }
  12011. // Meshes
  12012. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  12013. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  12014. this._evaluateActiveMeshes();
  12015. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  12016. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  12017. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  12018. var skeleton = this._activeSkeletons.data[skeletonIndex];
  12019. skeleton.prepare();
  12020. }
  12021. // Render targets
  12022. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12023. if (this.renderTargetsEnabled) {
  12024. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12025. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  12026. var renderTarget = this._renderTargets.data[renderIndex];
  12027. if (renderTarget._shouldRender()) {
  12028. this._renderId++;
  12029. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  12030. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  12031. }
  12032. }
  12033. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12034. this._renderId++;
  12035. }
  12036. if (this._renderTargets.length > 0) {
  12037. engine.restoreDefaultFramebuffer();
  12038. }
  12039. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12040. // Prepare Frame
  12041. this.postProcessManager._prepareFrame();
  12042. var beforeRenderDate = BABYLON.Tools.Now;
  12043. // Backgrounds
  12044. if (this.layers.length) {
  12045. engine.setDepthBuffer(false);
  12046. var layerIndex;
  12047. var layer;
  12048. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12049. layer = this.layers[layerIndex];
  12050. if (layer.isBackground) {
  12051. layer.render();
  12052. }
  12053. }
  12054. engine.setDepthBuffer(true);
  12055. }
  12056. // Render
  12057. BABYLON.Tools.StartPerformanceCounter("Main render");
  12058. this._renderingManager.render(null, null, true, true);
  12059. BABYLON.Tools.EndPerformanceCounter("Main render");
  12060. // Bounding boxes
  12061. this._boundingBoxRenderer.render();
  12062. // Lens flares
  12063. if (this.lensFlaresEnabled) {
  12064. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12065. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  12066. this.lensFlareSystems[lensFlareSystemIndex].render();
  12067. }
  12068. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12069. }
  12070. // Foregrounds
  12071. if (this.layers.length) {
  12072. engine.setDepthBuffer(false);
  12073. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12074. layer = this.layers[layerIndex];
  12075. if (!layer.isBackground) {
  12076. layer.render();
  12077. }
  12078. }
  12079. engine.setDepthBuffer(true);
  12080. }
  12081. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  12082. // Finalize frame
  12083. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  12084. // Update camera
  12085. this.activeCamera._updateFromScene();
  12086. // Reset some special arrays
  12087. this._renderTargets.reset();
  12088. if (this.afterCameraRender) {
  12089. this.afterCameraRender(this.activeCamera);
  12090. }
  12091. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12092. };
  12093. Scene.prototype._processSubCameras = function (camera) {
  12094. if (camera.subCameras.length === 0) {
  12095. this._renderForCamera(camera);
  12096. return;
  12097. }
  12098. for (var index = 0; index < camera.subCameras.length; index++) {
  12099. this._renderForCamera(camera.subCameras[index]);
  12100. }
  12101. this.activeCamera = camera;
  12102. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  12103. // Update camera
  12104. this.activeCamera._updateFromScene();
  12105. };
  12106. Scene.prototype._checkIntersections = function () {
  12107. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  12108. var sourceMesh = this._meshesForIntersections.data[index];
  12109. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  12110. var action = sourceMesh.actionManager.actions[actionIndex];
  12111. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12112. var parameters = action.getTriggerParameter();
  12113. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  12114. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  12115. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  12116. if (areIntersecting && currentIntersectionInProgress === -1) {
  12117. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  12118. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  12119. sourceMesh._intersectionsInProgress.push(otherMesh);
  12120. }
  12121. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12122. sourceMesh._intersectionsInProgress.push(otherMesh);
  12123. }
  12124. }
  12125. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12126. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  12127. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  12128. if (indexOfOther > -1) {
  12129. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  12130. }
  12131. }
  12132. }
  12133. }
  12134. }
  12135. };
  12136. Scene.prototype.render = function () {
  12137. var startDate = BABYLON.Tools.Now;
  12138. this._particlesDuration = 0;
  12139. this._spritesDuration = 0;
  12140. this._activeParticles = 0;
  12141. this._renderDuration = 0;
  12142. this._renderTargetsDuration = 0;
  12143. this._evaluateActiveMeshesDuration = 0;
  12144. this._totalVertices = 0;
  12145. this._activeIndices = 0;
  12146. this._activeBones = 0;
  12147. this.getEngine().resetDrawCalls();
  12148. this._meshesForIntersections.reset();
  12149. this.resetCachedMaterial();
  12150. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  12151. // Actions
  12152. if (this.actionManager) {
  12153. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  12154. }
  12155. //Simplification Queue
  12156. if (!this.simplificationQueue.running) {
  12157. this.simplificationQueue.executeNext();
  12158. }
  12159. // Before render
  12160. if (this.beforeRender) {
  12161. this.beforeRender();
  12162. }
  12163. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  12164. this._onBeforeRenderCallbacks[callbackIndex]();
  12165. }
  12166. // Animations
  12167. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  12168. this._animationRatio = deltaTime * (60.0 / 1000.0);
  12169. this._animate();
  12170. // Physics
  12171. if (this._physicsEngine) {
  12172. BABYLON.Tools.StartPerformanceCounter("Physics");
  12173. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  12174. BABYLON.Tools.EndPerformanceCounter("Physics");
  12175. }
  12176. // Customs render targets
  12177. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12178. var engine = this.getEngine();
  12179. var currentActiveCamera = this.activeCamera;
  12180. if (this.renderTargetsEnabled) {
  12181. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12182. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  12183. var renderTarget = this.customRenderTargets[customIndex];
  12184. if (renderTarget._shouldRender()) {
  12185. this._renderId++;
  12186. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  12187. if (!this.activeCamera)
  12188. throw new Error("Active camera not set");
  12189. // Viewport
  12190. engine.setViewport(this.activeCamera.viewport);
  12191. // Camera
  12192. this.updateTransformMatrix();
  12193. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  12194. }
  12195. }
  12196. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12197. this._renderId++;
  12198. }
  12199. if (this.customRenderTargets.length > 0) {
  12200. engine.restoreDefaultFramebuffer();
  12201. }
  12202. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12203. this.activeCamera = currentActiveCamera;
  12204. // Procedural textures
  12205. if (this.proceduralTexturesEnabled) {
  12206. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12207. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  12208. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  12209. if (proceduralTexture._shouldRender()) {
  12210. proceduralTexture.render();
  12211. }
  12212. }
  12213. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12214. }
  12215. // Clear
  12216. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  12217. // Shadows
  12218. if (this.shadowsEnabled) {
  12219. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  12220. var light = this.lights[lightIndex];
  12221. var shadowGenerator = light.getShadowGenerator();
  12222. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  12223. this._renderTargets.push(shadowGenerator.getShadowMap());
  12224. }
  12225. }
  12226. }
  12227. // Depth renderer
  12228. if (this._depthRenderer) {
  12229. this._renderTargets.push(this._depthRenderer.getDepthMap());
  12230. }
  12231. // RenderPipeline
  12232. this.postProcessRenderPipelineManager.update();
  12233. // Multi-cameras?
  12234. if (this.activeCameras.length > 0) {
  12235. var currentRenderId = this._renderId;
  12236. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  12237. this._renderId = currentRenderId;
  12238. this._processSubCameras(this.activeCameras[cameraIndex]);
  12239. }
  12240. }
  12241. else {
  12242. if (!this.activeCamera) {
  12243. throw new Error("No camera defined");
  12244. }
  12245. this._processSubCameras(this.activeCamera);
  12246. }
  12247. // Intersection checks
  12248. this._checkIntersections();
  12249. // Update the audio listener attached to the camera
  12250. this._updateAudioParameters();
  12251. // After render
  12252. if (this.afterRender) {
  12253. this.afterRender();
  12254. }
  12255. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  12256. this._onAfterRenderCallbacks[callbackIndex]();
  12257. }
  12258. for (var index = 0; index < this._toBeDisposed.length; index++) {
  12259. this._toBeDisposed.data[index].dispose();
  12260. this._toBeDisposed[index] = null;
  12261. }
  12262. this._toBeDisposed.reset();
  12263. if (this.dumpNextRenderTargets) {
  12264. this.dumpNextRenderTargets = false;
  12265. }
  12266. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  12267. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  12268. };
  12269. Scene.prototype._updateAudioParameters = function () {
  12270. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  12271. return;
  12272. }
  12273. var listeningCamera;
  12274. var audioEngine = BABYLON.Engine.audioEngine;
  12275. if (this.activeCameras.length > 0) {
  12276. listeningCamera = this.activeCameras[0];
  12277. }
  12278. else {
  12279. listeningCamera = this.activeCamera;
  12280. }
  12281. if (listeningCamera && audioEngine.canUseWebAudio) {
  12282. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  12283. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  12284. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  12285. cameraDirection.normalize();
  12286. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  12287. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12288. var sound = this.mainSoundTrack.soundCollection[i];
  12289. if (sound.useCustomAttenuation) {
  12290. sound.updateDistanceFromListener();
  12291. }
  12292. }
  12293. for (i = 0; i < this.soundTracks.length; i++) {
  12294. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12295. sound = this.soundTracks[i].soundCollection[j];
  12296. if (sound.useCustomAttenuation) {
  12297. sound.updateDistanceFromListener();
  12298. }
  12299. }
  12300. }
  12301. }
  12302. };
  12303. Object.defineProperty(Scene.prototype, "audioEnabled", {
  12304. // Audio
  12305. get: function () {
  12306. return this._audioEnabled;
  12307. },
  12308. set: function (value) {
  12309. this._audioEnabled = value;
  12310. if (this._audioEnabled) {
  12311. this._enableAudio();
  12312. }
  12313. else {
  12314. this._disableAudio();
  12315. }
  12316. },
  12317. enumerable: true,
  12318. configurable: true
  12319. });
  12320. Scene.prototype._disableAudio = function () {
  12321. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12322. this.mainSoundTrack.soundCollection[i].pause();
  12323. }
  12324. for (i = 0; i < this.soundTracks.length; i++) {
  12325. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12326. this.soundTracks[i].soundCollection[j].pause();
  12327. }
  12328. }
  12329. };
  12330. Scene.prototype._enableAudio = function () {
  12331. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12332. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  12333. this.mainSoundTrack.soundCollection[i].play();
  12334. }
  12335. }
  12336. for (i = 0; i < this.soundTracks.length; i++) {
  12337. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12338. if (this.soundTracks[i].soundCollection[j].isPaused) {
  12339. this.soundTracks[i].soundCollection[j].play();
  12340. }
  12341. }
  12342. }
  12343. };
  12344. Object.defineProperty(Scene.prototype, "headphone", {
  12345. get: function () {
  12346. return this._headphone;
  12347. },
  12348. set: function (value) {
  12349. this._headphone = value;
  12350. if (this._headphone) {
  12351. this._switchAudioModeForHeadphones();
  12352. }
  12353. else {
  12354. this._switchAudioModeForNormalSpeakers();
  12355. }
  12356. },
  12357. enumerable: true,
  12358. configurable: true
  12359. });
  12360. Scene.prototype._switchAudioModeForHeadphones = function () {
  12361. this.mainSoundTrack.switchPanningModelToHRTF();
  12362. for (var i = 0; i < this.soundTracks.length; i++) {
  12363. this.soundTracks[i].switchPanningModelToHRTF();
  12364. }
  12365. };
  12366. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  12367. this.mainSoundTrack.switchPanningModelToEqualPower();
  12368. for (var i = 0; i < this.soundTracks.length; i++) {
  12369. this.soundTracks[i].switchPanningModelToEqualPower();
  12370. }
  12371. };
  12372. Scene.prototype.enableDepthRenderer = function () {
  12373. if (this._depthRenderer) {
  12374. return this._depthRenderer;
  12375. }
  12376. this._depthRenderer = new BABYLON.DepthRenderer(this);
  12377. return this._depthRenderer;
  12378. };
  12379. Scene.prototype.disableDepthRenderer = function () {
  12380. if (!this._depthRenderer) {
  12381. return;
  12382. }
  12383. this._depthRenderer.dispose();
  12384. this._depthRenderer = null;
  12385. };
  12386. Scene.prototype.dispose = function () {
  12387. this.beforeRender = null;
  12388. this.afterRender = null;
  12389. this.skeletons = [];
  12390. this._boundingBoxRenderer.dispose();
  12391. if (this._depthRenderer) {
  12392. this._depthRenderer.dispose();
  12393. }
  12394. // Debug layer
  12395. this.debugLayer.hide();
  12396. // Events
  12397. if (this.onDispose) {
  12398. this.onDispose();
  12399. }
  12400. this._onBeforeRenderCallbacks = [];
  12401. this._onAfterRenderCallbacks = [];
  12402. this.detachControl();
  12403. // Release sounds & sounds tracks
  12404. this.disposeSounds();
  12405. // Detach cameras
  12406. var canvas = this._engine.getRenderingCanvas();
  12407. var index;
  12408. for (index = 0; index < this.cameras.length; index++) {
  12409. this.cameras[index].detachControl(canvas);
  12410. }
  12411. while (this.lights.length) {
  12412. this.lights[0].dispose();
  12413. }
  12414. while (this.meshes.length) {
  12415. this.meshes[0].dispose(true);
  12416. }
  12417. while (this.cameras.length) {
  12418. this.cameras[0].dispose();
  12419. }
  12420. while (this.materials.length) {
  12421. this.materials[0].dispose();
  12422. }
  12423. while (this.particleSystems.length) {
  12424. this.particleSystems[0].dispose();
  12425. }
  12426. while (this.spriteManagers.length) {
  12427. this.spriteManagers[0].dispose();
  12428. }
  12429. while (this.layers.length) {
  12430. this.layers[0].dispose();
  12431. }
  12432. while (this.textures.length) {
  12433. this.textures[0].dispose();
  12434. }
  12435. // Post-processes
  12436. this.postProcessManager.dispose();
  12437. // Physics
  12438. if (this._physicsEngine) {
  12439. this.disablePhysicsEngine();
  12440. }
  12441. // Remove from engine
  12442. index = this._engine.scenes.indexOf(this);
  12443. if (index > -1) {
  12444. this._engine.scenes.splice(index, 1);
  12445. }
  12446. this._engine.wipeCaches();
  12447. };
  12448. // Release sounds & sounds tracks
  12449. Scene.prototype.disposeSounds = function () {
  12450. this.mainSoundTrack.dispose();
  12451. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  12452. this.soundTracks[scIndex].dispose();
  12453. }
  12454. };
  12455. // Octrees
  12456. Scene.prototype.getWorldExtends = function () {
  12457. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12458. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  12459. for (var index = 0; index < this.meshes.length; index++) {
  12460. var mesh = this.meshes[index];
  12461. mesh.computeWorldMatrix(true);
  12462. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  12463. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  12464. BABYLON.Tools.CheckExtends(minBox, min, max);
  12465. BABYLON.Tools.CheckExtends(maxBox, min, max);
  12466. }
  12467. return {
  12468. min: min,
  12469. max: max
  12470. };
  12471. };
  12472. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  12473. if (maxCapacity === void 0) { maxCapacity = 64; }
  12474. if (maxDepth === void 0) { maxDepth = 2; }
  12475. if (!this._selectionOctree) {
  12476. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  12477. }
  12478. var worldExtends = this.getWorldExtends();
  12479. // Update octree
  12480. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  12481. return this._selectionOctree;
  12482. };
  12483. // Picking
  12484. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  12485. var engine = this._engine;
  12486. if (!camera) {
  12487. if (!this.activeCamera)
  12488. throw new Error("Active camera not set");
  12489. camera = this.activeCamera;
  12490. }
  12491. var cameraViewport = camera.viewport;
  12492. var viewport = cameraViewport.toGlobal(engine);
  12493. // Moving coordinates to local viewport world
  12494. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  12495. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  12496. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  12497. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  12498. };
  12499. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  12500. var pickingInfo = null;
  12501. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  12502. var mesh = this.meshes[meshIndex];
  12503. if (predicate) {
  12504. if (!predicate(mesh)) {
  12505. continue;
  12506. }
  12507. }
  12508. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  12509. continue;
  12510. }
  12511. var world = mesh.getWorldMatrix();
  12512. var ray = rayFunction(world);
  12513. var result = mesh.intersects(ray, fastCheck);
  12514. if (!result || !result.hit)
  12515. continue;
  12516. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  12517. continue;
  12518. pickingInfo = result;
  12519. if (fastCheck) {
  12520. break;
  12521. }
  12522. }
  12523. return pickingInfo || new BABYLON.PickingInfo();
  12524. };
  12525. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  12526. var _this = this;
  12527. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  12528. /// <param name="x">X position on screen</param>
  12529. /// <param name="y">Y position on screen</param>
  12530. /// <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>
  12531. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  12532. /// <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>
  12533. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  12534. };
  12535. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  12536. var _this = this;
  12537. return this._internalPick(function (world) {
  12538. if (!_this._pickWithRayInverseMatrix) {
  12539. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  12540. }
  12541. world.invertToRef(_this._pickWithRayInverseMatrix);
  12542. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  12543. }, predicate, fastCheck);
  12544. };
  12545. Scene.prototype.setPointerOverMesh = function (mesh) {
  12546. if (this._pointerOverMesh === mesh) {
  12547. return;
  12548. }
  12549. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  12550. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  12551. }
  12552. this._pointerOverMesh = mesh;
  12553. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  12554. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  12555. }
  12556. };
  12557. Scene.prototype.getPointerOverMesh = function () {
  12558. return this._pointerOverMesh;
  12559. };
  12560. // Physics
  12561. Scene.prototype.getPhysicsEngine = function () {
  12562. return this._physicsEngine;
  12563. };
  12564. Scene.prototype.enablePhysics = function (gravity, plugin) {
  12565. if (this._physicsEngine) {
  12566. return true;
  12567. }
  12568. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  12569. if (!this._physicsEngine.isSupported()) {
  12570. this._physicsEngine = null;
  12571. return false;
  12572. }
  12573. this._physicsEngine._initialize(gravity);
  12574. return true;
  12575. };
  12576. Scene.prototype.disablePhysicsEngine = function () {
  12577. if (!this._physicsEngine) {
  12578. return;
  12579. }
  12580. this._physicsEngine.dispose();
  12581. this._physicsEngine = undefined;
  12582. };
  12583. Scene.prototype.isPhysicsEnabled = function () {
  12584. return this._physicsEngine !== undefined;
  12585. };
  12586. Scene.prototype.setGravity = function (gravity) {
  12587. if (!this._physicsEngine) {
  12588. return;
  12589. }
  12590. this._physicsEngine._setGravity(gravity);
  12591. };
  12592. Scene.prototype.createCompoundImpostor = function (parts, options) {
  12593. if (parts.parts) {
  12594. options = parts;
  12595. parts = parts.parts;
  12596. }
  12597. if (!this._physicsEngine) {
  12598. return null;
  12599. }
  12600. for (var index = 0; index < parts.length; index++) {
  12601. var mesh = parts[index].mesh;
  12602. mesh._physicImpostor = parts[index].impostor;
  12603. mesh._physicsMass = options.mass / parts.length;
  12604. mesh._physicsFriction = options.friction;
  12605. mesh._physicRestitution = options.restitution;
  12606. }
  12607. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  12608. };
  12609. Scene.prototype.deleteCompoundImpostor = function (compound) {
  12610. for (var index = 0; index < compound.parts.length; index++) {
  12611. var mesh = compound.parts[index].mesh;
  12612. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  12613. this._physicsEngine._unregisterMesh(mesh);
  12614. }
  12615. };
  12616. // Misc.
  12617. Scene.prototype.createDefaultCameraOrLight = function () {
  12618. // Light
  12619. if (this.lights.length === 0) {
  12620. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  12621. }
  12622. // Camera
  12623. if (!this.activeCamera) {
  12624. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  12625. // Compute position
  12626. var worldExtends = this.getWorldExtends();
  12627. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  12628. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  12629. camera.setTarget(worldCenter);
  12630. this.activeCamera = camera;
  12631. }
  12632. };
  12633. // Tags
  12634. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  12635. if (tagsQuery === undefined) {
  12636. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  12637. return list;
  12638. }
  12639. var listByTags = [];
  12640. forEach = forEach || (function (item) {
  12641. return;
  12642. });
  12643. for (var i in list) {
  12644. var item = list[i];
  12645. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  12646. listByTags.push(item);
  12647. forEach(item);
  12648. }
  12649. }
  12650. return listByTags;
  12651. };
  12652. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  12653. return this._getByTags(this.meshes, tagsQuery, forEach);
  12654. };
  12655. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  12656. return this._getByTags(this.cameras, tagsQuery, forEach);
  12657. };
  12658. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  12659. return this._getByTags(this.lights, tagsQuery, forEach);
  12660. };
  12661. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  12662. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  12663. };
  12664. // Statics
  12665. Scene._FOGMODE_NONE = 0;
  12666. Scene._FOGMODE_EXP = 1;
  12667. Scene._FOGMODE_EXP2 = 2;
  12668. Scene._FOGMODE_LINEAR = 3;
  12669. Scene.MinDeltaTime = 1.0;
  12670. Scene.MaxDeltaTime = 1000.0;
  12671. return Scene;
  12672. })();
  12673. BABYLON.Scene = Scene;
  12674. })(BABYLON || (BABYLON = {}));
  12675. //# sourceMappingURL=babylon.scene.js.map
  12676. var BABYLON;
  12677. (function (BABYLON) {
  12678. var VertexBuffer = (function () {
  12679. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  12680. if (engine instanceof BABYLON.Mesh) {
  12681. this._engine = engine.getScene().getEngine();
  12682. }
  12683. else {
  12684. this._engine = engine;
  12685. }
  12686. this._updatable = updatable;
  12687. this._data = data;
  12688. if (!postponeInternalCreation) {
  12689. this.create();
  12690. }
  12691. this._kind = kind;
  12692. if (stride) {
  12693. this._strideSize = stride;
  12694. return;
  12695. }
  12696. switch (kind) {
  12697. case VertexBuffer.PositionKind:
  12698. this._strideSize = 3;
  12699. break;
  12700. case VertexBuffer.NormalKind:
  12701. this._strideSize = 3;
  12702. break;
  12703. case VertexBuffer.UVKind:
  12704. this._strideSize = 2;
  12705. break;
  12706. case VertexBuffer.UV2Kind:
  12707. this._strideSize = 2;
  12708. break;
  12709. case VertexBuffer.ColorKind:
  12710. this._strideSize = 4;
  12711. break;
  12712. case VertexBuffer.MatricesIndicesKind:
  12713. this._strideSize = 4;
  12714. break;
  12715. case VertexBuffer.MatricesWeightsKind:
  12716. this._strideSize = 4;
  12717. break;
  12718. }
  12719. }
  12720. // Properties
  12721. VertexBuffer.prototype.isUpdatable = function () {
  12722. return this._updatable;
  12723. };
  12724. VertexBuffer.prototype.getData = function () {
  12725. return this._data;
  12726. };
  12727. VertexBuffer.prototype.getBuffer = function () {
  12728. return this._buffer;
  12729. };
  12730. VertexBuffer.prototype.getStrideSize = function () {
  12731. return this._strideSize;
  12732. };
  12733. // Methods
  12734. VertexBuffer.prototype.create = function (data) {
  12735. if (!data && this._buffer) {
  12736. return; // nothing to do
  12737. }
  12738. data = data || this._data;
  12739. if (!this._buffer) {
  12740. if (this._updatable) {
  12741. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  12742. }
  12743. else {
  12744. this._buffer = this._engine.createVertexBuffer(data);
  12745. }
  12746. }
  12747. if (this._updatable) {
  12748. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  12749. this._data = data;
  12750. }
  12751. };
  12752. VertexBuffer.prototype.update = function (data) {
  12753. this.create(data);
  12754. };
  12755. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  12756. if (!this._buffer) {
  12757. return;
  12758. }
  12759. if (this._updatable) {
  12760. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  12761. this._data = null;
  12762. }
  12763. };
  12764. VertexBuffer.prototype.dispose = function () {
  12765. if (!this._buffer) {
  12766. return;
  12767. }
  12768. if (this._engine._releaseBuffer(this._buffer)) {
  12769. this._buffer = null;
  12770. }
  12771. };
  12772. Object.defineProperty(VertexBuffer, "PositionKind", {
  12773. get: function () {
  12774. return VertexBuffer._PositionKind;
  12775. },
  12776. enumerable: true,
  12777. configurable: true
  12778. });
  12779. Object.defineProperty(VertexBuffer, "NormalKind", {
  12780. get: function () {
  12781. return VertexBuffer._NormalKind;
  12782. },
  12783. enumerable: true,
  12784. configurable: true
  12785. });
  12786. Object.defineProperty(VertexBuffer, "UVKind", {
  12787. get: function () {
  12788. return VertexBuffer._UVKind;
  12789. },
  12790. enumerable: true,
  12791. configurable: true
  12792. });
  12793. Object.defineProperty(VertexBuffer, "UV2Kind", {
  12794. get: function () {
  12795. return VertexBuffer._UV2Kind;
  12796. },
  12797. enumerable: true,
  12798. configurable: true
  12799. });
  12800. Object.defineProperty(VertexBuffer, "ColorKind", {
  12801. get: function () {
  12802. return VertexBuffer._ColorKind;
  12803. },
  12804. enumerable: true,
  12805. configurable: true
  12806. });
  12807. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  12808. get: function () {
  12809. return VertexBuffer._MatricesIndicesKind;
  12810. },
  12811. enumerable: true,
  12812. configurable: true
  12813. });
  12814. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  12815. get: function () {
  12816. return VertexBuffer._MatricesWeightsKind;
  12817. },
  12818. enumerable: true,
  12819. configurable: true
  12820. });
  12821. // Enums
  12822. VertexBuffer._PositionKind = "position";
  12823. VertexBuffer._NormalKind = "normal";
  12824. VertexBuffer._UVKind = "uv";
  12825. VertexBuffer._UV2Kind = "uv2";
  12826. VertexBuffer._ColorKind = "color";
  12827. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  12828. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  12829. return VertexBuffer;
  12830. })();
  12831. BABYLON.VertexBuffer = VertexBuffer;
  12832. })(BABYLON || (BABYLON = {}));
  12833. //# sourceMappingURL=babylon.vertexBuffer.js.map
  12834. var __extends = this.__extends || function (d, b) {
  12835. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12836. function __() { this.constructor = d; }
  12837. __.prototype = b.prototype;
  12838. d.prototype = new __();
  12839. };
  12840. var BABYLON;
  12841. (function (BABYLON) {
  12842. /**
  12843. * Creates an instance based on a source mesh.
  12844. */
  12845. var InstancedMesh = (function (_super) {
  12846. __extends(InstancedMesh, _super);
  12847. function InstancedMesh(name, source) {
  12848. _super.call(this, name, source.getScene());
  12849. source.instances.push(this);
  12850. this._sourceMesh = source;
  12851. this.position.copyFrom(source.position);
  12852. this.rotation.copyFrom(source.rotation);
  12853. this.scaling.copyFrom(source.scaling);
  12854. if (source.rotationQuaternion) {
  12855. this.rotationQuaternion = source.rotationQuaternion.clone();
  12856. }
  12857. this.infiniteDistance = source.infiniteDistance;
  12858. this.setPivotMatrix(source.getPivotMatrix());
  12859. this.refreshBoundingInfo();
  12860. this._syncSubMeshes();
  12861. }
  12862. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  12863. // Methods
  12864. get: function () {
  12865. return this._sourceMesh.receiveShadows;
  12866. },
  12867. enumerable: true,
  12868. configurable: true
  12869. });
  12870. Object.defineProperty(InstancedMesh.prototype, "material", {
  12871. get: function () {
  12872. return this._sourceMesh.material;
  12873. },
  12874. enumerable: true,
  12875. configurable: true
  12876. });
  12877. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  12878. get: function () {
  12879. return this._sourceMesh.visibility;
  12880. },
  12881. enumerable: true,
  12882. configurable: true
  12883. });
  12884. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  12885. get: function () {
  12886. return this._sourceMesh.skeleton;
  12887. },
  12888. enumerable: true,
  12889. configurable: true
  12890. });
  12891. InstancedMesh.prototype.getTotalVertices = function () {
  12892. return this._sourceMesh.getTotalVertices();
  12893. };
  12894. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  12895. get: function () {
  12896. return this._sourceMesh;
  12897. },
  12898. enumerable: true,
  12899. configurable: true
  12900. });
  12901. InstancedMesh.prototype.getVerticesData = function (kind) {
  12902. return this._sourceMesh.getVerticesData(kind);
  12903. };
  12904. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  12905. return this._sourceMesh.isVerticesDataPresent(kind);
  12906. };
  12907. InstancedMesh.prototype.getIndices = function () {
  12908. return this._sourceMesh.getIndices();
  12909. };
  12910. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  12911. get: function () {
  12912. return this._sourceMesh._positions;
  12913. },
  12914. enumerable: true,
  12915. configurable: true
  12916. });
  12917. InstancedMesh.prototype.refreshBoundingInfo = function () {
  12918. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12919. if (data) {
  12920. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  12921. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12922. }
  12923. this._updateBoundingInfo();
  12924. };
  12925. InstancedMesh.prototype._preActivate = function () {
  12926. if (this._currentLOD) {
  12927. this._currentLOD._preActivate();
  12928. }
  12929. };
  12930. InstancedMesh.prototype._activate = function (renderId) {
  12931. if (this._currentLOD) {
  12932. this._currentLOD._registerInstanceForRenderId(this, renderId);
  12933. }
  12934. };
  12935. InstancedMesh.prototype.getLOD = function (camera) {
  12936. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  12937. if (this._currentLOD === this.sourceMesh) {
  12938. return this;
  12939. }
  12940. return this._currentLOD;
  12941. };
  12942. InstancedMesh.prototype._syncSubMeshes = function () {
  12943. this.releaseSubMeshes();
  12944. if (this._sourceMesh.subMeshes) {
  12945. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  12946. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  12947. }
  12948. }
  12949. };
  12950. InstancedMesh.prototype._generatePointsArray = function () {
  12951. return this._sourceMesh._generatePointsArray();
  12952. };
  12953. // Clone
  12954. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12955. var result = this._sourceMesh.createInstance(name);
  12956. // Deep copy
  12957. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  12958. // Bounding info
  12959. this.refreshBoundingInfo();
  12960. // Parent
  12961. if (newParent) {
  12962. result.parent = newParent;
  12963. }
  12964. if (!doNotCloneChildren) {
  12965. for (var index = 0; index < this.getScene().meshes.length; index++) {
  12966. var mesh = this.getScene().meshes[index];
  12967. if (mesh.parent === this) {
  12968. mesh.clone(mesh.name, result);
  12969. }
  12970. }
  12971. }
  12972. result.computeWorldMatrix(true);
  12973. return result;
  12974. };
  12975. // Dispoe
  12976. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  12977. // Remove from mesh
  12978. var index = this._sourceMesh.instances.indexOf(this);
  12979. this._sourceMesh.instances.splice(index, 1);
  12980. _super.prototype.dispose.call(this, doNotRecurse);
  12981. };
  12982. return InstancedMesh;
  12983. })(BABYLON.AbstractMesh);
  12984. BABYLON.InstancedMesh = InstancedMesh;
  12985. })(BABYLON || (BABYLON = {}));
  12986. //# sourceMappingURL=babylon.instancedMesh.js.map
  12987. var __extends = this.__extends || function (d, b) {
  12988. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12989. function __() { this.constructor = d; }
  12990. __.prototype = b.prototype;
  12991. d.prototype = new __();
  12992. };
  12993. var BABYLON;
  12994. (function (BABYLON) {
  12995. var _InstancesBatch = (function () {
  12996. function _InstancesBatch() {
  12997. this.mustReturn = false;
  12998. this.visibleInstances = new Array();
  12999. this.renderSelf = new Array();
  13000. }
  13001. return _InstancesBatch;
  13002. })();
  13003. BABYLON._InstancesBatch = _InstancesBatch;
  13004. var Mesh = (function (_super) {
  13005. __extends(Mesh, _super);
  13006. /**
  13007. * @constructor
  13008. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  13009. * @param {Scene} scene - The scene to add this mesh to.
  13010. * @param {Node} parent - The parent of this mesh, if it has one
  13011. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  13012. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  13013. * When false, achieved by calling a clone(), also passing False.
  13014. * This will make creation of children, recursive.
  13015. */
  13016. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  13017. if (parent === void 0) { parent = null; }
  13018. _super.call(this, name, scene);
  13019. // Members
  13020. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  13021. this.instances = new Array();
  13022. this._LODLevels = new Array();
  13023. this._onBeforeRenderCallbacks = new Array();
  13024. this._onAfterRenderCallbacks = new Array();
  13025. this._visibleInstances = {};
  13026. this._renderIdForInstances = new Array();
  13027. this._batchCache = new _InstancesBatch();
  13028. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  13029. this._sideOrientation = Mesh._DEFAULTSIDE;
  13030. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  13031. if (source) {
  13032. // Geometry
  13033. if (source._geometry) {
  13034. source._geometry.applyToMesh(this);
  13035. }
  13036. // Deep copy
  13037. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  13038. // Material
  13039. this.material = source.material;
  13040. if (!doNotCloneChildren) {
  13041. for (var index = 0; index < scene.meshes.length; index++) {
  13042. var mesh = scene.meshes[index];
  13043. if (mesh.parent === source) {
  13044. // doNotCloneChildren is always going to be False
  13045. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  13046. }
  13047. }
  13048. }
  13049. for (index = 0; index < scene.particleSystems.length; index++) {
  13050. var system = scene.particleSystems[index];
  13051. if (system.emitter === source) {
  13052. system.clone(system.name, this);
  13053. }
  13054. }
  13055. this.computeWorldMatrix(true);
  13056. }
  13057. // Parent
  13058. if (parent !== null) {
  13059. this.parent = parent;
  13060. }
  13061. }
  13062. Object.defineProperty(Mesh, "FRONTSIDE", {
  13063. get: function () {
  13064. return Mesh._FRONTSIDE;
  13065. },
  13066. enumerable: true,
  13067. configurable: true
  13068. });
  13069. Object.defineProperty(Mesh, "BACKSIDE", {
  13070. get: function () {
  13071. return Mesh._BACKSIDE;
  13072. },
  13073. enumerable: true,
  13074. configurable: true
  13075. });
  13076. Object.defineProperty(Mesh, "DOUBLESIDE", {
  13077. get: function () {
  13078. return Mesh._DOUBLESIDE;
  13079. },
  13080. enumerable: true,
  13081. configurable: true
  13082. });
  13083. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  13084. get: function () {
  13085. return Mesh._DEFAULTSIDE;
  13086. },
  13087. enumerable: true,
  13088. configurable: true
  13089. });
  13090. Object.defineProperty(Mesh, "NO_CAP", {
  13091. get: function () {
  13092. return Mesh._NO_CAP;
  13093. },
  13094. enumerable: true,
  13095. configurable: true
  13096. });
  13097. Object.defineProperty(Mesh, "CAP_START", {
  13098. get: function () {
  13099. return Mesh._CAP_START;
  13100. },
  13101. enumerable: true,
  13102. configurable: true
  13103. });
  13104. Object.defineProperty(Mesh, "CAP_END", {
  13105. get: function () {
  13106. return Mesh._CAP_END;
  13107. },
  13108. enumerable: true,
  13109. configurable: true
  13110. });
  13111. Object.defineProperty(Mesh, "CAP_ALL", {
  13112. get: function () {
  13113. return Mesh._CAP_ALL;
  13114. },
  13115. enumerable: true,
  13116. configurable: true
  13117. });
  13118. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  13119. // Methods
  13120. get: function () {
  13121. return this._LODLevels.length > 0;
  13122. },
  13123. enumerable: true,
  13124. configurable: true
  13125. });
  13126. Mesh.prototype._sortLODLevels = function () {
  13127. this._LODLevels.sort(function (a, b) {
  13128. if (a.distance < b.distance) {
  13129. return 1;
  13130. }
  13131. if (a.distance > b.distance) {
  13132. return -1;
  13133. }
  13134. return 0;
  13135. });
  13136. };
  13137. /**
  13138. * Add a mesh as LOD level triggered at the given distance.
  13139. * @param {number} distance - the distance from the center of the object to show this level
  13140. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  13141. * @return {BABYLON.Mesh} this mesh (for chaining)
  13142. */
  13143. Mesh.prototype.addLODLevel = function (distance, mesh) {
  13144. if (mesh && mesh._masterMesh) {
  13145. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  13146. return this;
  13147. }
  13148. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  13149. this._LODLevels.push(level);
  13150. if (mesh) {
  13151. mesh._masterMesh = this;
  13152. }
  13153. this._sortLODLevels();
  13154. return this;
  13155. };
  13156. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  13157. for (var index = 0; index < this._LODLevels.length; index++) {
  13158. var level = this._LODLevels[index];
  13159. if (level.distance === distance) {
  13160. return level.mesh;
  13161. }
  13162. }
  13163. return null;
  13164. };
  13165. /**
  13166. * Remove a mesh from the LOD array
  13167. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  13168. * @return {BABYLON.Mesh} this mesh (for chaining)
  13169. */
  13170. Mesh.prototype.removeLODLevel = function (mesh) {
  13171. for (var index = 0; index < this._LODLevels.length; index++) {
  13172. if (this._LODLevels[index].mesh === mesh) {
  13173. this._LODLevels.splice(index, 1);
  13174. if (mesh) {
  13175. mesh._masterMesh = null;
  13176. }
  13177. }
  13178. }
  13179. this._sortLODLevels();
  13180. return this;
  13181. };
  13182. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  13183. if (!this._LODLevels || this._LODLevels.length === 0) {
  13184. return this;
  13185. }
  13186. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  13187. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  13188. if (this.onLODLevelSelection) {
  13189. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  13190. }
  13191. return this;
  13192. }
  13193. for (var index = 0; index < this._LODLevels.length; index++) {
  13194. var level = this._LODLevels[index];
  13195. if (level.distance < distanceToCamera) {
  13196. if (level.mesh) {
  13197. level.mesh._preActivate();
  13198. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13199. }
  13200. if (this.onLODLevelSelection) {
  13201. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  13202. }
  13203. return level.mesh;
  13204. }
  13205. }
  13206. if (this.onLODLevelSelection) {
  13207. this.onLODLevelSelection(distanceToCamera, this, this);
  13208. }
  13209. return this;
  13210. };
  13211. Object.defineProperty(Mesh.prototype, "geometry", {
  13212. get: function () {
  13213. return this._geometry;
  13214. },
  13215. enumerable: true,
  13216. configurable: true
  13217. });
  13218. Mesh.prototype.getTotalVertices = function () {
  13219. if (!this._geometry) {
  13220. return 0;
  13221. }
  13222. return this._geometry.getTotalVertices();
  13223. };
  13224. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  13225. if (!this._geometry) {
  13226. return null;
  13227. }
  13228. return this._geometry.getVerticesData(kind, copyWhenShared);
  13229. };
  13230. Mesh.prototype.getVertexBuffer = function (kind) {
  13231. if (!this._geometry) {
  13232. return undefined;
  13233. }
  13234. return this._geometry.getVertexBuffer(kind);
  13235. };
  13236. Mesh.prototype.isVerticesDataPresent = function (kind) {
  13237. if (!this._geometry) {
  13238. if (this._delayInfo) {
  13239. return this._delayInfo.indexOf(kind) !== -1;
  13240. }
  13241. return false;
  13242. }
  13243. return this._geometry.isVerticesDataPresent(kind);
  13244. };
  13245. Mesh.prototype.getVerticesDataKinds = function () {
  13246. if (!this._geometry) {
  13247. var result = [];
  13248. if (this._delayInfo) {
  13249. for (var kind in this._delayInfo) {
  13250. result.push(kind);
  13251. }
  13252. }
  13253. return result;
  13254. }
  13255. return this._geometry.getVerticesDataKinds();
  13256. };
  13257. Mesh.prototype.getTotalIndices = function () {
  13258. if (!this._geometry) {
  13259. return 0;
  13260. }
  13261. return this._geometry.getTotalIndices();
  13262. };
  13263. Mesh.prototype.getIndices = function (copyWhenShared) {
  13264. if (!this._geometry) {
  13265. return [];
  13266. }
  13267. return this._geometry.getIndices(copyWhenShared);
  13268. };
  13269. Object.defineProperty(Mesh.prototype, "isBlocked", {
  13270. get: function () {
  13271. return this._masterMesh !== null && this._masterMesh !== undefined;
  13272. },
  13273. enumerable: true,
  13274. configurable: true
  13275. });
  13276. Mesh.prototype.isReady = function () {
  13277. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13278. return false;
  13279. }
  13280. return _super.prototype.isReady.call(this);
  13281. };
  13282. Mesh.prototype.isDisposed = function () {
  13283. return this._isDisposed;
  13284. };
  13285. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  13286. get: function () {
  13287. return this._sideOrientation;
  13288. },
  13289. set: function (sideO) {
  13290. this._sideOrientation = sideO;
  13291. },
  13292. enumerable: true,
  13293. configurable: true
  13294. });
  13295. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  13296. get: function () {
  13297. return this._areNormalsFrozen;
  13298. },
  13299. enumerable: true,
  13300. configurable: true
  13301. });
  13302. Mesh.prototype.freezeNormals = function () {
  13303. this._areNormalsFrozen = true;
  13304. };
  13305. Mesh.prototype.unfreezeNormals = function () {
  13306. this._areNormalsFrozen = false;
  13307. };
  13308. // Methods
  13309. Mesh.prototype._preActivate = function () {
  13310. var sceneRenderId = this.getScene().getRenderId();
  13311. if (this._preActivateId === sceneRenderId) {
  13312. return;
  13313. }
  13314. this._preActivateId = sceneRenderId;
  13315. this._visibleInstances = null;
  13316. };
  13317. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  13318. if (!this._visibleInstances) {
  13319. this._visibleInstances = {};
  13320. this._visibleInstances.defaultRenderId = renderId;
  13321. this._visibleInstances.selfDefaultRenderId = this._renderId;
  13322. }
  13323. if (!this._visibleInstances[renderId]) {
  13324. this._visibleInstances[renderId] = new Array();
  13325. }
  13326. this._visibleInstances[renderId].push(instance);
  13327. };
  13328. Mesh.prototype.refreshBoundingInfo = function () {
  13329. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13330. if (data) {
  13331. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  13332. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  13333. }
  13334. if (this.subMeshes) {
  13335. for (var index = 0; index < this.subMeshes.length; index++) {
  13336. this.subMeshes[index].refreshBoundingInfo();
  13337. }
  13338. }
  13339. this._updateBoundingInfo();
  13340. };
  13341. Mesh.prototype._createGlobalSubMesh = function () {
  13342. var totalVertices = this.getTotalVertices();
  13343. if (!totalVertices || !this.getIndices()) {
  13344. return null;
  13345. }
  13346. this.releaseSubMeshes();
  13347. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  13348. };
  13349. Mesh.prototype.subdivide = function (count) {
  13350. if (count < 1) {
  13351. return;
  13352. }
  13353. var totalIndices = this.getTotalIndices();
  13354. var subdivisionSize = (totalIndices / count) | 0;
  13355. var offset = 0;
  13356. while (subdivisionSize % 3 !== 0) {
  13357. subdivisionSize++;
  13358. }
  13359. this.releaseSubMeshes();
  13360. for (var index = 0; index < count; index++) {
  13361. if (offset >= totalIndices) {
  13362. break;
  13363. }
  13364. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  13365. offset += subdivisionSize;
  13366. }
  13367. this.synchronizeInstances();
  13368. };
  13369. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13370. if (kind instanceof Array) {
  13371. var temp = data;
  13372. data = kind;
  13373. kind = temp;
  13374. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  13375. }
  13376. if (!this._geometry) {
  13377. var vertexData = new BABYLON.VertexData();
  13378. vertexData.set(data, kind);
  13379. var scene = this.getScene();
  13380. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  13381. }
  13382. else {
  13383. this._geometry.setVerticesData(kind, data, updatable, stride);
  13384. }
  13385. };
  13386. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13387. if (!this._geometry) {
  13388. return;
  13389. }
  13390. if (!makeItUnique) {
  13391. this._geometry.updateVerticesData(kind, data, updateExtends);
  13392. }
  13393. else {
  13394. this.makeGeometryUnique();
  13395. this.updateVerticesData(kind, data, updateExtends, false);
  13396. }
  13397. };
  13398. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  13399. if (!this._geometry) {
  13400. return;
  13401. }
  13402. if (!makeItUnique) {
  13403. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  13404. }
  13405. else {
  13406. this.makeGeometryUnique();
  13407. this.updateVerticesDataDirectly(kind, data, offset, false);
  13408. }
  13409. };
  13410. // Mesh positions update function :
  13411. // updates the mesh positions according to the positionFunction returned values.
  13412. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  13413. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  13414. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  13415. if (computeNormals === void 0) { computeNormals = true; }
  13416. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13417. positionFunction(positions);
  13418. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  13419. if (computeNormals) {
  13420. var indices = this.getIndices();
  13421. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13422. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  13423. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  13424. }
  13425. };
  13426. Mesh.prototype.makeGeometryUnique = function () {
  13427. if (!this._geometry) {
  13428. return;
  13429. }
  13430. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  13431. geometry.applyToMesh(this);
  13432. };
  13433. Mesh.prototype.setIndices = function (indices, totalVertices) {
  13434. if (!this._geometry) {
  13435. var vertexData = new BABYLON.VertexData();
  13436. vertexData.indices = indices;
  13437. var scene = this.getScene();
  13438. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  13439. }
  13440. else {
  13441. this._geometry.setIndices(indices, totalVertices);
  13442. }
  13443. };
  13444. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  13445. var engine = this.getScene().getEngine();
  13446. // Wireframe
  13447. var indexToBind;
  13448. switch (fillMode) {
  13449. case BABYLON.Material.PointFillMode:
  13450. indexToBind = null;
  13451. break;
  13452. case BABYLON.Material.WireFrameFillMode:
  13453. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  13454. break;
  13455. default:
  13456. case BABYLON.Material.TriangleFillMode:
  13457. indexToBind = this._geometry.getIndexBuffer();
  13458. break;
  13459. }
  13460. // VBOs
  13461. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  13462. };
  13463. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  13464. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  13465. return;
  13466. }
  13467. var engine = this.getScene().getEngine();
  13468. switch (fillMode) {
  13469. case BABYLON.Material.PointFillMode:
  13470. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  13471. break;
  13472. case BABYLON.Material.WireFrameFillMode:
  13473. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  13474. break;
  13475. default:
  13476. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  13477. }
  13478. };
  13479. Mesh.prototype.registerBeforeRender = function (func) {
  13480. this._onBeforeRenderCallbacks.push(func);
  13481. };
  13482. Mesh.prototype.unregisterBeforeRender = function (func) {
  13483. var index = this._onBeforeRenderCallbacks.indexOf(func);
  13484. if (index > -1) {
  13485. this._onBeforeRenderCallbacks.splice(index, 1);
  13486. }
  13487. };
  13488. Mesh.prototype.registerAfterRender = function (func) {
  13489. this._onAfterRenderCallbacks.push(func);
  13490. };
  13491. Mesh.prototype.unregisterAfterRender = function (func) {
  13492. var index = this._onAfterRenderCallbacks.indexOf(func);
  13493. if (index > -1) {
  13494. this._onAfterRenderCallbacks.splice(index, 1);
  13495. }
  13496. };
  13497. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  13498. var scene = this.getScene();
  13499. this._batchCache.mustReturn = false;
  13500. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  13501. this._batchCache.visibleInstances[subMeshId] = null;
  13502. if (this._visibleInstances) {
  13503. var currentRenderId = scene.getRenderId();
  13504. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  13505. var selfRenderId = this._renderId;
  13506. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  13507. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  13508. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  13509. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  13510. }
  13511. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  13512. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  13513. this._batchCache.mustReturn = true;
  13514. return this._batchCache;
  13515. }
  13516. if (currentRenderId !== selfRenderId) {
  13517. this._batchCache.renderSelf[subMeshId] = false;
  13518. }
  13519. }
  13520. this._renderIdForInstances[subMeshId] = currentRenderId;
  13521. }
  13522. return this._batchCache;
  13523. };
  13524. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  13525. var visibleInstances = batch.visibleInstances[subMesh._id];
  13526. var matricesCount = visibleInstances.length + 1;
  13527. var bufferSize = matricesCount * 16 * 4;
  13528. while (this._instancesBufferSize < bufferSize) {
  13529. this._instancesBufferSize *= 2;
  13530. }
  13531. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  13532. if (this._worldMatricesInstancesBuffer) {
  13533. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  13534. }
  13535. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  13536. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  13537. }
  13538. var offset = 0;
  13539. var instancesCount = 0;
  13540. var world = this.getWorldMatrix();
  13541. if (batch.renderSelf[subMesh._id]) {
  13542. world.copyToArray(this._worldMatricesInstancesArray, offset);
  13543. offset += 16;
  13544. instancesCount++;
  13545. }
  13546. if (visibleInstances) {
  13547. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  13548. var instance = visibleInstances[instanceIndex];
  13549. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  13550. offset += 16;
  13551. instancesCount++;
  13552. }
  13553. }
  13554. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  13555. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  13556. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  13557. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  13558. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  13559. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  13560. this._draw(subMesh, fillMode, instancesCount);
  13561. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  13562. };
  13563. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  13564. var scene = this.getScene();
  13565. var engine = scene.getEngine();
  13566. if (hardwareInstancedRendering) {
  13567. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  13568. }
  13569. else {
  13570. if (batch.renderSelf[subMesh._id]) {
  13571. // Draw
  13572. if (onBeforeDraw) {
  13573. onBeforeDraw(false, this.getWorldMatrix());
  13574. }
  13575. this._draw(subMesh, fillMode);
  13576. }
  13577. if (batch.visibleInstances[subMesh._id]) {
  13578. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  13579. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  13580. // World
  13581. var world = instance.getWorldMatrix();
  13582. if (onBeforeDraw) {
  13583. onBeforeDraw(true, world);
  13584. }
  13585. // Draw
  13586. this._draw(subMesh, fillMode);
  13587. }
  13588. }
  13589. }
  13590. };
  13591. Mesh.prototype.render = function (subMesh) {
  13592. var scene = this.getScene();
  13593. // Managing instances
  13594. var batch = this._getInstancesRenderList(subMesh._id);
  13595. if (batch.mustReturn) {
  13596. return;
  13597. }
  13598. // Checking geometry state
  13599. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  13600. return;
  13601. }
  13602. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13603. this._onBeforeRenderCallbacks[callbackIndex](this);
  13604. }
  13605. var engine = scene.getEngine();
  13606. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  13607. // Material
  13608. var effectiveMaterial = subMesh.getMaterial();
  13609. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  13610. return;
  13611. }
  13612. // Outline - step 1
  13613. var savedDepthWrite = engine.getDepthWrite();
  13614. if (this.renderOutline) {
  13615. engine.setDepthWrite(false);
  13616. scene.getOutlineRenderer().render(subMesh, batch);
  13617. engine.setDepthWrite(savedDepthWrite);
  13618. }
  13619. effectiveMaterial._preBind();
  13620. var effect = effectiveMaterial.getEffect();
  13621. // Bind
  13622. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  13623. this._bind(subMesh, effect, fillMode);
  13624. var world = this.getWorldMatrix();
  13625. effectiveMaterial.bind(world, this);
  13626. // Draw
  13627. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  13628. if (isInstance) {
  13629. effectiveMaterial.bindOnlyWorldMatrix(world);
  13630. }
  13631. });
  13632. // Unbind
  13633. effectiveMaterial.unbind();
  13634. // Outline - step 2
  13635. if (this.renderOutline && savedDepthWrite) {
  13636. engine.setDepthWrite(true);
  13637. engine.setColorWrite(false);
  13638. scene.getOutlineRenderer().render(subMesh, batch);
  13639. engine.setColorWrite(true);
  13640. }
  13641. // Overlay
  13642. if (this.renderOverlay) {
  13643. var currentMode = engine.getAlphaMode();
  13644. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13645. scene.getOutlineRenderer().render(subMesh, batch, true);
  13646. engine.setAlphaMode(currentMode);
  13647. }
  13648. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13649. this._onAfterRenderCallbacks[callbackIndex](this);
  13650. }
  13651. };
  13652. Mesh.prototype.getEmittedParticleSystems = function () {
  13653. var results = new Array();
  13654. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  13655. var particleSystem = this.getScene().particleSystems[index];
  13656. if (particleSystem.emitter === this) {
  13657. results.push(particleSystem);
  13658. }
  13659. }
  13660. return results;
  13661. };
  13662. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  13663. var results = new Array();
  13664. var descendants = this.getDescendants();
  13665. descendants.push(this);
  13666. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  13667. var particleSystem = this.getScene().particleSystems[index];
  13668. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  13669. results.push(particleSystem);
  13670. }
  13671. }
  13672. return results;
  13673. };
  13674. Mesh.prototype.getChildren = function () {
  13675. var results = [];
  13676. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13677. var mesh = this.getScene().meshes[index];
  13678. if (mesh.parent === this) {
  13679. results.push(mesh);
  13680. }
  13681. }
  13682. return results;
  13683. };
  13684. Mesh.prototype._checkDelayState = function () {
  13685. var _this = this;
  13686. var that = this;
  13687. var scene = this.getScene();
  13688. if (this._geometry) {
  13689. this._geometry.load(scene);
  13690. }
  13691. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13692. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  13693. scene._addPendingData(that);
  13694. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  13695. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  13696. if (data instanceof ArrayBuffer) {
  13697. _this._delayLoadingFunction(data, _this);
  13698. }
  13699. else {
  13700. _this._delayLoadingFunction(JSON.parse(data), _this);
  13701. }
  13702. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13703. scene._removePendingData(_this);
  13704. }, function () {
  13705. }, scene.database, getBinaryData);
  13706. }
  13707. };
  13708. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  13709. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13710. return false;
  13711. }
  13712. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  13713. return false;
  13714. }
  13715. this._checkDelayState();
  13716. return true;
  13717. };
  13718. Mesh.prototype.setMaterialByID = function (id) {
  13719. var materials = this.getScene().materials;
  13720. for (var index = 0; index < materials.length; index++) {
  13721. if (materials[index].id === id) {
  13722. this.material = materials[index];
  13723. return;
  13724. }
  13725. }
  13726. // Multi
  13727. var multiMaterials = this.getScene().multiMaterials;
  13728. for (index = 0; index < multiMaterials.length; index++) {
  13729. if (multiMaterials[index].id === id) {
  13730. this.material = multiMaterials[index];
  13731. return;
  13732. }
  13733. }
  13734. };
  13735. Mesh.prototype.getAnimatables = function () {
  13736. var results = [];
  13737. if (this.material) {
  13738. results.push(this.material);
  13739. }
  13740. if (this.skeleton) {
  13741. results.push(this.skeleton);
  13742. }
  13743. return results;
  13744. };
  13745. // Geometry
  13746. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  13747. // Position
  13748. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  13749. return;
  13750. }
  13751. this._resetPointsArrayCache();
  13752. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13753. var temp = [];
  13754. for (var index = 0; index < data.length; index += 3) {
  13755. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  13756. }
  13757. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  13758. // Normals
  13759. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13760. return;
  13761. }
  13762. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13763. temp = [];
  13764. for (index = 0; index < data.length; index += 3) {
  13765. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  13766. }
  13767. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  13768. };
  13769. // Cache
  13770. Mesh.prototype._resetPointsArrayCache = function () {
  13771. this._positions = null;
  13772. };
  13773. Mesh.prototype._generatePointsArray = function () {
  13774. if (this._positions)
  13775. return true;
  13776. this._positions = [];
  13777. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13778. if (!data) {
  13779. return false;
  13780. }
  13781. for (var index = 0; index < data.length; index += 3) {
  13782. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  13783. }
  13784. return true;
  13785. };
  13786. // Clone
  13787. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13788. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  13789. };
  13790. // Dispose
  13791. Mesh.prototype.dispose = function (doNotRecurse) {
  13792. if (this._geometry) {
  13793. this._geometry.releaseForMesh(this, true);
  13794. }
  13795. // Instances
  13796. if (this._worldMatricesInstancesBuffer) {
  13797. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  13798. this._worldMatricesInstancesBuffer = null;
  13799. }
  13800. while (this.instances.length) {
  13801. this.instances[0].dispose();
  13802. }
  13803. _super.prototype.dispose.call(this, doNotRecurse);
  13804. };
  13805. // Geometric tools
  13806. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  13807. var _this = this;
  13808. var scene = this.getScene();
  13809. var onload = function (img) {
  13810. // Getting height map data
  13811. var canvas = document.createElement("canvas");
  13812. var context = canvas.getContext("2d");
  13813. var heightMapWidth = img.width;
  13814. var heightMapHeight = img.height;
  13815. canvas.width = heightMapWidth;
  13816. canvas.height = heightMapHeight;
  13817. context.drawImage(img, 0, 0);
  13818. // Create VertexData from map data
  13819. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  13820. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  13821. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  13822. //execute success callback, if set
  13823. if (onSuccess) {
  13824. onSuccess(_this);
  13825. }
  13826. };
  13827. BABYLON.Tools.LoadImage(url, onload, function () {
  13828. }, scene.database);
  13829. };
  13830. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  13831. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13832. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  13833. return;
  13834. }
  13835. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13836. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13837. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13838. var position = BABYLON.Vector3.Zero();
  13839. var normal = BABYLON.Vector3.Zero();
  13840. var uv = BABYLON.Vector2.Zero();
  13841. for (var index = 0; index < positions.length; index += 3) {
  13842. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  13843. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  13844. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  13845. // Compute height
  13846. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  13847. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  13848. var pos = (u + v * heightMapWidth) * 4;
  13849. var r = buffer[pos] / 255.0;
  13850. var g = buffer[pos + 1] / 255.0;
  13851. var b = buffer[pos + 2] / 255.0;
  13852. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  13853. normal.normalize();
  13854. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  13855. position = position.add(normal);
  13856. position.toArray(positions, index);
  13857. }
  13858. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  13859. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  13860. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  13861. };
  13862. Mesh.prototype.convertToFlatShadedMesh = function () {
  13863. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  13864. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  13865. var kinds = this.getVerticesDataKinds();
  13866. var vbs = [];
  13867. var data = [];
  13868. var newdata = [];
  13869. var updatableNormals = false;
  13870. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  13871. var kind = kinds[kindIndex];
  13872. var vertexBuffer = this.getVertexBuffer(kind);
  13873. if (kind === BABYLON.VertexBuffer.NormalKind) {
  13874. updatableNormals = vertexBuffer.isUpdatable();
  13875. kinds.splice(kindIndex, 1);
  13876. kindIndex--;
  13877. continue;
  13878. }
  13879. vbs[kind] = vertexBuffer;
  13880. data[kind] = vbs[kind].getData();
  13881. newdata[kind] = [];
  13882. }
  13883. // Save previous submeshes
  13884. var previousSubmeshes = this.subMeshes.slice(0);
  13885. var indices = this.getIndices();
  13886. var totalIndices = this.getTotalIndices();
  13887. for (var index = 0; index < totalIndices; index++) {
  13888. var vertexIndex = indices[index];
  13889. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  13890. kind = kinds[kindIndex];
  13891. var stride = vbs[kind].getStrideSize();
  13892. for (var offset = 0; offset < stride; offset++) {
  13893. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  13894. }
  13895. }
  13896. }
  13897. // Updating faces & normal
  13898. var normals = [];
  13899. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  13900. for (index = 0; index < totalIndices; index += 3) {
  13901. indices[index] = index;
  13902. indices[index + 1] = index + 1;
  13903. indices[index + 2] = index + 2;
  13904. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  13905. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  13906. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  13907. var p1p2 = p1.subtract(p2);
  13908. var p3p2 = p3.subtract(p2);
  13909. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  13910. for (var localIndex = 0; localIndex < 3; localIndex++) {
  13911. normals.push(normal.x);
  13912. normals.push(normal.y);
  13913. normals.push(normal.z);
  13914. }
  13915. }
  13916. this.setIndices(indices);
  13917. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  13918. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  13919. kind = kinds[kindIndex];
  13920. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  13921. }
  13922. // Updating submeshes
  13923. this.releaseSubMeshes();
  13924. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  13925. var previousOne = previousSubmeshes[submeshIndex];
  13926. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  13927. }
  13928. this.synchronizeInstances();
  13929. };
  13930. // Instances
  13931. Mesh.prototype.createInstance = function (name) {
  13932. return new BABYLON.InstancedMesh(name, this);
  13933. };
  13934. Mesh.prototype.synchronizeInstances = function () {
  13935. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  13936. var instance = this.instances[instanceIndex];
  13937. instance._syncSubMeshes();
  13938. }
  13939. };
  13940. /**
  13941. * Simplify the mesh according to the given array of settings.
  13942. * Function will return immediately and will simplify async.
  13943. * @param settings a collection of simplification settings.
  13944. * @param parallelProcessing should all levels calculate parallel or one after the other.
  13945. * @param type the type of simplification to run.
  13946. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  13947. */
  13948. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  13949. if (parallelProcessing === void 0) { parallelProcessing = true; }
  13950. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  13951. this.getScene().simplificationQueue.addTask({
  13952. settings: settings,
  13953. parallelProcessing: parallelProcessing,
  13954. mesh: this,
  13955. simplificationType: simplificationType,
  13956. successCallback: successCallback
  13957. });
  13958. };
  13959. /**
  13960. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  13961. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  13962. * This should be used together with the simplification to avoid disappearing triangles.
  13963. * @param successCallback an optional success callback to be called after the optimization finished.
  13964. */
  13965. Mesh.prototype.optimizeIndices = function (successCallback) {
  13966. var _this = this;
  13967. var indices = this.getIndices();
  13968. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13969. var vectorPositions = [];
  13970. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  13971. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  13972. }
  13973. var dupes = [];
  13974. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  13975. var realPos = vectorPositions.length - 1 - iteration;
  13976. var testedPosition = vectorPositions[realPos];
  13977. for (var j = 0; j < realPos; ++j) {
  13978. var againstPosition = vectorPositions[j];
  13979. if (testedPosition.equals(againstPosition)) {
  13980. dupes[realPos] = j;
  13981. break;
  13982. }
  13983. }
  13984. }, function () {
  13985. for (var i = 0; i < indices.length; ++i) {
  13986. indices[i] = dupes[indices[i]] || indices[i];
  13987. }
  13988. //indices are now reordered
  13989. var originalSubMeshes = _this.subMeshes.slice(0);
  13990. _this.setIndices(indices);
  13991. _this.subMeshes = originalSubMeshes;
  13992. if (successCallback) {
  13993. successCallback(_this);
  13994. }
  13995. });
  13996. };
  13997. // Statics
  13998. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  13999. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14000. if (ribbonInstance === void 0) { ribbonInstance = null; }
  14001. if (ribbonInstance) {
  14002. // positionFunction : ribbon case
  14003. // only pathArray and sideOrientation parameters are taken into account for positions update
  14004. var positionsOfRibbon = function (pathArray, sideOrientation) {
  14005. var positionFunction = function (positions) {
  14006. var minlg = pathArray[0].length;
  14007. var i = 0;
  14008. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  14009. for (var si = 1; si <= ns; si++) {
  14010. for (var p = 0; p < pathArray.length; p++) {
  14011. var path = pathArray[p];
  14012. var l = path.length;
  14013. minlg = (minlg < l) ? minlg : l;
  14014. var j = 0;
  14015. while (j < minlg) {
  14016. positions[i] = path[j].x;
  14017. positions[i + 1] = path[j].y;
  14018. positions[i + 2] = path[j].z;
  14019. j++;
  14020. i += 3;
  14021. }
  14022. }
  14023. }
  14024. };
  14025. return positionFunction;
  14026. };
  14027. var sideOrientation = ribbonInstance.sideOrientation;
  14028. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  14029. var computeNormals = !(ribbonInstance.areNormalsFrozen);
  14030. ribbonInstance.updateMeshPositions(positionFunction, computeNormals);
  14031. return ribbonInstance;
  14032. }
  14033. else {
  14034. var ribbon = new Mesh(name, scene);
  14035. ribbon.sideOrientation = sideOrientation;
  14036. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  14037. vertexData.applyToMesh(ribbon, updatable);
  14038. return ribbon;
  14039. }
  14040. };
  14041. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  14042. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14043. var disc = new Mesh(name, scene);
  14044. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  14045. vertexData.applyToMesh(disc, updatable);
  14046. return disc;
  14047. };
  14048. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  14049. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14050. var box = new Mesh(name, scene);
  14051. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  14052. vertexData.applyToMesh(box, updatable);
  14053. return box;
  14054. };
  14055. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  14056. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14057. var sphere = new Mesh(name, scene);
  14058. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  14059. vertexData.applyToMesh(sphere, updatable);
  14060. return sphere;
  14061. };
  14062. // Cylinder and cone (Code inspired by SharpDX.org)
  14063. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  14064. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14065. // subdivisions is a new parameter, we need to support old signature
  14066. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  14067. if (scene !== undefined) {
  14068. updatable = scene;
  14069. }
  14070. scene = subdivisions;
  14071. subdivisions = 1;
  14072. }
  14073. var cylinder = new Mesh(name, scene);
  14074. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  14075. vertexData.applyToMesh(cylinder, updatable);
  14076. return cylinder;
  14077. };
  14078. // Torus (Code from SharpDX.org)
  14079. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  14080. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14081. var torus = new Mesh(name, scene);
  14082. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  14083. vertexData.applyToMesh(torus, updatable);
  14084. return torus;
  14085. };
  14086. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  14087. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14088. var torusKnot = new Mesh(name, scene);
  14089. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  14090. vertexData.applyToMesh(torusKnot, updatable);
  14091. return torusKnot;
  14092. };
  14093. // Lines
  14094. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  14095. if (linesInstance === void 0) { linesInstance = null; }
  14096. if (linesInstance) {
  14097. var positionsOfLines = function (points) {
  14098. var positionFunction = function (positions) {
  14099. var i = 0;
  14100. for (var p = 0; p < points.length; p++) {
  14101. positions[i] = points[p].x;
  14102. positions[i + 1] = points[p].y;
  14103. positions[i + 2] = points[p].z;
  14104. i += 3;
  14105. }
  14106. };
  14107. return positionFunction;
  14108. };
  14109. var positionFunction = positionsOfLines(points);
  14110. linesInstance.updateMeshPositions(positionFunction, false);
  14111. return linesInstance;
  14112. }
  14113. // lines creation
  14114. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  14115. var vertexData = BABYLON.VertexData.CreateLines(points);
  14116. vertexData.applyToMesh(lines, updatable);
  14117. return lines;
  14118. };
  14119. // Extrusion
  14120. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  14121. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14122. if (extrudedInstance === void 0) { extrudedInstance = null; }
  14123. scale = scale || 1;
  14124. rotation = rotation || 0;
  14125. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  14126. return extruded;
  14127. };
  14128. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  14129. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14130. if (extrudedInstance === void 0) { extrudedInstance = null; }
  14131. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  14132. return extrudedCustom;
  14133. };
  14134. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  14135. // extrusion geometry
  14136. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  14137. var tangents = path3D.getTangents();
  14138. var normals = path3D.getNormals();
  14139. var binormals = path3D.getBinormals();
  14140. var distances = path3D.getDistances();
  14141. var angle = 0;
  14142. var returnScale = function (i, distance) {
  14143. return scale;
  14144. };
  14145. var returnRotation = function (i, distance) {
  14146. return rotation;
  14147. };
  14148. var rotate = custom ? rotateFunction : returnRotation;
  14149. var scl = custom ? scaleFunction : returnScale;
  14150. var index = 0;
  14151. for (var i = 0; i < curve.length; i++) {
  14152. var shapePath = new Array();
  14153. var angleStep = rotate(i, distances[i]);
  14154. var scaleRatio = scl(i, distances[i]);
  14155. for (var p = 0; p < shape.length; p++) {
  14156. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  14157. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  14158. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  14159. shapePath.push(rotated);
  14160. }
  14161. shapePaths[index] = shapePath;
  14162. angle += angleStep;
  14163. index++;
  14164. }
  14165. // cap
  14166. var capPath = function (shapePath) {
  14167. var pointCap = Array();
  14168. var barycenter = BABYLON.Vector3.Zero();
  14169. var i;
  14170. for (i = 0; i < shapePath.length; i++) {
  14171. barycenter.addInPlace(shapePath[i]);
  14172. }
  14173. barycenter.scaleInPlace(1 / shapePath.length);
  14174. for (i = 0; i < shapePath.length; i++) {
  14175. pointCap.push(barycenter);
  14176. }
  14177. return pointCap;
  14178. };
  14179. switch (cap) {
  14180. case BABYLON.Mesh.NO_CAP:
  14181. break;
  14182. case BABYLON.Mesh.CAP_START:
  14183. shapePaths.unshift(capPath(shapePaths[0]));
  14184. break;
  14185. case BABYLON.Mesh.CAP_END:
  14186. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  14187. break;
  14188. case BABYLON.Mesh.CAP_ALL:
  14189. shapePaths.unshift(capPath(shapePaths[0]));
  14190. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  14191. break;
  14192. default:
  14193. break;
  14194. }
  14195. return shapePaths;
  14196. };
  14197. if (instance) {
  14198. var path3D = (instance.path3D).update(curve);
  14199. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  14200. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  14201. return instance;
  14202. }
  14203. // extruded shape creation
  14204. var path3D = new BABYLON.Path3D(curve);
  14205. var newShapePaths = new Array();
  14206. cap = (cap < 0 || cap > 3) ? 0 : cap;
  14207. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  14208. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  14209. extrudedGeneric.pathArray = pathArray;
  14210. extrudedGeneric.path3D = path3D;
  14211. extrudedGeneric.cap = cap;
  14212. return extrudedGeneric;
  14213. };
  14214. // Plane & ground
  14215. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  14216. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14217. var plane = new Mesh(name, scene);
  14218. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  14219. vertexData.applyToMesh(plane, updatable);
  14220. return plane;
  14221. };
  14222. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  14223. var ground = new BABYLON.GroundMesh(name, scene);
  14224. ground._setReady(false);
  14225. ground._subdivisions = subdivisions;
  14226. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  14227. vertexData.applyToMesh(ground, updatable);
  14228. ground._setReady(true);
  14229. return ground;
  14230. };
  14231. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  14232. var tiledGround = new Mesh(name, scene);
  14233. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  14234. vertexData.applyToMesh(tiledGround, updatable);
  14235. return tiledGround;
  14236. };
  14237. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  14238. var ground = new BABYLON.GroundMesh(name, scene);
  14239. ground._subdivisions = subdivisions;
  14240. ground._setReady(false);
  14241. var onload = function (img) {
  14242. // Getting height map data
  14243. var canvas = document.createElement("canvas");
  14244. var context = canvas.getContext("2d");
  14245. var heightMapWidth = img.width;
  14246. var heightMapHeight = img.height;
  14247. canvas.width = heightMapWidth;
  14248. canvas.height = heightMapHeight;
  14249. context.drawImage(img, 0, 0);
  14250. // Create VertexData from map data
  14251. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14252. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14253. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  14254. vertexData.applyToMesh(ground, updatable);
  14255. ground._setReady(true);
  14256. //execute ready callback, if set
  14257. if (onReady) {
  14258. onReady(ground);
  14259. }
  14260. };
  14261. BABYLON.Tools.LoadImage(url, onload, function () {
  14262. }, scene.database);
  14263. return ground;
  14264. };
  14265. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  14266. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14267. if (tubeInstance === void 0) { tubeInstance = null; }
  14268. // tube geometry
  14269. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  14270. var tangents = path3D.getTangents();
  14271. var normals = path3D.getNormals();
  14272. var distances = path3D.getDistances();
  14273. var pi2 = Math.PI * 2;
  14274. var step = pi2 / tessellation;
  14275. var returnRadius = function (i, distance) { return radius; };
  14276. var radiusFunctionFinal = radiusFunction || returnRadius;
  14277. var circlePath;
  14278. var rad;
  14279. var normal;
  14280. var rotated;
  14281. var rotationMatrix;
  14282. var index = 0;
  14283. for (var i = 0; i < path.length; i++) {
  14284. rad = radiusFunctionFinal(i, distances[i]); // current radius
  14285. circlePath = Array(); // current circle array
  14286. normal = normals[i]; // current normal
  14287. for (var t = 0; t < tessellation; t++) {
  14288. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  14289. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  14290. circlePath.push(rotated);
  14291. }
  14292. circlePath.push(circlePath[0]);
  14293. circlePaths[index] = circlePath;
  14294. index++;
  14295. }
  14296. // cap
  14297. var capPath = function (nbPoints, pathIndex) {
  14298. var pointCap = Array();
  14299. for (var i = 0; i < nbPoints; i++) {
  14300. pointCap.push(path[pathIndex]);
  14301. }
  14302. return pointCap;
  14303. };
  14304. switch (cap) {
  14305. case BABYLON.Mesh.NO_CAP:
  14306. break;
  14307. case BABYLON.Mesh.CAP_START:
  14308. circlePaths.unshift(capPath(tessellation + 1, 0));
  14309. break;
  14310. case BABYLON.Mesh.CAP_END:
  14311. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  14312. break;
  14313. case BABYLON.Mesh.CAP_ALL:
  14314. circlePaths.unshift(capPath(tessellation + 1, 0));
  14315. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  14316. break;
  14317. default:
  14318. break;
  14319. }
  14320. return circlePaths;
  14321. };
  14322. if (tubeInstance) {
  14323. var path3D = (tubeInstance.path3D).update(path);
  14324. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  14325. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  14326. return tubeInstance;
  14327. }
  14328. // tube creation
  14329. var path3D = new BABYLON.Path3D(path);
  14330. var newPathArray = new Array();
  14331. cap = (cap < 0 || cap > 3) ? 0 : cap;
  14332. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  14333. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  14334. tube.pathArray = pathArray;
  14335. tube.path3D = path3D;
  14336. tube.tessellation = tessellation;
  14337. tube.cap = cap;
  14338. return tube;
  14339. };
  14340. // Decals
  14341. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  14342. if (angle === void 0) { angle = 0; }
  14343. var indices = sourceMesh.getIndices();
  14344. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14345. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14346. // Getting correct rotation
  14347. if (!normal) {
  14348. var target = new BABYLON.Vector3(0, 0, 1);
  14349. var camera = sourceMesh.getScene().activeCamera;
  14350. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  14351. normal = camera.globalPosition.subtract(cameraWorldTarget);
  14352. }
  14353. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  14354. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  14355. var pitch = Math.atan2(normal.y, len);
  14356. // Matrix
  14357. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  14358. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  14359. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  14360. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  14361. var vertexData = new BABYLON.VertexData();
  14362. vertexData.indices = [];
  14363. vertexData.positions = [];
  14364. vertexData.normals = [];
  14365. vertexData.uvs = [];
  14366. var currentVertexDataIndex = 0;
  14367. var extractDecalVector3 = function (indexId) {
  14368. var vertexId = indices[indexId];
  14369. var result = new BABYLON.PositionNormalVertex();
  14370. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  14371. // Send vector to decal local world
  14372. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  14373. // Get normal
  14374. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  14375. return result;
  14376. };
  14377. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  14378. var clip = function (vertices, axis) {
  14379. if (vertices.length === 0) {
  14380. return vertices;
  14381. }
  14382. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  14383. var clipVertices = function (v0, v1) {
  14384. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  14385. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  14386. };
  14387. var result = new Array();
  14388. for (var index = 0; index < vertices.length; index += 3) {
  14389. var v1Out;
  14390. var v2Out;
  14391. var v3Out;
  14392. var total = 0;
  14393. var nV1, nV2, nV3, nV4;
  14394. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  14395. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  14396. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  14397. v1Out = d1 > 0;
  14398. v2Out = d2 > 0;
  14399. v3Out = d3 > 0;
  14400. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  14401. switch (total) {
  14402. case 0:
  14403. result.push(vertices[index]);
  14404. result.push(vertices[index + 1]);
  14405. result.push(vertices[index + 2]);
  14406. break;
  14407. case 1:
  14408. if (v1Out) {
  14409. nV1 = vertices[index + 1];
  14410. nV2 = vertices[index + 2];
  14411. nV3 = clipVertices(vertices[index], nV1);
  14412. nV4 = clipVertices(vertices[index], nV2);
  14413. }
  14414. if (v2Out) {
  14415. nV1 = vertices[index];
  14416. nV2 = vertices[index + 2];
  14417. nV3 = clipVertices(vertices[index + 1], nV1);
  14418. nV4 = clipVertices(vertices[index + 1], nV2);
  14419. result.push(nV3);
  14420. result.push(nV2.clone());
  14421. result.push(nV1.clone());
  14422. result.push(nV2.clone());
  14423. result.push(nV3.clone());
  14424. result.push(nV4);
  14425. break;
  14426. }
  14427. if (v3Out) {
  14428. nV1 = vertices[index];
  14429. nV2 = vertices[index + 1];
  14430. nV3 = clipVertices(vertices[index + 2], nV1);
  14431. nV4 = clipVertices(vertices[index + 2], nV2);
  14432. }
  14433. result.push(nV1.clone());
  14434. result.push(nV2.clone());
  14435. result.push(nV3);
  14436. result.push(nV4);
  14437. result.push(nV3.clone());
  14438. result.push(nV2.clone());
  14439. break;
  14440. case 2:
  14441. if (!v1Out) {
  14442. nV1 = vertices[index].clone();
  14443. nV2 = clipVertices(nV1, vertices[index + 1]);
  14444. nV3 = clipVertices(nV1, vertices[index + 2]);
  14445. result.push(nV1);
  14446. result.push(nV2);
  14447. result.push(nV3);
  14448. }
  14449. if (!v2Out) {
  14450. nV1 = vertices[index + 1].clone();
  14451. nV2 = clipVertices(nV1, vertices[index + 2]);
  14452. nV3 = clipVertices(nV1, vertices[index]);
  14453. result.push(nV1);
  14454. result.push(nV2);
  14455. result.push(nV3);
  14456. }
  14457. if (!v3Out) {
  14458. nV1 = vertices[index + 2].clone();
  14459. nV2 = clipVertices(nV1, vertices[index]);
  14460. nV3 = clipVertices(nV1, vertices[index + 1]);
  14461. result.push(nV1);
  14462. result.push(nV2);
  14463. result.push(nV3);
  14464. }
  14465. break;
  14466. case 3:
  14467. break;
  14468. }
  14469. }
  14470. return result;
  14471. };
  14472. for (var index = 0; index < indices.length; index += 3) {
  14473. var faceVertices = new Array();
  14474. faceVertices.push(extractDecalVector3(index));
  14475. faceVertices.push(extractDecalVector3(index + 1));
  14476. faceVertices.push(extractDecalVector3(index + 2));
  14477. // Clip
  14478. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  14479. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  14480. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  14481. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  14482. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  14483. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  14484. if (faceVertices.length === 0) {
  14485. continue;
  14486. }
  14487. // Add UVs and get back to world
  14488. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  14489. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  14490. var vertex = faceVertices[vIndex];
  14491. vertexData.indices.push(currentVertexDataIndex);
  14492. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  14493. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  14494. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  14495. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  14496. currentVertexDataIndex++;
  14497. }
  14498. }
  14499. // Return mesh
  14500. var decal = new Mesh(name, sourceMesh.getScene());
  14501. vertexData.applyToMesh(decal);
  14502. decal.position = position.clone();
  14503. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  14504. return decal;
  14505. };
  14506. // Tools
  14507. Mesh.MinMax = function (meshes) {
  14508. var minVector = null;
  14509. var maxVector = null;
  14510. for (var i in meshes) {
  14511. var mesh = meshes[i];
  14512. var boundingBox = mesh.getBoundingInfo().boundingBox;
  14513. if (!minVector) {
  14514. minVector = boundingBox.minimumWorld;
  14515. maxVector = boundingBox.maximumWorld;
  14516. continue;
  14517. }
  14518. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  14519. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  14520. }
  14521. return {
  14522. min: minVector,
  14523. max: maxVector
  14524. };
  14525. };
  14526. Mesh.Center = function (meshesOrMinMaxVector) {
  14527. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  14528. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  14529. };
  14530. /**
  14531. * Merge the array of meshes into a single mesh for performance reasons.
  14532. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  14533. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  14534. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  14535. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  14536. */
  14537. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  14538. if (disposeSource === void 0) { disposeSource = true; }
  14539. if (!allow32BitsIndices) {
  14540. var totalVertices = 0;
  14541. for (var index = 0; index < meshes.length; index++) {
  14542. if (meshes[index]) {
  14543. totalVertices += meshes[index].getTotalVertices();
  14544. if (totalVertices > 65536) {
  14545. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  14546. return null;
  14547. }
  14548. }
  14549. }
  14550. }
  14551. // Merge
  14552. var vertexData;
  14553. var otherVertexData;
  14554. var source;
  14555. for (index = 0; index < meshes.length; index++) {
  14556. if (meshes[index]) {
  14557. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  14558. otherVertexData.transform(meshes[index].getWorldMatrix());
  14559. if (vertexData) {
  14560. vertexData.merge(otherVertexData);
  14561. }
  14562. else {
  14563. vertexData = otherVertexData;
  14564. source = meshes[index];
  14565. }
  14566. }
  14567. }
  14568. if (!meshSubclass) {
  14569. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  14570. }
  14571. vertexData.applyToMesh(meshSubclass);
  14572. // Setting properties
  14573. meshSubclass.material = source.material;
  14574. meshSubclass.checkCollisions = source.checkCollisions;
  14575. // Cleaning
  14576. if (disposeSource) {
  14577. for (index = 0; index < meshes.length; index++) {
  14578. if (meshes[index]) {
  14579. meshes[index].dispose();
  14580. }
  14581. }
  14582. }
  14583. return meshSubclass;
  14584. };
  14585. // Consts
  14586. Mesh._FRONTSIDE = 0;
  14587. Mesh._BACKSIDE = 1;
  14588. Mesh._DOUBLESIDE = 2;
  14589. Mesh._DEFAULTSIDE = 0;
  14590. Mesh._NO_CAP = 0;
  14591. Mesh._CAP_START = 1;
  14592. Mesh._CAP_END = 2;
  14593. Mesh._CAP_ALL = 3;
  14594. return Mesh;
  14595. })(BABYLON.AbstractMesh);
  14596. BABYLON.Mesh = Mesh;
  14597. })(BABYLON || (BABYLON = {}));
  14598. //# sourceMappingURL=babylon.mesh.js.map
  14599. var BABYLON;
  14600. (function (BABYLON) {
  14601. var SubMesh = (function () {
  14602. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  14603. if (createBoundingBox === void 0) { createBoundingBox = true; }
  14604. this.materialIndex = materialIndex;
  14605. this.verticesStart = verticesStart;
  14606. this.verticesCount = verticesCount;
  14607. this.indexStart = indexStart;
  14608. this.indexCount = indexCount;
  14609. this._renderId = 0;
  14610. this._mesh = mesh;
  14611. this._renderingMesh = renderingMesh || mesh;
  14612. mesh.subMeshes.push(this);
  14613. this._trianglePlanes = [];
  14614. this._id = mesh.subMeshes.length - 1;
  14615. if (createBoundingBox) {
  14616. this.refreshBoundingInfo();
  14617. mesh.computeWorldMatrix(true);
  14618. }
  14619. }
  14620. SubMesh.prototype.getBoundingInfo = function () {
  14621. return this._boundingInfo;
  14622. };
  14623. SubMesh.prototype.getMesh = function () {
  14624. return this._mesh;
  14625. };
  14626. SubMesh.prototype.getRenderingMesh = function () {
  14627. return this._renderingMesh;
  14628. };
  14629. SubMesh.prototype.getMaterial = function () {
  14630. var rootMaterial = this._renderingMesh.material;
  14631. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  14632. var multiMaterial = rootMaterial;
  14633. return multiMaterial.getSubMaterial(this.materialIndex);
  14634. }
  14635. if (!rootMaterial) {
  14636. return this._mesh.getScene().defaultMaterial;
  14637. }
  14638. return rootMaterial;
  14639. };
  14640. // Methods
  14641. SubMesh.prototype.refreshBoundingInfo = function () {
  14642. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14643. if (!data) {
  14644. this._boundingInfo = this._mesh._boundingInfo;
  14645. return;
  14646. }
  14647. var indices = this._renderingMesh.getIndices();
  14648. var extend;
  14649. if (this.indexStart === 0 && this.indexCount === indices.length) {
  14650. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  14651. }
  14652. else {
  14653. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  14654. }
  14655. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14656. };
  14657. SubMesh.prototype._checkCollision = function (collider) {
  14658. return this._boundingInfo._checkCollision(collider);
  14659. };
  14660. SubMesh.prototype.updateBoundingInfo = function (world) {
  14661. if (!this._boundingInfo) {
  14662. this.refreshBoundingInfo();
  14663. }
  14664. this._boundingInfo._update(world);
  14665. };
  14666. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  14667. return this._boundingInfo.isInFrustum(frustumPlanes);
  14668. };
  14669. SubMesh.prototype.render = function () {
  14670. this._renderingMesh.render(this);
  14671. };
  14672. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  14673. if (!this._linesIndexBuffer) {
  14674. var linesIndices = [];
  14675. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  14676. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  14677. }
  14678. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  14679. this.linesIndexCount = linesIndices.length;
  14680. }
  14681. return this._linesIndexBuffer;
  14682. };
  14683. SubMesh.prototype.canIntersects = function (ray) {
  14684. return ray.intersectsBox(this._boundingInfo.boundingBox);
  14685. };
  14686. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  14687. var intersectInfo = null;
  14688. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  14689. var p0 = positions[indices[index]];
  14690. var p1 = positions[indices[index + 1]];
  14691. var p2 = positions[indices[index + 2]];
  14692. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  14693. if (currentIntersectInfo) {
  14694. if (currentIntersectInfo.distance < 0) {
  14695. continue;
  14696. }
  14697. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14698. intersectInfo = currentIntersectInfo;
  14699. intersectInfo.faceId = index / 3;
  14700. if (fastCheck) {
  14701. break;
  14702. }
  14703. }
  14704. }
  14705. }
  14706. return intersectInfo;
  14707. };
  14708. // Clone
  14709. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  14710. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  14711. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  14712. return result;
  14713. };
  14714. // Dispose
  14715. SubMesh.prototype.dispose = function () {
  14716. if (this._linesIndexBuffer) {
  14717. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  14718. this._linesIndexBuffer = null;
  14719. }
  14720. // Remove from mesh
  14721. var index = this._mesh.subMeshes.indexOf(this);
  14722. this._mesh.subMeshes.splice(index, 1);
  14723. };
  14724. // Statics
  14725. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  14726. var minVertexIndex = Number.MAX_VALUE;
  14727. var maxVertexIndex = -Number.MAX_VALUE;
  14728. renderingMesh = renderingMesh || mesh;
  14729. var indices = renderingMesh.getIndices();
  14730. for (var index = startIndex; index < startIndex + indexCount; index++) {
  14731. var vertexIndex = indices[index];
  14732. if (vertexIndex < minVertexIndex)
  14733. minVertexIndex = vertexIndex;
  14734. if (vertexIndex > maxVertexIndex)
  14735. maxVertexIndex = vertexIndex;
  14736. }
  14737. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  14738. };
  14739. return SubMesh;
  14740. })();
  14741. BABYLON.SubMesh = SubMesh;
  14742. })(BABYLON || (BABYLON = {}));
  14743. //# sourceMappingURL=babylon.subMesh.js.map
  14744. var BABYLON;
  14745. (function (BABYLON) {
  14746. var BaseTexture = (function () {
  14747. function BaseTexture(scene) {
  14748. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14749. this.hasAlpha = false;
  14750. this.getAlphaFromRGB = false;
  14751. this.level = 1;
  14752. this.isCube = false;
  14753. this.isRenderTarget = false;
  14754. this.animations = new Array();
  14755. this.coordinatesIndex = 0;
  14756. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  14757. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  14758. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  14759. this.anisotropicFilteringLevel = 4;
  14760. this._scene = scene;
  14761. this._scene.textures.push(this);
  14762. }
  14763. BaseTexture.prototype.getScene = function () {
  14764. return this._scene;
  14765. };
  14766. BaseTexture.prototype.getTextureMatrix = function () {
  14767. return null;
  14768. };
  14769. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  14770. return null;
  14771. };
  14772. BaseTexture.prototype.getInternalTexture = function () {
  14773. return this._texture;
  14774. };
  14775. BaseTexture.prototype.isReady = function () {
  14776. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14777. return true;
  14778. }
  14779. if (this._texture) {
  14780. return this._texture.isReady;
  14781. }
  14782. return false;
  14783. };
  14784. BaseTexture.prototype.getSize = function () {
  14785. if (this._texture._width) {
  14786. return { width: this._texture._width, height: this._texture._height };
  14787. }
  14788. if (this._texture._size) {
  14789. return { width: this._texture._size, height: this._texture._size };
  14790. }
  14791. return { width: 0, height: 0 };
  14792. };
  14793. BaseTexture.prototype.getBaseSize = function () {
  14794. if (!this.isReady())
  14795. return { width: 0, height: 0 };
  14796. if (this._texture._size) {
  14797. return { width: this._texture._size, height: this._texture._size };
  14798. }
  14799. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  14800. };
  14801. BaseTexture.prototype.scale = function (ratio) {
  14802. };
  14803. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  14804. get: function () {
  14805. return false;
  14806. },
  14807. enumerable: true,
  14808. configurable: true
  14809. });
  14810. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  14811. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  14812. for (var index = 0; index < texturesCache.length; index++) {
  14813. var texturesCacheEntry = texturesCache[index];
  14814. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  14815. texturesCache.splice(index, 1);
  14816. return;
  14817. }
  14818. }
  14819. };
  14820. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  14821. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  14822. for (var index = 0; index < texturesCache.length; index++) {
  14823. var texturesCacheEntry = texturesCache[index];
  14824. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  14825. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  14826. texturesCacheEntry.references++;
  14827. return texturesCacheEntry;
  14828. }
  14829. }
  14830. }
  14831. return null;
  14832. };
  14833. BaseTexture.prototype.delayLoad = function () {
  14834. };
  14835. BaseTexture.prototype.releaseInternalTexture = function () {
  14836. if (!this._texture) {
  14837. return;
  14838. }
  14839. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  14840. this._texture.references--;
  14841. // Final reference ?
  14842. if (this._texture.references === 0) {
  14843. var index = texturesCache.indexOf(this._texture);
  14844. texturesCache.splice(index, 1);
  14845. this._scene.getEngine()._releaseTexture(this._texture);
  14846. delete this._texture;
  14847. }
  14848. };
  14849. BaseTexture.prototype.clone = function () {
  14850. return null;
  14851. };
  14852. BaseTexture.prototype.dispose = function () {
  14853. // Remove from scene
  14854. var index = this._scene.textures.indexOf(this);
  14855. if (index >= 0) {
  14856. this._scene.textures.splice(index, 1);
  14857. }
  14858. if (this._texture === undefined) {
  14859. return;
  14860. }
  14861. this.releaseInternalTexture();
  14862. // Callback
  14863. if (this.onDispose) {
  14864. this.onDispose();
  14865. }
  14866. };
  14867. return BaseTexture;
  14868. })();
  14869. BABYLON.BaseTexture = BaseTexture;
  14870. })(BABYLON || (BABYLON = {}));
  14871. //# sourceMappingURL=babylon.baseTexture.js.map
  14872. var __extends = this.__extends || function (d, b) {
  14873. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14874. function __() { this.constructor = d; }
  14875. __.prototype = b.prototype;
  14876. d.prototype = new __();
  14877. };
  14878. var BABYLON;
  14879. (function (BABYLON) {
  14880. var Texture = (function (_super) {
  14881. __extends(Texture, _super);
  14882. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  14883. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  14884. if (onLoad === void 0) { onLoad = null; }
  14885. if (onError === void 0) { onError = null; }
  14886. if (buffer === void 0) { buffer = null; }
  14887. if (deleteBuffer === void 0) { deleteBuffer = false; }
  14888. _super.call(this, scene);
  14889. this.uOffset = 0;
  14890. this.vOffset = 0;
  14891. this.uScale = 1.0;
  14892. this.vScale = 1.0;
  14893. this.uAng = 0;
  14894. this.vAng = 0;
  14895. this.wAng = 0;
  14896. this.name = url;
  14897. this.url = url;
  14898. this._noMipmap = noMipmap;
  14899. this._invertY = invertY;
  14900. this._samplingMode = samplingMode;
  14901. this._buffer = buffer;
  14902. this._deleteBuffer = deleteBuffer;
  14903. if (!url) {
  14904. return;
  14905. }
  14906. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  14907. if (!this._texture) {
  14908. if (!scene.useDelayedTextureLoading) {
  14909. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  14910. if (deleteBuffer) {
  14911. delete this._buffer;
  14912. }
  14913. }
  14914. else {
  14915. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14916. }
  14917. }
  14918. }
  14919. Texture.prototype.delayLoad = function () {
  14920. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14921. return;
  14922. }
  14923. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14924. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  14925. if (!this._texture) {
  14926. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  14927. if (this._deleteBuffer) {
  14928. delete this._buffer;
  14929. }
  14930. }
  14931. };
  14932. Texture.prototype.updateSamplingMode = function (samplingMode) {
  14933. if (!this._texture) {
  14934. return;
  14935. }
  14936. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  14937. };
  14938. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  14939. x -= this.uOffset + 0.5;
  14940. y -= this.vOffset + 0.5;
  14941. z -= 0.5;
  14942. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  14943. t.x *= this.uScale;
  14944. t.y *= this.vScale;
  14945. t.x += 0.5;
  14946. t.y += 0.5;
  14947. t.z += 0.5;
  14948. };
  14949. Texture.prototype.getTextureMatrix = function () {
  14950. 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) {
  14951. return this._cachedTextureMatrix;
  14952. }
  14953. this._cachedUOffset = this.uOffset;
  14954. this._cachedVOffset = this.vOffset;
  14955. this._cachedUScale = this.uScale;
  14956. this._cachedVScale = this.vScale;
  14957. this._cachedUAng = this.uAng;
  14958. this._cachedVAng = this.vAng;
  14959. this._cachedWAng = this.wAng;
  14960. if (!this._cachedTextureMatrix) {
  14961. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  14962. this._rowGenerationMatrix = new BABYLON.Matrix();
  14963. this._t0 = BABYLON.Vector3.Zero();
  14964. this._t1 = BABYLON.Vector3.Zero();
  14965. this._t2 = BABYLON.Vector3.Zero();
  14966. }
  14967. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  14968. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  14969. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  14970. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  14971. this._t1.subtractInPlace(this._t0);
  14972. this._t2.subtractInPlace(this._t0);
  14973. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  14974. this._cachedTextureMatrix.m[0] = this._t1.x;
  14975. this._cachedTextureMatrix.m[1] = this._t1.y;
  14976. this._cachedTextureMatrix.m[2] = this._t1.z;
  14977. this._cachedTextureMatrix.m[4] = this._t2.x;
  14978. this._cachedTextureMatrix.m[5] = this._t2.y;
  14979. this._cachedTextureMatrix.m[6] = this._t2.z;
  14980. this._cachedTextureMatrix.m[8] = this._t0.x;
  14981. this._cachedTextureMatrix.m[9] = this._t0.y;
  14982. this._cachedTextureMatrix.m[10] = this._t0.z;
  14983. return this._cachedTextureMatrix;
  14984. };
  14985. Texture.prototype.getReflectionTextureMatrix = function () {
  14986. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  14987. return this._cachedTextureMatrix;
  14988. }
  14989. if (!this._cachedTextureMatrix) {
  14990. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  14991. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  14992. }
  14993. this._cachedCoordinatesMode = this.coordinatesMode;
  14994. switch (this.coordinatesMode) {
  14995. case Texture.SPHERICAL_MODE:
  14996. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  14997. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  14998. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  14999. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  15000. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  15001. break;
  15002. case Texture.PLANAR_MODE:
  15003. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15004. this._cachedTextureMatrix[0] = this.uScale;
  15005. this._cachedTextureMatrix[5] = this.vScale;
  15006. this._cachedTextureMatrix[12] = this.uOffset;
  15007. this._cachedTextureMatrix[13] = this.vOffset;
  15008. break;
  15009. case Texture.PROJECTION_MODE:
  15010. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  15011. this._projectionModeMatrix.m[0] = 0.5;
  15012. this._projectionModeMatrix.m[5] = -0.5;
  15013. this._projectionModeMatrix.m[10] = 0.0;
  15014. this._projectionModeMatrix.m[12] = 0.5;
  15015. this._projectionModeMatrix.m[13] = 0.5;
  15016. this._projectionModeMatrix.m[14] = 1.0;
  15017. this._projectionModeMatrix.m[15] = 1.0;
  15018. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  15019. break;
  15020. default:
  15021. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15022. break;
  15023. }
  15024. return this._cachedTextureMatrix;
  15025. };
  15026. Texture.prototype.clone = function () {
  15027. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  15028. // Base texture
  15029. newTexture.hasAlpha = this.hasAlpha;
  15030. newTexture.level = this.level;
  15031. newTexture.wrapU = this.wrapU;
  15032. newTexture.wrapV = this.wrapV;
  15033. newTexture.coordinatesIndex = this.coordinatesIndex;
  15034. newTexture.coordinatesMode = this.coordinatesMode;
  15035. // Texture
  15036. newTexture.uOffset = this.uOffset;
  15037. newTexture.vOffset = this.vOffset;
  15038. newTexture.uScale = this.uScale;
  15039. newTexture.vScale = this.vScale;
  15040. newTexture.uAng = this.uAng;
  15041. newTexture.vAng = this.vAng;
  15042. newTexture.wAng = this.wAng;
  15043. return newTexture;
  15044. };
  15045. // Statics
  15046. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  15047. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  15048. if (onLoad === void 0) { onLoad = null; }
  15049. if (onError === void 0) { onError = null; }
  15050. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  15051. };
  15052. // Constants
  15053. Texture.NEAREST_SAMPLINGMODE = 1;
  15054. Texture.BILINEAR_SAMPLINGMODE = 2;
  15055. Texture.TRILINEAR_SAMPLINGMODE = 3;
  15056. Texture.EXPLICIT_MODE = 0;
  15057. Texture.SPHERICAL_MODE = 1;
  15058. Texture.PLANAR_MODE = 2;
  15059. Texture.CUBIC_MODE = 3;
  15060. Texture.PROJECTION_MODE = 4;
  15061. Texture.SKYBOX_MODE = 5;
  15062. Texture.CLAMP_ADDRESSMODE = 0;
  15063. Texture.WRAP_ADDRESSMODE = 1;
  15064. Texture.MIRROR_ADDRESSMODE = 2;
  15065. return Texture;
  15066. })(BABYLON.BaseTexture);
  15067. BABYLON.Texture = Texture;
  15068. })(BABYLON || (BABYLON = {}));
  15069. //# sourceMappingURL=babylon.texture.js.map
  15070. var __extends = this.__extends || function (d, b) {
  15071. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15072. function __() { this.constructor = d; }
  15073. __.prototype = b.prototype;
  15074. d.prototype = new __();
  15075. };
  15076. var BABYLON;
  15077. (function (BABYLON) {
  15078. var CubeTexture = (function (_super) {
  15079. __extends(CubeTexture, _super);
  15080. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  15081. _super.call(this, scene);
  15082. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  15083. this.name = rootUrl;
  15084. this.url = rootUrl;
  15085. this._noMipmap = noMipmap;
  15086. this.hasAlpha = false;
  15087. this._texture = this._getFromCache(rootUrl, noMipmap);
  15088. if (!extensions) {
  15089. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  15090. }
  15091. this._extensions = extensions;
  15092. if (!this._texture) {
  15093. if (!scene.useDelayedTextureLoading) {
  15094. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  15095. }
  15096. else {
  15097. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15098. }
  15099. }
  15100. this.isCube = true;
  15101. this._textureMatrix = BABYLON.Matrix.Identity();
  15102. }
  15103. CubeTexture.prototype.clone = function () {
  15104. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  15105. // Base texture
  15106. newTexture.level = this.level;
  15107. newTexture.wrapU = this.wrapU;
  15108. newTexture.wrapV = this.wrapV;
  15109. newTexture.coordinatesIndex = this.coordinatesIndex;
  15110. newTexture.coordinatesMode = this.coordinatesMode;
  15111. return newTexture;
  15112. };
  15113. // Methods
  15114. CubeTexture.prototype.delayLoad = function () {
  15115. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15116. return;
  15117. }
  15118. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15119. this._texture = this._getFromCache(this.url, this._noMipmap);
  15120. if (!this._texture) {
  15121. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  15122. }
  15123. };
  15124. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  15125. return this._textureMatrix;
  15126. };
  15127. return CubeTexture;
  15128. })(BABYLON.BaseTexture);
  15129. BABYLON.CubeTexture = CubeTexture;
  15130. })(BABYLON || (BABYLON = {}));
  15131. //# sourceMappingURL=babylon.cubeTexture.js.map
  15132. var __extends = this.__extends || function (d, b) {
  15133. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15134. function __() { this.constructor = d; }
  15135. __.prototype = b.prototype;
  15136. d.prototype = new __();
  15137. };
  15138. var BABYLON;
  15139. (function (BABYLON) {
  15140. var RenderTargetTexture = (function (_super) {
  15141. __extends(RenderTargetTexture, _super);
  15142. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  15143. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  15144. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  15145. _super.call(this, null, scene, !generateMipMaps);
  15146. this.renderList = new Array();
  15147. this.renderParticles = true;
  15148. this.renderSprites = false;
  15149. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  15150. this._currentRefreshId = -1;
  15151. this._refreshRate = 1;
  15152. this.name = name;
  15153. this.isRenderTarget = true;
  15154. this._size = size;
  15155. this._generateMipMaps = generateMipMaps;
  15156. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  15157. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  15158. // Rendering groups
  15159. this._renderingManager = new BABYLON.RenderingManager(scene);
  15160. }
  15161. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  15162. this._currentRefreshId = -1;
  15163. };
  15164. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  15165. get: function () {
  15166. return this._refreshRate;
  15167. },
  15168. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  15169. set: function (value) {
  15170. this._refreshRate = value;
  15171. this.resetRefreshCounter();
  15172. },
  15173. enumerable: true,
  15174. configurable: true
  15175. });
  15176. RenderTargetTexture.prototype._shouldRender = function () {
  15177. if (this._currentRefreshId === -1) {
  15178. this._currentRefreshId = 1;
  15179. return true;
  15180. }
  15181. if (this.refreshRate === this._currentRefreshId) {
  15182. this._currentRefreshId = 1;
  15183. return true;
  15184. }
  15185. this._currentRefreshId++;
  15186. return false;
  15187. };
  15188. RenderTargetTexture.prototype.isReady = function () {
  15189. if (!this.getScene().renderTargetsEnabled) {
  15190. return false;
  15191. }
  15192. return _super.prototype.isReady.call(this);
  15193. };
  15194. RenderTargetTexture.prototype.getRenderSize = function () {
  15195. return this._size;
  15196. };
  15197. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  15198. get: function () {
  15199. return true;
  15200. },
  15201. enumerable: true,
  15202. configurable: true
  15203. });
  15204. RenderTargetTexture.prototype.scale = function (ratio) {
  15205. var newSize = this._size * ratio;
  15206. this.resize(newSize, this._generateMipMaps);
  15207. };
  15208. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  15209. this.releaseInternalTexture();
  15210. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  15211. };
  15212. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  15213. var scene = this.getScene();
  15214. var engine = scene.getEngine();
  15215. if (this._waitingRenderList) {
  15216. this.renderList = [];
  15217. for (var index = 0; index < this._waitingRenderList.length; index++) {
  15218. var id = this._waitingRenderList[index];
  15219. this.renderList.push(scene.getMeshByID(id));
  15220. }
  15221. delete this._waitingRenderList;
  15222. }
  15223. if (this.renderList && this.renderList.length === 0) {
  15224. return;
  15225. }
  15226. // Bind
  15227. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  15228. engine.bindFramebuffer(this._texture);
  15229. }
  15230. this._renderingManager.reset();
  15231. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  15232. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  15233. var mesh = currentRenderList[meshIndex];
  15234. if (mesh) {
  15235. if (!mesh.isReady()) {
  15236. // Reset _currentRefreshId
  15237. this.resetRefreshCounter();
  15238. continue;
  15239. }
  15240. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  15241. mesh._activate(scene.getRenderId());
  15242. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  15243. var subMesh = mesh.subMeshes[subIndex];
  15244. scene._activeIndices += subMesh.indexCount;
  15245. this._renderingManager.dispatch(subMesh);
  15246. }
  15247. }
  15248. }
  15249. }
  15250. if (this.onBeforeRender) {
  15251. this.onBeforeRender();
  15252. }
  15253. // Clear
  15254. if (this.onClear) {
  15255. this.onClear(engine);
  15256. }
  15257. else {
  15258. engine.clear(scene.clearColor, true, true);
  15259. }
  15260. if (!this._doNotChangeAspectRatio) {
  15261. scene.updateTransformMatrix(true);
  15262. }
  15263. // Render
  15264. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  15265. if (useCameraPostProcess) {
  15266. scene.postProcessManager._finalizeFrame(false, this._texture);
  15267. }
  15268. if (!this._doNotChangeAspectRatio) {
  15269. scene.updateTransformMatrix(true);
  15270. }
  15271. if (this.onAfterRender) {
  15272. this.onAfterRender();
  15273. }
  15274. // Dump ?
  15275. if (dumpForDebug) {
  15276. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  15277. }
  15278. // Unbind
  15279. engine.unBindFramebuffer(this._texture);
  15280. if (this.onAfterUnbind) {
  15281. this.onAfterUnbind();
  15282. }
  15283. };
  15284. RenderTargetTexture.prototype.clone = function () {
  15285. var textureSize = this.getSize();
  15286. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  15287. // Base texture
  15288. newTexture.hasAlpha = this.hasAlpha;
  15289. newTexture.level = this.level;
  15290. // RenderTarget Texture
  15291. newTexture.coordinatesMode = this.coordinatesMode;
  15292. newTexture.renderList = this.renderList.slice(0);
  15293. return newTexture;
  15294. };
  15295. return RenderTargetTexture;
  15296. })(BABYLON.Texture);
  15297. BABYLON.RenderTargetTexture = RenderTargetTexture;
  15298. })(BABYLON || (BABYLON = {}));
  15299. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  15300. var __extends = this.__extends || function (d, b) {
  15301. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15302. function __() { this.constructor = d; }
  15303. __.prototype = b.prototype;
  15304. d.prototype = new __();
  15305. };
  15306. var BABYLON;
  15307. (function (BABYLON) {
  15308. var ProceduralTexture = (function (_super) {
  15309. __extends(ProceduralTexture, _super);
  15310. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  15311. if (generateMipMaps === void 0) { generateMipMaps = true; }
  15312. _super.call(this, null, scene, !generateMipMaps);
  15313. this._currentRefreshId = -1;
  15314. this._refreshRate = 1;
  15315. this._vertexDeclaration = [2];
  15316. this._vertexStrideSize = 2 * 4;
  15317. this._uniforms = new Array();
  15318. this._samplers = new Array();
  15319. this._textures = new Array();
  15320. this._floats = new Array();
  15321. this._floatsArrays = {};
  15322. this._colors3 = new Array();
  15323. this._colors4 = new Array();
  15324. this._vectors2 = new Array();
  15325. this._vectors3 = new Array();
  15326. this._matrices = new Array();
  15327. this._fallbackTextureUsed = false;
  15328. scene._proceduralTextures.push(this);
  15329. this.name = name;
  15330. this.isRenderTarget = true;
  15331. this._size = size;
  15332. this._generateMipMaps = generateMipMaps;
  15333. this.setFragment(fragment);
  15334. this._fallbackTexture = fallbackTexture;
  15335. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  15336. // VBO
  15337. var vertices = [];
  15338. vertices.push(1, 1);
  15339. vertices.push(-1, 1);
  15340. vertices.push(-1, -1);
  15341. vertices.push(1, -1);
  15342. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15343. // Indices
  15344. var indices = [];
  15345. indices.push(0);
  15346. indices.push(1);
  15347. indices.push(2);
  15348. indices.push(0);
  15349. indices.push(2);
  15350. indices.push(3);
  15351. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15352. }
  15353. ProceduralTexture.prototype.reset = function () {
  15354. if (this._effect === undefined) {
  15355. return;
  15356. }
  15357. var engine = this.getScene().getEngine();
  15358. engine._releaseEffect(this._effect);
  15359. };
  15360. ProceduralTexture.prototype.isReady = function () {
  15361. var _this = this;
  15362. var engine = this.getScene().getEngine();
  15363. var shaders;
  15364. if (!this._fragment) {
  15365. return false;
  15366. }
  15367. if (this._fallbackTextureUsed) {
  15368. return true;
  15369. }
  15370. if (this._fragment.fragmentElement !== undefined) {
  15371. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  15372. }
  15373. else {
  15374. shaders = { vertex: "procedural", fragment: this._fragment };
  15375. }
  15376. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  15377. _this.releaseInternalTexture();
  15378. if (_this._fallbackTexture) {
  15379. _this._texture = _this._fallbackTexture._texture;
  15380. _this._texture.references++;
  15381. }
  15382. _this._fallbackTextureUsed = true;
  15383. });
  15384. return this._effect.isReady();
  15385. };
  15386. ProceduralTexture.prototype.resetRefreshCounter = function () {
  15387. this._currentRefreshId = -1;
  15388. };
  15389. ProceduralTexture.prototype.setFragment = function (fragment) {
  15390. this._fragment = fragment;
  15391. };
  15392. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  15393. get: function () {
  15394. return this._refreshRate;
  15395. },
  15396. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  15397. set: function (value) {
  15398. this._refreshRate = value;
  15399. this.resetRefreshCounter();
  15400. },
  15401. enumerable: true,
  15402. configurable: true
  15403. });
  15404. ProceduralTexture.prototype._shouldRender = function () {
  15405. if (!this.isReady() || !this._texture) {
  15406. return false;
  15407. }
  15408. if (this._fallbackTextureUsed) {
  15409. return false;
  15410. }
  15411. if (this._currentRefreshId === -1) {
  15412. this._currentRefreshId = 1;
  15413. return true;
  15414. }
  15415. if (this.refreshRate === this._currentRefreshId) {
  15416. this._currentRefreshId = 1;
  15417. return true;
  15418. }
  15419. this._currentRefreshId++;
  15420. return false;
  15421. };
  15422. ProceduralTexture.prototype.getRenderSize = function () {
  15423. return this._size;
  15424. };
  15425. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  15426. if (this._fallbackTextureUsed) {
  15427. return;
  15428. }
  15429. this.releaseInternalTexture();
  15430. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  15431. };
  15432. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  15433. if (this._uniforms.indexOf(uniformName) === -1) {
  15434. this._uniforms.push(uniformName);
  15435. }
  15436. };
  15437. ProceduralTexture.prototype.setTexture = function (name, texture) {
  15438. if (this._samplers.indexOf(name) === -1) {
  15439. this._samplers.push(name);
  15440. }
  15441. this._textures[name] = texture;
  15442. return this;
  15443. };
  15444. ProceduralTexture.prototype.setFloat = function (name, value) {
  15445. this._checkUniform(name);
  15446. this._floats[name] = value;
  15447. return this;
  15448. };
  15449. ProceduralTexture.prototype.setFloats = function (name, value) {
  15450. this._checkUniform(name);
  15451. this._floatsArrays[name] = value;
  15452. return this;
  15453. };
  15454. ProceduralTexture.prototype.setColor3 = function (name, value) {
  15455. this._checkUniform(name);
  15456. this._colors3[name] = value;
  15457. return this;
  15458. };
  15459. ProceduralTexture.prototype.setColor4 = function (name, value) {
  15460. this._checkUniform(name);
  15461. this._colors4[name] = value;
  15462. return this;
  15463. };
  15464. ProceduralTexture.prototype.setVector2 = function (name, value) {
  15465. this._checkUniform(name);
  15466. this._vectors2[name] = value;
  15467. return this;
  15468. };
  15469. ProceduralTexture.prototype.setVector3 = function (name, value) {
  15470. this._checkUniform(name);
  15471. this._vectors3[name] = value;
  15472. return this;
  15473. };
  15474. ProceduralTexture.prototype.setMatrix = function (name, value) {
  15475. this._checkUniform(name);
  15476. this._matrices[name] = value;
  15477. return this;
  15478. };
  15479. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  15480. var scene = this.getScene();
  15481. var engine = scene.getEngine();
  15482. engine.bindFramebuffer(this._texture);
  15483. // Clear
  15484. engine.clear(scene.clearColor, true, true);
  15485. // Render
  15486. engine.enableEffect(this._effect);
  15487. engine.setState(false);
  15488. for (var name in this._textures) {
  15489. this._effect.setTexture(name, this._textures[name]);
  15490. }
  15491. for (name in this._floats) {
  15492. this._effect.setFloat(name, this._floats[name]);
  15493. }
  15494. for (name in this._floatsArrays) {
  15495. this._effect.setArray(name, this._floatsArrays[name]);
  15496. }
  15497. for (name in this._colors3) {
  15498. this._effect.setColor3(name, this._colors3[name]);
  15499. }
  15500. for (name in this._colors4) {
  15501. var color = this._colors4[name];
  15502. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  15503. }
  15504. for (name in this._vectors2) {
  15505. this._effect.setVector2(name, this._vectors2[name]);
  15506. }
  15507. for (name in this._vectors3) {
  15508. this._effect.setVector3(name, this._vectors3[name]);
  15509. }
  15510. for (name in this._matrices) {
  15511. this._effect.setMatrix(name, this._matrices[name]);
  15512. }
  15513. // VBOs
  15514. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15515. // Draw order
  15516. engine.draw(true, 0, 6);
  15517. // Unbind
  15518. engine.unBindFramebuffer(this._texture);
  15519. };
  15520. ProceduralTexture.prototype.clone = function () {
  15521. var textureSize = this.getSize();
  15522. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  15523. // Base texture
  15524. newTexture.hasAlpha = this.hasAlpha;
  15525. newTexture.level = this.level;
  15526. // RenderTarget Texture
  15527. newTexture.coordinatesMode = this.coordinatesMode;
  15528. return newTexture;
  15529. };
  15530. ProceduralTexture.prototype.dispose = function () {
  15531. var index = this.getScene()._proceduralTextures.indexOf(this);
  15532. if (index >= 0) {
  15533. this.getScene()._proceduralTextures.splice(index, 1);
  15534. }
  15535. _super.prototype.dispose.call(this);
  15536. };
  15537. return ProceduralTexture;
  15538. })(BABYLON.Texture);
  15539. BABYLON.ProceduralTexture = ProceduralTexture;
  15540. })(BABYLON || (BABYLON = {}));
  15541. //# sourceMappingURL=babylon.proceduralTexture.js.map
  15542. var __extends = this.__extends || function (d, b) {
  15543. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15544. function __() { this.constructor = d; }
  15545. __.prototype = b.prototype;
  15546. d.prototype = new __();
  15547. };
  15548. var BABYLON;
  15549. (function (BABYLON) {
  15550. var MirrorTexture = (function (_super) {
  15551. __extends(MirrorTexture, _super);
  15552. function MirrorTexture(name, size, scene, generateMipMaps) {
  15553. var _this = this;
  15554. _super.call(this, name, size, scene, generateMipMaps, true);
  15555. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  15556. this._transformMatrix = BABYLON.Matrix.Zero();
  15557. this._mirrorMatrix = BABYLON.Matrix.Zero();
  15558. this.onBeforeRender = function () {
  15559. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  15560. _this._savedViewMatrix = scene.getViewMatrix();
  15561. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  15562. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  15563. scene.clipPlane = _this.mirrorPlane;
  15564. scene.getEngine().cullBackFaces = false;
  15565. };
  15566. this.onAfterRender = function () {
  15567. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  15568. scene.getEngine().cullBackFaces = true;
  15569. delete scene.clipPlane;
  15570. };
  15571. }
  15572. MirrorTexture.prototype.clone = function () {
  15573. var textureSize = this.getSize();
  15574. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  15575. // Base texture
  15576. newTexture.hasAlpha = this.hasAlpha;
  15577. newTexture.level = this.level;
  15578. // Mirror Texture
  15579. newTexture.mirrorPlane = this.mirrorPlane.clone();
  15580. newTexture.renderList = this.renderList.slice(0);
  15581. return newTexture;
  15582. };
  15583. return MirrorTexture;
  15584. })(BABYLON.RenderTargetTexture);
  15585. BABYLON.MirrorTexture = MirrorTexture;
  15586. })(BABYLON || (BABYLON = {}));
  15587. //# sourceMappingURL=babylon.mirrorTexture.js.map
  15588. var __extends = this.__extends || function (d, b) {
  15589. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15590. function __() { this.constructor = d; }
  15591. __.prototype = b.prototype;
  15592. d.prototype = new __();
  15593. };
  15594. var BABYLON;
  15595. (function (BABYLON) {
  15596. var DynamicTexture = (function (_super) {
  15597. __extends(DynamicTexture, _super);
  15598. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  15599. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15600. _super.call(this, null, scene, !generateMipMaps);
  15601. this.name = name;
  15602. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15603. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15604. this._generateMipMaps = generateMipMaps;
  15605. if (options.getContext) {
  15606. this._canvas = options;
  15607. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  15608. }
  15609. else {
  15610. this._canvas = document.createElement("canvas");
  15611. if (options.width) {
  15612. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  15613. }
  15614. else {
  15615. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  15616. }
  15617. }
  15618. var textureSize = this.getSize();
  15619. this._canvas.width = textureSize.width;
  15620. this._canvas.height = textureSize.height;
  15621. this._context = this._canvas.getContext("2d");
  15622. }
  15623. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  15624. get: function () {
  15625. return true;
  15626. },
  15627. enumerable: true,
  15628. configurable: true
  15629. });
  15630. DynamicTexture.prototype.scale = function (ratio) {
  15631. var textureSize = this.getSize();
  15632. textureSize.width *= ratio;
  15633. textureSize.height *= ratio;
  15634. this._canvas.width = textureSize.width;
  15635. this._canvas.height = textureSize.height;
  15636. this.releaseInternalTexture();
  15637. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  15638. };
  15639. DynamicTexture.prototype.getContext = function () {
  15640. return this._context;
  15641. };
  15642. DynamicTexture.prototype.clear = function () {
  15643. var size = this.getSize();
  15644. this._context.fillRect(0, 0, size.width, size.height);
  15645. };
  15646. DynamicTexture.prototype.update = function (invertY) {
  15647. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  15648. };
  15649. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  15650. if (update === void 0) { update = true; }
  15651. var size = this.getSize();
  15652. if (clearColor) {
  15653. this._context.fillStyle = clearColor;
  15654. this._context.fillRect(0, 0, size.width, size.height);
  15655. }
  15656. this._context.font = font;
  15657. if (x === null) {
  15658. var textSize = this._context.measureText(text);
  15659. x = (size.width - textSize.width) / 2;
  15660. }
  15661. this._context.fillStyle = color;
  15662. this._context.fillText(text, x, y);
  15663. if (update) {
  15664. this.update(invertY);
  15665. }
  15666. };
  15667. DynamicTexture.prototype.clone = function () {
  15668. var textureSize = this.getSize();
  15669. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  15670. // Base texture
  15671. newTexture.hasAlpha = this.hasAlpha;
  15672. newTexture.level = this.level;
  15673. // Dynamic Texture
  15674. newTexture.wrapU = this.wrapU;
  15675. newTexture.wrapV = this.wrapV;
  15676. return newTexture;
  15677. };
  15678. return DynamicTexture;
  15679. })(BABYLON.Texture);
  15680. BABYLON.DynamicTexture = DynamicTexture;
  15681. })(BABYLON || (BABYLON = {}));
  15682. //# sourceMappingURL=babylon.dynamicTexture.js.map
  15683. var __extends = this.__extends || function (d, b) {
  15684. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15685. function __() { this.constructor = d; }
  15686. __.prototype = b.prototype;
  15687. d.prototype = new __();
  15688. };
  15689. var BABYLON;
  15690. (function (BABYLON) {
  15691. var VideoTexture = (function (_super) {
  15692. __extends(VideoTexture, _super);
  15693. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  15694. var _this = this;
  15695. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15696. _super.call(this, null, scene, !generateMipMaps, invertY);
  15697. this._autoLaunch = true;
  15698. this.name = name;
  15699. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  15700. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  15701. var requiredWidth = size.width || size;
  15702. var requiredHeight = size.height || size;
  15703. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  15704. var textureSize = this.getSize();
  15705. this.video = document.createElement("video");
  15706. this.video.width = textureSize.width;
  15707. this.video.height = textureSize.height;
  15708. this.video.autoplay = false;
  15709. this.video.loop = true;
  15710. this.video.addEventListener("canplaythrough", function () {
  15711. if (_this._texture) {
  15712. _this._texture.isReady = true;
  15713. }
  15714. });
  15715. urls.forEach(function (url) {
  15716. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  15717. var source = document.createElement("source");
  15718. source.src = url;
  15719. _this.video.appendChild(source);
  15720. });
  15721. this._lastUpdate = BABYLON.Tools.Now;
  15722. }
  15723. VideoTexture.prototype.update = function () {
  15724. if (this._autoLaunch) {
  15725. this._autoLaunch = false;
  15726. this.video.play();
  15727. }
  15728. var now = BABYLON.Tools.Now;
  15729. if (now - this._lastUpdate < 15) {
  15730. return false;
  15731. }
  15732. this._lastUpdate = now;
  15733. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  15734. return true;
  15735. };
  15736. return VideoTexture;
  15737. })(BABYLON.Texture);
  15738. BABYLON.VideoTexture = VideoTexture;
  15739. })(BABYLON || (BABYLON = {}));
  15740. //# sourceMappingURL=babylon.videoTexture.js.map
  15741. var __extends = this.__extends || function (d, b) {
  15742. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15743. function __() { this.constructor = d; }
  15744. __.prototype = b.prototype;
  15745. d.prototype = new __();
  15746. };
  15747. var BABYLON;
  15748. (function (BABYLON) {
  15749. var CustomProceduralTexture = (function (_super) {
  15750. __extends(CustomProceduralTexture, _super);
  15751. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  15752. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  15753. this._animate = true;
  15754. this._time = 0;
  15755. this._texturePath = texturePath;
  15756. //Try to load json
  15757. this.loadJson(texturePath);
  15758. this.refreshRate = 1;
  15759. }
  15760. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  15761. var _this = this;
  15762. var that = this;
  15763. function noConfigFile() {
  15764. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  15765. try {
  15766. that.setFragment(that._texturePath);
  15767. }
  15768. catch (ex) {
  15769. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  15770. }
  15771. }
  15772. var configFileUrl = jsonUrl + "/config.json";
  15773. var xhr = new XMLHttpRequest();
  15774. xhr.open("GET", configFileUrl, true);
  15775. xhr.addEventListener("load", function () {
  15776. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15777. try {
  15778. _this._config = JSON.parse(xhr.response);
  15779. _this.updateShaderUniforms();
  15780. _this.updateTextures();
  15781. _this.setFragment(_this._texturePath + "/custom");
  15782. _this._animate = _this._config.animate;
  15783. _this.refreshRate = _this._config.refreshrate;
  15784. }
  15785. catch (ex) {
  15786. noConfigFile();
  15787. }
  15788. }
  15789. else {
  15790. noConfigFile();
  15791. }
  15792. }, false);
  15793. xhr.addEventListener("error", function () {
  15794. noConfigFile();
  15795. }, false);
  15796. try {
  15797. xhr.send();
  15798. }
  15799. catch (ex) {
  15800. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  15801. }
  15802. };
  15803. CustomProceduralTexture.prototype.isReady = function () {
  15804. if (!_super.prototype.isReady.call(this)) {
  15805. return false;
  15806. }
  15807. for (var name in this._textures) {
  15808. var texture = this._textures[name];
  15809. if (!texture.isReady()) {
  15810. return false;
  15811. }
  15812. }
  15813. return true;
  15814. };
  15815. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  15816. if (this._animate) {
  15817. this._time += this.getScene().getAnimationRatio() * 0.03;
  15818. this.updateShaderUniforms();
  15819. }
  15820. _super.prototype.render.call(this, useCameraPostProcess);
  15821. };
  15822. CustomProceduralTexture.prototype.updateTextures = function () {
  15823. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  15824. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  15825. }
  15826. };
  15827. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  15828. if (this._config) {
  15829. for (var j = 0; j < this._config.uniforms.length; j++) {
  15830. var uniform = this._config.uniforms[j];
  15831. switch (uniform.type) {
  15832. case "float":
  15833. this.setFloat(uniform.name, uniform.value);
  15834. break;
  15835. case "color3":
  15836. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  15837. break;
  15838. case "color4":
  15839. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  15840. break;
  15841. case "vector2":
  15842. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  15843. break;
  15844. case "vector3":
  15845. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  15846. break;
  15847. }
  15848. }
  15849. }
  15850. this.setFloat("time", this._time);
  15851. };
  15852. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  15853. get: function () {
  15854. return this._animate;
  15855. },
  15856. set: function (value) {
  15857. this._animate = value;
  15858. },
  15859. enumerable: true,
  15860. configurable: true
  15861. });
  15862. return CustomProceduralTexture;
  15863. })(BABYLON.ProceduralTexture);
  15864. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  15865. })(BABYLON || (BABYLON = {}));
  15866. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  15867. var __extends = this.__extends || function (d, b) {
  15868. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15869. function __() { this.constructor = d; }
  15870. __.prototype = b.prototype;
  15871. d.prototype = new __();
  15872. };
  15873. var BABYLON;
  15874. (function (BABYLON) {
  15875. var WoodProceduralTexture = (function (_super) {
  15876. __extends(WoodProceduralTexture, _super);
  15877. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  15878. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  15879. this._ampScale = 100.0;
  15880. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  15881. this.updateShaderUniforms();
  15882. this.refreshRate = 0;
  15883. }
  15884. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  15885. this.setFloat("ampScale", this._ampScale);
  15886. this.setColor3("woodColor", this._woodColor);
  15887. };
  15888. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  15889. get: function () {
  15890. return this._ampScale;
  15891. },
  15892. set: function (value) {
  15893. this._ampScale = value;
  15894. this.updateShaderUniforms();
  15895. },
  15896. enumerable: true,
  15897. configurable: true
  15898. });
  15899. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  15900. get: function () {
  15901. return this._woodColor;
  15902. },
  15903. set: function (value) {
  15904. this._woodColor = value;
  15905. this.updateShaderUniforms();
  15906. },
  15907. enumerable: true,
  15908. configurable: true
  15909. });
  15910. return WoodProceduralTexture;
  15911. })(BABYLON.ProceduralTexture);
  15912. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  15913. var FireProceduralTexture = (function (_super) {
  15914. __extends(FireProceduralTexture, _super);
  15915. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  15916. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  15917. this._time = 0.0;
  15918. this._speed = new BABYLON.Vector2(0.5, 0.3);
  15919. this._autoGenerateTime = true;
  15920. this._alphaThreshold = 0.5;
  15921. this._fireColors = FireProceduralTexture.RedFireColors;
  15922. this.updateShaderUniforms();
  15923. this.refreshRate = 1;
  15924. }
  15925. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  15926. this.setFloat("time", this._time);
  15927. this.setVector2("speed", this._speed);
  15928. this.setColor3("c1", this._fireColors[0]);
  15929. this.setColor3("c2", this._fireColors[1]);
  15930. this.setColor3("c3", this._fireColors[2]);
  15931. this.setColor3("c4", this._fireColors[3]);
  15932. this.setColor3("c5", this._fireColors[4]);
  15933. this.setColor3("c6", this._fireColors[5]);
  15934. this.setFloat("alphaThreshold", this._alphaThreshold);
  15935. };
  15936. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  15937. if (this._autoGenerateTime) {
  15938. this._time += this.getScene().getAnimationRatio() * 0.03;
  15939. this.updateShaderUniforms();
  15940. }
  15941. _super.prototype.render.call(this, useCameraPostProcess);
  15942. };
  15943. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  15944. get: function () {
  15945. return [
  15946. new BABYLON.Color3(0.5, 0.0, 1.0),
  15947. new BABYLON.Color3(0.9, 0.0, 1.0),
  15948. new BABYLON.Color3(0.2, 0.0, 1.0),
  15949. new BABYLON.Color3(1.0, 0.9, 1.0),
  15950. new BABYLON.Color3(0.1, 0.1, 1.0),
  15951. new BABYLON.Color3(0.9, 0.9, 1.0)
  15952. ];
  15953. },
  15954. enumerable: true,
  15955. configurable: true
  15956. });
  15957. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  15958. get: function () {
  15959. return [
  15960. new BABYLON.Color3(0.5, 1.0, 0.0),
  15961. new BABYLON.Color3(0.5, 1.0, 0.0),
  15962. new BABYLON.Color3(0.3, 0.4, 0.0),
  15963. new BABYLON.Color3(0.5, 1.0, 0.0),
  15964. new BABYLON.Color3(0.2, 0.0, 0.0),
  15965. new BABYLON.Color3(0.5, 1.0, 0.0)
  15966. ];
  15967. },
  15968. enumerable: true,
  15969. configurable: true
  15970. });
  15971. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  15972. get: function () {
  15973. return [
  15974. new BABYLON.Color3(0.5, 0.0, 0.1),
  15975. new BABYLON.Color3(0.9, 0.0, 0.0),
  15976. new BABYLON.Color3(0.2, 0.0, 0.0),
  15977. new BABYLON.Color3(1.0, 0.9, 0.0),
  15978. new BABYLON.Color3(0.1, 0.1, 0.1),
  15979. new BABYLON.Color3(0.9, 0.9, 0.9)
  15980. ];
  15981. },
  15982. enumerable: true,
  15983. configurable: true
  15984. });
  15985. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  15986. get: function () {
  15987. return [
  15988. new BABYLON.Color3(0.1, 0.0, 0.5),
  15989. new BABYLON.Color3(0.0, 0.0, 0.5),
  15990. new BABYLON.Color3(0.1, 0.0, 0.2),
  15991. new BABYLON.Color3(0.0, 0.0, 1.0),
  15992. new BABYLON.Color3(0.1, 0.2, 0.3),
  15993. new BABYLON.Color3(0.0, 0.2, 0.9)
  15994. ];
  15995. },
  15996. enumerable: true,
  15997. configurable: true
  15998. });
  15999. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  16000. get: function () {
  16001. return this._fireColors;
  16002. },
  16003. set: function (value) {
  16004. this._fireColors = value;
  16005. this.updateShaderUniforms();
  16006. },
  16007. enumerable: true,
  16008. configurable: true
  16009. });
  16010. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  16011. get: function () {
  16012. return this._time;
  16013. },
  16014. set: function (value) {
  16015. this._time = value;
  16016. this.updateShaderUniforms();
  16017. },
  16018. enumerable: true,
  16019. configurable: true
  16020. });
  16021. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  16022. get: function () {
  16023. return this._speed;
  16024. },
  16025. set: function (value) {
  16026. this._speed = value;
  16027. this.updateShaderUniforms();
  16028. },
  16029. enumerable: true,
  16030. configurable: true
  16031. });
  16032. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  16033. get: function () {
  16034. return this._alphaThreshold;
  16035. },
  16036. set: function (value) {
  16037. this._alphaThreshold = value;
  16038. this.updateShaderUniforms();
  16039. },
  16040. enumerable: true,
  16041. configurable: true
  16042. });
  16043. return FireProceduralTexture;
  16044. })(BABYLON.ProceduralTexture);
  16045. BABYLON.FireProceduralTexture = FireProceduralTexture;
  16046. var CloudProceduralTexture = (function (_super) {
  16047. __extends(CloudProceduralTexture, _super);
  16048. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16049. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  16050. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  16051. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  16052. this.updateShaderUniforms();
  16053. this.refreshRate = 0;
  16054. }
  16055. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  16056. this.setColor3("skyColor", this._skyColor);
  16057. this.setColor3("cloudColor", this._cloudColor);
  16058. };
  16059. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  16060. get: function () {
  16061. return this._skyColor;
  16062. },
  16063. set: function (value) {
  16064. this._skyColor = value;
  16065. this.updateShaderUniforms();
  16066. },
  16067. enumerable: true,
  16068. configurable: true
  16069. });
  16070. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  16071. get: function () {
  16072. return this._cloudColor;
  16073. },
  16074. set: function (value) {
  16075. this._cloudColor = value;
  16076. this.updateShaderUniforms();
  16077. },
  16078. enumerable: true,
  16079. configurable: true
  16080. });
  16081. return CloudProceduralTexture;
  16082. })(BABYLON.ProceduralTexture);
  16083. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  16084. var GrassProceduralTexture = (function (_super) {
  16085. __extends(GrassProceduralTexture, _super);
  16086. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16087. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  16088. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  16089. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  16090. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  16091. this._groundColor = new BABYLON.Color3(1, 1, 1);
  16092. this._grassColors = [
  16093. new BABYLON.Color3(0.29, 0.38, 0.02),
  16094. new BABYLON.Color3(0.36, 0.49, 0.09),
  16095. new BABYLON.Color3(0.51, 0.6, 0.28)
  16096. ];
  16097. this.updateShaderUniforms();
  16098. this.refreshRate = 0;
  16099. }
  16100. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  16101. this.setColor3("herb1Color", this._grassColors[0]);
  16102. this.setColor3("herb2Color", this._grassColors[1]);
  16103. this.setColor3("herb3Color", this._grassColors[2]);
  16104. this.setColor3("groundColor", this._groundColor);
  16105. };
  16106. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  16107. get: function () {
  16108. return this._grassColors;
  16109. },
  16110. set: function (value) {
  16111. this._grassColors = value;
  16112. this.updateShaderUniforms();
  16113. },
  16114. enumerable: true,
  16115. configurable: true
  16116. });
  16117. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  16118. get: function () {
  16119. return this._groundColor;
  16120. },
  16121. set: function (value) {
  16122. this.groundColor = value;
  16123. this.updateShaderUniforms();
  16124. },
  16125. enumerable: true,
  16126. configurable: true
  16127. });
  16128. return GrassProceduralTexture;
  16129. })(BABYLON.ProceduralTexture);
  16130. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  16131. var RoadProceduralTexture = (function (_super) {
  16132. __extends(RoadProceduralTexture, _super);
  16133. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16134. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  16135. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  16136. this.updateShaderUniforms();
  16137. this.refreshRate = 0;
  16138. }
  16139. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  16140. this.setColor3("roadColor", this._roadColor);
  16141. };
  16142. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  16143. get: function () {
  16144. return this._roadColor;
  16145. },
  16146. set: function (value) {
  16147. this._roadColor = value;
  16148. this.updateShaderUniforms();
  16149. },
  16150. enumerable: true,
  16151. configurable: true
  16152. });
  16153. return RoadProceduralTexture;
  16154. })(BABYLON.ProceduralTexture);
  16155. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  16156. var BrickProceduralTexture = (function (_super) {
  16157. __extends(BrickProceduralTexture, _super);
  16158. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16159. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  16160. this._numberOfBricksHeight = 15;
  16161. this._numberOfBricksWidth = 5;
  16162. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  16163. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  16164. this.updateShaderUniforms();
  16165. this.refreshRate = 0;
  16166. }
  16167. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  16168. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  16169. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  16170. this.setColor3("brickColor", this._brickColor);
  16171. this.setColor3("jointColor", this._jointColor);
  16172. };
  16173. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  16174. get: function () {
  16175. return this._numberOfBricksHeight;
  16176. },
  16177. set: function (value) {
  16178. this._numberOfBricksHeight = value;
  16179. this.updateShaderUniforms();
  16180. },
  16181. enumerable: true,
  16182. configurable: true
  16183. });
  16184. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  16185. get: function () {
  16186. return this._numberOfBricksWidth;
  16187. },
  16188. set: function (value) {
  16189. this._numberOfBricksHeight = value;
  16190. this.updateShaderUniforms();
  16191. },
  16192. enumerable: true,
  16193. configurable: true
  16194. });
  16195. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  16196. get: function () {
  16197. return this._jointColor;
  16198. },
  16199. set: function (value) {
  16200. this._jointColor = value;
  16201. this.updateShaderUniforms();
  16202. },
  16203. enumerable: true,
  16204. configurable: true
  16205. });
  16206. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  16207. get: function () {
  16208. return this._brickColor;
  16209. },
  16210. set: function (value) {
  16211. this._brickColor = value;
  16212. this.updateShaderUniforms();
  16213. },
  16214. enumerable: true,
  16215. configurable: true
  16216. });
  16217. return BrickProceduralTexture;
  16218. })(BABYLON.ProceduralTexture);
  16219. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  16220. var MarbleProceduralTexture = (function (_super) {
  16221. __extends(MarbleProceduralTexture, _super);
  16222. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16223. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  16224. this._numberOfTilesHeight = 3;
  16225. this._numberOfTilesWidth = 3;
  16226. this._amplitude = 9.0;
  16227. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  16228. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  16229. this.updateShaderUniforms();
  16230. this.refreshRate = 0;
  16231. }
  16232. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  16233. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  16234. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  16235. this.setFloat("amplitude", this._amplitude);
  16236. this.setColor3("marbleColor", this._marbleColor);
  16237. this.setColor3("jointColor", this._jointColor);
  16238. };
  16239. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  16240. get: function () {
  16241. return this._numberOfTilesHeight;
  16242. },
  16243. set: function (value) {
  16244. this._numberOfTilesHeight = value;
  16245. this.updateShaderUniforms();
  16246. },
  16247. enumerable: true,
  16248. configurable: true
  16249. });
  16250. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  16251. get: function () {
  16252. return this._numberOfTilesWidth;
  16253. },
  16254. set: function (value) {
  16255. this._numberOfTilesWidth = value;
  16256. this.updateShaderUniforms();
  16257. },
  16258. enumerable: true,
  16259. configurable: true
  16260. });
  16261. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  16262. get: function () {
  16263. return this._jointColor;
  16264. },
  16265. set: function (value) {
  16266. this._jointColor = value;
  16267. this.updateShaderUniforms();
  16268. },
  16269. enumerable: true,
  16270. configurable: true
  16271. });
  16272. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  16273. get: function () {
  16274. return this._marbleColor;
  16275. },
  16276. set: function (value) {
  16277. this._marbleColor = value;
  16278. this.updateShaderUniforms();
  16279. },
  16280. enumerable: true,
  16281. configurable: true
  16282. });
  16283. return MarbleProceduralTexture;
  16284. })(BABYLON.ProceduralTexture);
  16285. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  16286. })(BABYLON || (BABYLON = {}));
  16287. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  16288. var BABYLON;
  16289. (function (BABYLON) {
  16290. var EffectFallbacks = (function () {
  16291. function EffectFallbacks() {
  16292. this._defines = {};
  16293. this._currentRank = 32;
  16294. this._maxRank = -1;
  16295. }
  16296. EffectFallbacks.prototype.addFallback = function (rank, define) {
  16297. if (!this._defines[rank]) {
  16298. if (rank < this._currentRank) {
  16299. this._currentRank = rank;
  16300. }
  16301. if (rank > this._maxRank) {
  16302. this._maxRank = rank;
  16303. }
  16304. this._defines[rank] = new Array();
  16305. }
  16306. this._defines[rank].push(define);
  16307. };
  16308. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  16309. get: function () {
  16310. return this._currentRank <= this._maxRank;
  16311. },
  16312. enumerable: true,
  16313. configurable: true
  16314. });
  16315. EffectFallbacks.prototype.reduce = function (currentDefines) {
  16316. var currentFallbacks = this._defines[this._currentRank];
  16317. for (var index = 0; index < currentFallbacks.length; index++) {
  16318. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  16319. }
  16320. this._currentRank++;
  16321. return currentDefines;
  16322. };
  16323. return EffectFallbacks;
  16324. })();
  16325. BABYLON.EffectFallbacks = EffectFallbacks;
  16326. var Effect = (function () {
  16327. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  16328. var _this = this;
  16329. this._isReady = false;
  16330. this._compilationError = "";
  16331. this._valueCache = [];
  16332. this._engine = engine;
  16333. this.name = baseName;
  16334. this.defines = defines;
  16335. this._uniformsNames = uniformsNames.concat(samplers);
  16336. this._samplers = samplers;
  16337. this._attributesNames = attributesNames;
  16338. this.onError = onError;
  16339. this.onCompiled = onCompiled;
  16340. var vertexSource;
  16341. var fragmentSource;
  16342. if (baseName.vertexElement) {
  16343. vertexSource = document.getElementById(baseName.vertexElement);
  16344. if (!vertexSource) {
  16345. vertexSource = baseName.vertexElement;
  16346. }
  16347. }
  16348. else {
  16349. vertexSource = baseName.vertex || baseName;
  16350. }
  16351. if (baseName.fragmentElement) {
  16352. fragmentSource = document.getElementById(baseName.fragmentElement);
  16353. if (!fragmentSource) {
  16354. fragmentSource = baseName.fragmentElement;
  16355. }
  16356. }
  16357. else {
  16358. fragmentSource = baseName.fragment || baseName;
  16359. }
  16360. this._loadVertexShader(vertexSource, function (vertexCode) {
  16361. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  16362. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  16363. });
  16364. });
  16365. }
  16366. // Properties
  16367. Effect.prototype.isReady = function () {
  16368. return this._isReady;
  16369. };
  16370. Effect.prototype.getProgram = function () {
  16371. return this._program;
  16372. };
  16373. Effect.prototype.getAttributesNames = function () {
  16374. return this._attributesNames;
  16375. };
  16376. Effect.prototype.getAttributeLocation = function (index) {
  16377. return this._attributes[index];
  16378. };
  16379. Effect.prototype.getAttributeLocationByName = function (name) {
  16380. var index = this._attributesNames.indexOf(name);
  16381. return this._attributes[index];
  16382. };
  16383. Effect.prototype.getAttributesCount = function () {
  16384. return this._attributes.length;
  16385. };
  16386. Effect.prototype.getUniformIndex = function (uniformName) {
  16387. return this._uniformsNames.indexOf(uniformName);
  16388. };
  16389. Effect.prototype.getUniform = function (uniformName) {
  16390. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  16391. };
  16392. Effect.prototype.getSamplers = function () {
  16393. return this._samplers;
  16394. };
  16395. Effect.prototype.getCompilationError = function () {
  16396. return this._compilationError;
  16397. };
  16398. // Methods
  16399. Effect.prototype._loadVertexShader = function (vertex, callback) {
  16400. // DOM element ?
  16401. if (vertex instanceof HTMLElement) {
  16402. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  16403. callback(vertexCode);
  16404. return;
  16405. }
  16406. // Is in local store ?
  16407. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  16408. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  16409. return;
  16410. }
  16411. var vertexShaderUrl;
  16412. if (vertex[0] === ".") {
  16413. vertexShaderUrl = vertex;
  16414. }
  16415. else {
  16416. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  16417. }
  16418. // Vertex shader
  16419. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  16420. };
  16421. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  16422. // DOM element ?
  16423. if (fragment instanceof HTMLElement) {
  16424. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  16425. callback(fragmentCode);
  16426. return;
  16427. }
  16428. // Is in local store ?
  16429. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  16430. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  16431. return;
  16432. }
  16433. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  16434. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  16435. return;
  16436. }
  16437. var fragmentShaderUrl;
  16438. if (fragment[0] === ".") {
  16439. fragmentShaderUrl = fragment;
  16440. }
  16441. else {
  16442. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  16443. }
  16444. // Fragment shader
  16445. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  16446. };
  16447. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  16448. try {
  16449. var engine = this._engine;
  16450. if (!engine.getCaps().highPrecisionShaderSupported) {
  16451. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  16452. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  16453. }
  16454. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  16455. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  16456. this._attributes = engine.getAttributes(this._program, attributesNames);
  16457. for (var index = 0; index < this._samplers.length; index++) {
  16458. var sampler = this.getUniform(this._samplers[index]);
  16459. if (sampler == null) {
  16460. this._samplers.splice(index, 1);
  16461. index--;
  16462. }
  16463. }
  16464. engine.bindSamplers(this);
  16465. this._isReady = true;
  16466. if (this.onCompiled) {
  16467. this.onCompiled(this);
  16468. }
  16469. }
  16470. catch (e) {
  16471. // Is it a problem with precision?
  16472. if (e.message.indexOf("highp") !== -1) {
  16473. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  16474. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  16475. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  16476. return;
  16477. }
  16478. // Let's go through fallbacks then
  16479. if (fallbacks && fallbacks.isMoreFallbacks) {
  16480. defines = fallbacks.reduce(defines);
  16481. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  16482. }
  16483. else {
  16484. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  16485. BABYLON.Tools.Error("Defines: " + defines);
  16486. BABYLON.Tools.Error("Error: " + e.message);
  16487. this._compilationError = e.message;
  16488. if (this.onError) {
  16489. this.onError(this, this._compilationError);
  16490. }
  16491. }
  16492. }
  16493. };
  16494. Effect.prototype._bindTexture = function (channel, texture) {
  16495. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  16496. };
  16497. Effect.prototype.setTexture = function (channel, texture) {
  16498. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  16499. };
  16500. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16501. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  16502. };
  16503. //public _cacheMatrix(uniformName, matrix) {
  16504. // if (!this._valueCache[uniformName]) {
  16505. // this._valueCache[uniformName] = new BABYLON.Matrix();
  16506. // }
  16507. // for (var index = 0; index < 16; index++) {
  16508. // this._valueCache[uniformName].m[index] = matrix.m[index];
  16509. // }
  16510. //};
  16511. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  16512. if (!this._valueCache[uniformName]) {
  16513. this._valueCache[uniformName] = [x, y];
  16514. return;
  16515. }
  16516. this._valueCache[uniformName][0] = x;
  16517. this._valueCache[uniformName][1] = y;
  16518. };
  16519. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  16520. if (!this._valueCache[uniformName]) {
  16521. this._valueCache[uniformName] = [x, y, z];
  16522. return;
  16523. }
  16524. this._valueCache[uniformName][0] = x;
  16525. this._valueCache[uniformName][1] = y;
  16526. this._valueCache[uniformName][2] = z;
  16527. };
  16528. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  16529. if (!this._valueCache[uniformName]) {
  16530. this._valueCache[uniformName] = [x, y, z, w];
  16531. return;
  16532. }
  16533. this._valueCache[uniformName][0] = x;
  16534. this._valueCache[uniformName][1] = y;
  16535. this._valueCache[uniformName][2] = z;
  16536. this._valueCache[uniformName][3] = w;
  16537. };
  16538. Effect.prototype.setArray = function (uniformName, array) {
  16539. this._engine.setArray(this.getUniform(uniformName), array);
  16540. return this;
  16541. };
  16542. Effect.prototype.setArray2 = function (uniformName, array) {
  16543. this._engine.setArray2(this.getUniform(uniformName), array);
  16544. return this;
  16545. };
  16546. Effect.prototype.setArray3 = function (uniformName, array) {
  16547. this._engine.setArray3(this.getUniform(uniformName), array);
  16548. return this;
  16549. };
  16550. Effect.prototype.setArray4 = function (uniformName, array) {
  16551. this._engine.setArray4(this.getUniform(uniformName), array);
  16552. return this;
  16553. };
  16554. Effect.prototype.setMatrices = function (uniformName, matrices) {
  16555. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  16556. return this;
  16557. };
  16558. Effect.prototype.setMatrix = function (uniformName, matrix) {
  16559. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  16560. // return;
  16561. //this._cacheMatrix(uniformName, matrix);
  16562. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  16563. return this;
  16564. };
  16565. Effect.prototype.setFloat = function (uniformName, value) {
  16566. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  16567. return this;
  16568. this._valueCache[uniformName] = value;
  16569. this._engine.setFloat(this.getUniform(uniformName), value);
  16570. return this;
  16571. };
  16572. Effect.prototype.setBool = function (uniformName, bool) {
  16573. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  16574. return this;
  16575. this._valueCache[uniformName] = bool;
  16576. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  16577. return this;
  16578. };
  16579. Effect.prototype.setVector2 = function (uniformName, vector2) {
  16580. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  16581. return this;
  16582. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  16583. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  16584. return this;
  16585. };
  16586. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  16587. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  16588. return this;
  16589. this._cacheFloat2(uniformName, x, y);
  16590. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  16591. return this;
  16592. };
  16593. Effect.prototype.setVector3 = function (uniformName, vector3) {
  16594. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  16595. return this;
  16596. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  16597. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  16598. return this;
  16599. };
  16600. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  16601. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  16602. return this;
  16603. this._cacheFloat3(uniformName, x, y, z);
  16604. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  16605. return this;
  16606. };
  16607. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  16608. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  16609. return this;
  16610. this._cacheFloat4(uniformName, x, y, z, w);
  16611. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  16612. return this;
  16613. };
  16614. Effect.prototype.setColor3 = function (uniformName, color3) {
  16615. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  16616. return this;
  16617. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  16618. this._engine.setColor3(this.getUniform(uniformName), color3);
  16619. return this;
  16620. };
  16621. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  16622. 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)
  16623. return this;
  16624. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  16625. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  16626. return this;
  16627. };
  16628. // Statics
  16629. Effect.ShadersStore = {};
  16630. return Effect;
  16631. })();
  16632. BABYLON.Effect = Effect;
  16633. })(BABYLON || (BABYLON = {}));
  16634. //# sourceMappingURL=babylon.effect.js.map
  16635. var BABYLON;
  16636. (function (BABYLON) {
  16637. var Material = (function () {
  16638. function Material(name, scene, doNotAdd) {
  16639. this.name = name;
  16640. this.checkReadyOnEveryCall = true;
  16641. this.checkReadyOnlyOnce = false;
  16642. this.state = "";
  16643. this.alpha = 1.0;
  16644. this.backFaceCulling = true;
  16645. this._wasPreviouslyReady = false;
  16646. this._fillMode = Material.TriangleFillMode;
  16647. this.pointSize = 1.0;
  16648. this.zOffset = 0;
  16649. this.id = name;
  16650. this._scene = scene;
  16651. if (!doNotAdd) {
  16652. scene.materials.push(this);
  16653. }
  16654. }
  16655. Object.defineProperty(Material, "TriangleFillMode", {
  16656. get: function () {
  16657. return Material._TriangleFillMode;
  16658. },
  16659. enumerable: true,
  16660. configurable: true
  16661. });
  16662. Object.defineProperty(Material, "WireFrameFillMode", {
  16663. get: function () {
  16664. return Material._WireFrameFillMode;
  16665. },
  16666. enumerable: true,
  16667. configurable: true
  16668. });
  16669. Object.defineProperty(Material, "PointFillMode", {
  16670. get: function () {
  16671. return Material._PointFillMode;
  16672. },
  16673. enumerable: true,
  16674. configurable: true
  16675. });
  16676. Object.defineProperty(Material.prototype, "wireframe", {
  16677. get: function () {
  16678. return this._fillMode === Material.WireFrameFillMode;
  16679. },
  16680. set: function (value) {
  16681. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  16682. },
  16683. enumerable: true,
  16684. configurable: true
  16685. });
  16686. Object.defineProperty(Material.prototype, "pointsCloud", {
  16687. get: function () {
  16688. return this._fillMode === Material.PointFillMode;
  16689. },
  16690. set: function (value) {
  16691. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  16692. },
  16693. enumerable: true,
  16694. configurable: true
  16695. });
  16696. Object.defineProperty(Material.prototype, "fillMode", {
  16697. get: function () {
  16698. return this._fillMode;
  16699. },
  16700. set: function (value) {
  16701. this._fillMode = value;
  16702. },
  16703. enumerable: true,
  16704. configurable: true
  16705. });
  16706. Material.prototype.isReady = function (mesh, useInstances) {
  16707. return true;
  16708. };
  16709. Material.prototype.getEffect = function () {
  16710. return this._effect;
  16711. };
  16712. Material.prototype.getScene = function () {
  16713. return this._scene;
  16714. };
  16715. Material.prototype.needAlphaBlending = function () {
  16716. return (this.alpha < 1.0);
  16717. };
  16718. Material.prototype.needAlphaTesting = function () {
  16719. return false;
  16720. };
  16721. Material.prototype.getAlphaTestTexture = function () {
  16722. return null;
  16723. };
  16724. Material.prototype.trackCreation = function (onCompiled, onError) {
  16725. };
  16726. Material.prototype._preBind = function () {
  16727. var engine = this._scene.getEngine();
  16728. engine.enableEffect(this._effect);
  16729. engine.setState(this.backFaceCulling, this.zOffset);
  16730. };
  16731. Material.prototype.bind = function (world, mesh) {
  16732. this._scene._cachedMaterial = this;
  16733. if (this.onBind) {
  16734. this.onBind(this, mesh);
  16735. }
  16736. };
  16737. Material.prototype.bindOnlyWorldMatrix = function (world) {
  16738. };
  16739. Material.prototype.unbind = function () {
  16740. };
  16741. Material.prototype.dispose = function (forceDisposeEffect) {
  16742. // Remove from scene
  16743. var index = this._scene.materials.indexOf(this);
  16744. this._scene.materials.splice(index, 1);
  16745. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  16746. if (forceDisposeEffect && this._effect) {
  16747. this._scene.getEngine()._releaseEffect(this._effect);
  16748. this._effect = null;
  16749. }
  16750. // Callback
  16751. if (this.onDispose) {
  16752. this.onDispose();
  16753. }
  16754. };
  16755. Material._TriangleFillMode = 0;
  16756. Material._WireFrameFillMode = 1;
  16757. Material._PointFillMode = 2;
  16758. return Material;
  16759. })();
  16760. BABYLON.Material = Material;
  16761. })(BABYLON || (BABYLON = {}));
  16762. //# sourceMappingURL=babylon.material.js.map
  16763. var __extends = this.__extends || function (d, b) {
  16764. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16765. function __() { this.constructor = d; }
  16766. __.prototype = b.prototype;
  16767. d.prototype = new __();
  16768. };
  16769. var BABYLON;
  16770. (function (BABYLON) {
  16771. var maxSimultaneousLights = 4;
  16772. var FresnelParameters = (function () {
  16773. function FresnelParameters() {
  16774. this.isEnabled = true;
  16775. this.leftColor = BABYLON.Color3.White();
  16776. this.rightColor = BABYLON.Color3.Black();
  16777. this.bias = 0;
  16778. this.power = 1;
  16779. }
  16780. return FresnelParameters;
  16781. })();
  16782. BABYLON.FresnelParameters = FresnelParameters;
  16783. var StandardMaterial = (function (_super) {
  16784. __extends(StandardMaterial, _super);
  16785. function StandardMaterial(name, scene) {
  16786. var _this = this;
  16787. _super.call(this, name, scene);
  16788. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16789. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  16790. this.specularColor = new BABYLON.Color3(1, 1, 1);
  16791. this.specularPower = 64;
  16792. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  16793. this.useAlphaFromDiffuseTexture = false;
  16794. this.useSpecularOverAlpha = true;
  16795. this.fogEnabled = true;
  16796. this._cachedDefines = null;
  16797. this._renderTargets = new BABYLON.SmartArray(16);
  16798. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  16799. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  16800. this._scaledDiffuse = new BABYLON.Color3();
  16801. this._scaledSpecular = new BABYLON.Color3();
  16802. this.getRenderTargetTextures = function () {
  16803. _this._renderTargets.reset();
  16804. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  16805. _this._renderTargets.push(_this.reflectionTexture);
  16806. }
  16807. return _this._renderTargets;
  16808. };
  16809. }
  16810. StandardMaterial.prototype.needAlphaBlending = function () {
  16811. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  16812. };
  16813. StandardMaterial.prototype.needAlphaTesting = function () {
  16814. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  16815. };
  16816. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  16817. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  16818. };
  16819. StandardMaterial.prototype.getAlphaTestTexture = function () {
  16820. return this.diffuseTexture;
  16821. };
  16822. // Methods
  16823. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  16824. if (this.checkReadyOnlyOnce) {
  16825. if (this._wasPreviouslyReady) {
  16826. }
  16827. }
  16828. var scene = this.getScene();
  16829. if (!this.checkReadyOnEveryCall) {
  16830. if (this._renderId === scene.getRenderId()) {
  16831. }
  16832. }
  16833. var engine = scene.getEngine();
  16834. var defines = [];
  16835. var fallbacks = new BABYLON.EffectFallbacks();
  16836. var needNormals = false;
  16837. var needUVs = false;
  16838. // Textures
  16839. if (scene.texturesEnabled) {
  16840. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  16841. if (!this.diffuseTexture.isReady()) {
  16842. return false;
  16843. }
  16844. else {
  16845. needUVs = true;
  16846. defines.push("#define DIFFUSE");
  16847. }
  16848. }
  16849. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  16850. if (!this.ambientTexture.isReady()) {
  16851. return false;
  16852. }
  16853. else {
  16854. needUVs = true;
  16855. defines.push("#define AMBIENT");
  16856. }
  16857. }
  16858. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  16859. if (!this.opacityTexture.isReady()) {
  16860. return false;
  16861. }
  16862. else {
  16863. needUVs = true;
  16864. defines.push("#define OPACITY");
  16865. if (this.opacityTexture.getAlphaFromRGB) {
  16866. defines.push("#define OPACITYRGB");
  16867. }
  16868. }
  16869. }
  16870. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  16871. if (!this.reflectionTexture.isReady()) {
  16872. return false;
  16873. }
  16874. else {
  16875. needNormals = true;
  16876. needUVs = true;
  16877. defines.push("#define REFLECTION");
  16878. fallbacks.addFallback(0, "REFLECTION");
  16879. }
  16880. }
  16881. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  16882. if (!this.emissiveTexture.isReady()) {
  16883. return false;
  16884. }
  16885. else {
  16886. needUVs = true;
  16887. defines.push("#define EMISSIVE");
  16888. }
  16889. }
  16890. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  16891. if (!this.specularTexture.isReady()) {
  16892. return false;
  16893. }
  16894. else {
  16895. needUVs = true;
  16896. defines.push("#define SPECULAR");
  16897. fallbacks.addFallback(0, "SPECULAR");
  16898. }
  16899. }
  16900. }
  16901. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  16902. if (!this.bumpTexture.isReady()) {
  16903. return false;
  16904. }
  16905. else {
  16906. needUVs = true;
  16907. defines.push("#define BUMP");
  16908. fallbacks.addFallback(0, "BUMP");
  16909. }
  16910. }
  16911. // Effect
  16912. if (this.useSpecularOverAlpha) {
  16913. defines.push("#define SPECULAROVERALPHA");
  16914. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  16915. }
  16916. if (scene.clipPlane) {
  16917. defines.push("#define CLIPPLANE");
  16918. }
  16919. if (engine.getAlphaTesting()) {
  16920. defines.push("#define ALPHATEST");
  16921. }
  16922. if (this._shouldUseAlphaFromDiffuseTexture()) {
  16923. defines.push("#define ALPHAFROMDIFFUSE");
  16924. }
  16925. // Point size
  16926. if (this.pointsCloud || scene.forcePointsCloud) {
  16927. defines.push("#define POINTSIZE");
  16928. }
  16929. // Fog
  16930. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  16931. defines.push("#define FOG");
  16932. fallbacks.addFallback(1, "FOG");
  16933. }
  16934. var shadowsActivated = false;
  16935. var lightIndex = 0;
  16936. if (scene.lightsEnabled) {
  16937. for (var index = 0; index < scene.lights.length; index++) {
  16938. var light = scene.lights[index];
  16939. if (!light.isEnabled()) {
  16940. continue;
  16941. }
  16942. // Excluded check
  16943. if (light._excludedMeshesIds.length > 0) {
  16944. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  16945. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  16946. if (excludedMesh) {
  16947. light.excludedMeshes.push(excludedMesh);
  16948. }
  16949. }
  16950. light._excludedMeshesIds = [];
  16951. }
  16952. // Included check
  16953. if (light._includedOnlyMeshesIds.length > 0) {
  16954. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  16955. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  16956. if (includedOnlyMesh) {
  16957. light.includedOnlyMeshes.push(includedOnlyMesh);
  16958. }
  16959. }
  16960. light._includedOnlyMeshesIds = [];
  16961. }
  16962. if (!light.canAffectMesh(mesh)) {
  16963. continue;
  16964. }
  16965. needNormals = true;
  16966. defines.push("#define LIGHT" + lightIndex);
  16967. if (lightIndex > 0) {
  16968. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  16969. }
  16970. var type;
  16971. if (light instanceof BABYLON.SpotLight) {
  16972. type = "#define SPOTLIGHT" + lightIndex;
  16973. }
  16974. else if (light instanceof BABYLON.HemisphericLight) {
  16975. type = "#define HEMILIGHT" + lightIndex;
  16976. }
  16977. else {
  16978. type = "#define POINTDIRLIGHT" + lightIndex;
  16979. }
  16980. defines.push(type);
  16981. if (lightIndex > 0) {
  16982. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  16983. }
  16984. // Shadows
  16985. if (scene.shadowsEnabled) {
  16986. var shadowGenerator = light.getShadowGenerator();
  16987. if (mesh && mesh.receiveShadows && shadowGenerator) {
  16988. defines.push("#define SHADOW" + lightIndex);
  16989. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  16990. if (!shadowsActivated) {
  16991. defines.push("#define SHADOWS");
  16992. shadowsActivated = true;
  16993. }
  16994. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  16995. defines.push("#define SHADOWVSM" + lightIndex);
  16996. if (lightIndex > 0) {
  16997. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  16998. }
  16999. }
  17000. if (shadowGenerator.usePoissonSampling) {
  17001. defines.push("#define SHADOWPCF" + lightIndex);
  17002. if (lightIndex > 0) {
  17003. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  17004. }
  17005. }
  17006. }
  17007. }
  17008. lightIndex++;
  17009. if (lightIndex === maxSimultaneousLights)
  17010. break;
  17011. }
  17012. }
  17013. if (StandardMaterial.FresnelEnabled) {
  17014. // Fresnel
  17015. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  17016. var fresnelRank = 1;
  17017. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  17018. defines.push("#define DIFFUSEFRESNEL");
  17019. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  17020. fresnelRank++;
  17021. }
  17022. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  17023. defines.push("#define OPACITYFRESNEL");
  17024. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  17025. fresnelRank++;
  17026. }
  17027. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  17028. defines.push("#define REFLECTIONFRESNEL");
  17029. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  17030. fresnelRank++;
  17031. }
  17032. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  17033. defines.push("#define EMISSIVEFRESNEL");
  17034. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  17035. fresnelRank++;
  17036. }
  17037. needNormals = true;
  17038. defines.push("#define FRESNEL");
  17039. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  17040. }
  17041. }
  17042. // Attribs
  17043. var attribs = [BABYLON.VertexBuffer.PositionKind];
  17044. if (mesh) {
  17045. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17046. attribs.push(BABYLON.VertexBuffer.NormalKind);
  17047. defines.push("#define NORMAL");
  17048. }
  17049. if (needUVs) {
  17050. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17051. attribs.push(BABYLON.VertexBuffer.UVKind);
  17052. defines.push("#define UV1");
  17053. }
  17054. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17055. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  17056. defines.push("#define UV2");
  17057. }
  17058. }
  17059. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17060. attribs.push(BABYLON.VertexBuffer.ColorKind);
  17061. defines.push("#define VERTEXCOLOR");
  17062. if (mesh.hasVertexAlpha) {
  17063. defines.push("#define VERTEXALPHA");
  17064. }
  17065. }
  17066. if (mesh.useBones) {
  17067. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17068. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17069. defines.push("#define BONES");
  17070. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  17071. defines.push("#define BONES4");
  17072. fallbacks.addFallback(0, "BONES4");
  17073. }
  17074. // Instances
  17075. if (useInstances) {
  17076. defines.push("#define INSTANCES");
  17077. attribs.push("world0");
  17078. attribs.push("world1");
  17079. attribs.push("world2");
  17080. attribs.push("world3");
  17081. }
  17082. }
  17083. // Get correct effect
  17084. var join = defines.join("\n");
  17085. if (this._cachedDefines !== join) {
  17086. this._cachedDefines = join;
  17087. scene.resetCachedMaterial();
  17088. // Legacy browser patch
  17089. var shaderName = "default";
  17090. if (!scene.getEngine().getCaps().standardDerivatives) {
  17091. shaderName = "legacydefault";
  17092. }
  17093. 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);
  17094. }
  17095. if (!this._effect.isReady()) {
  17096. return false;
  17097. }
  17098. this._renderId = scene.getRenderId();
  17099. this._wasPreviouslyReady = true;
  17100. return true;
  17101. };
  17102. StandardMaterial.prototype.unbind = function () {
  17103. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  17104. this._effect.setTexture("reflection2DSampler", null);
  17105. }
  17106. };
  17107. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  17108. this._effect.setMatrix("world", world);
  17109. };
  17110. StandardMaterial.prototype.bind = function (world, mesh) {
  17111. var scene = this.getScene();
  17112. // Matrices
  17113. this.bindOnlyWorldMatrix(world);
  17114. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  17115. // Bones
  17116. if (mesh && mesh.useBones) {
  17117. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  17118. }
  17119. if (scene.getCachedMaterial() !== this) {
  17120. if (StandardMaterial.FresnelEnabled) {
  17121. // Fresnel
  17122. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  17123. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  17124. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  17125. }
  17126. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  17127. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  17128. }
  17129. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  17130. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  17131. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  17132. }
  17133. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  17134. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  17135. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  17136. }
  17137. }
  17138. // Textures
  17139. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  17140. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  17141. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  17142. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  17143. }
  17144. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  17145. this._effect.setTexture("ambientSampler", this.ambientTexture);
  17146. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  17147. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  17148. }
  17149. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  17150. this._effect.setTexture("opacitySampler", this.opacityTexture);
  17151. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  17152. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  17153. }
  17154. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  17155. if (this.reflectionTexture.isCube) {
  17156. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  17157. }
  17158. else {
  17159. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  17160. }
  17161. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  17162. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  17163. }
  17164. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  17165. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  17166. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  17167. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  17168. }
  17169. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  17170. this._effect.setTexture("specularSampler", this.specularTexture);
  17171. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  17172. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  17173. }
  17174. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  17175. this._effect.setTexture("bumpSampler", this.bumpTexture);
  17176. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  17177. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  17178. }
  17179. // Clip plane
  17180. if (scene.clipPlane) {
  17181. var clipPlane = scene.clipPlane;
  17182. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  17183. }
  17184. // Point size
  17185. if (this.pointsCloud) {
  17186. this._effect.setFloat("pointSize", this.pointSize);
  17187. }
  17188. // Colors
  17189. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  17190. // Scaling down color according to emissive
  17191. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  17192. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  17193. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  17194. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  17195. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  17196. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  17197. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  17198. }
  17199. // Scaling down color according to emissive
  17200. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  17201. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  17202. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  17203. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  17204. if (scene.lightsEnabled) {
  17205. var lightIndex = 0;
  17206. for (var index = 0; index < scene.lights.length; index++) {
  17207. var light = scene.lights[index];
  17208. if (!light.isEnabled()) {
  17209. continue;
  17210. }
  17211. if (!light.canAffectMesh(mesh)) {
  17212. continue;
  17213. }
  17214. if (light instanceof BABYLON.PointLight) {
  17215. // Point Light
  17216. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  17217. }
  17218. else if (light instanceof BABYLON.DirectionalLight) {
  17219. // Directional Light
  17220. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  17221. }
  17222. else if (light instanceof BABYLON.SpotLight) {
  17223. // Spot Light
  17224. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  17225. }
  17226. else if (light instanceof BABYLON.HemisphericLight) {
  17227. // Hemispheric Light
  17228. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  17229. }
  17230. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  17231. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  17232. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  17233. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  17234. // Shadows
  17235. if (scene.shadowsEnabled) {
  17236. var shadowGenerator = light.getShadowGenerator();
  17237. if (mesh.receiveShadows && shadowGenerator) {
  17238. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  17239. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  17240. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  17241. }
  17242. }
  17243. lightIndex++;
  17244. if (lightIndex === maxSimultaneousLights)
  17245. break;
  17246. }
  17247. }
  17248. // View
  17249. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  17250. this._effect.setMatrix("view", scene.getViewMatrix());
  17251. }
  17252. // Fog
  17253. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  17254. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  17255. this._effect.setColor3("vFogColor", scene.fogColor);
  17256. }
  17257. _super.prototype.bind.call(this, world, mesh);
  17258. };
  17259. StandardMaterial.prototype.getAnimatables = function () {
  17260. var results = [];
  17261. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  17262. results.push(this.diffuseTexture);
  17263. }
  17264. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  17265. results.push(this.ambientTexture);
  17266. }
  17267. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  17268. results.push(this.opacityTexture);
  17269. }
  17270. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  17271. results.push(this.reflectionTexture);
  17272. }
  17273. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  17274. results.push(this.emissiveTexture);
  17275. }
  17276. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  17277. results.push(this.specularTexture);
  17278. }
  17279. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  17280. results.push(this.bumpTexture);
  17281. }
  17282. return results;
  17283. };
  17284. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  17285. if (this.diffuseTexture) {
  17286. this.diffuseTexture.dispose();
  17287. }
  17288. if (this.ambientTexture) {
  17289. this.ambientTexture.dispose();
  17290. }
  17291. if (this.opacityTexture) {
  17292. this.opacityTexture.dispose();
  17293. }
  17294. if (this.reflectionTexture) {
  17295. this.reflectionTexture.dispose();
  17296. }
  17297. if (this.emissiveTexture) {
  17298. this.emissiveTexture.dispose();
  17299. }
  17300. if (this.specularTexture) {
  17301. this.specularTexture.dispose();
  17302. }
  17303. if (this.bumpTexture) {
  17304. this.bumpTexture.dispose();
  17305. }
  17306. _super.prototype.dispose.call(this, forceDisposeEffect);
  17307. };
  17308. StandardMaterial.prototype.clone = function (name) {
  17309. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  17310. // Base material
  17311. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  17312. newStandardMaterial.alpha = this.alpha;
  17313. newStandardMaterial.fillMode = this.fillMode;
  17314. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  17315. // Standard material
  17316. if (this.diffuseTexture && this.diffuseTexture.clone) {
  17317. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  17318. }
  17319. if (this.ambientTexture && this.ambientTexture.clone) {
  17320. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  17321. }
  17322. if (this.opacityTexture && this.opacityTexture.clone) {
  17323. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  17324. }
  17325. if (this.reflectionTexture && this.reflectionTexture.clone) {
  17326. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  17327. }
  17328. if (this.emissiveTexture && this.emissiveTexture.clone) {
  17329. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  17330. }
  17331. if (this.specularTexture && this.specularTexture.clone) {
  17332. newStandardMaterial.specularTexture = this.specularTexture.clone();
  17333. }
  17334. if (this.bumpTexture && this.bumpTexture.clone) {
  17335. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  17336. }
  17337. newStandardMaterial.ambientColor = this.ambientColor.clone();
  17338. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  17339. newStandardMaterial.specularColor = this.specularColor.clone();
  17340. newStandardMaterial.specularPower = this.specularPower;
  17341. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  17342. return newStandardMaterial;
  17343. };
  17344. // Statics
  17345. // Flags used to enable or disable a type of texture for all Standard Materials
  17346. StandardMaterial.DiffuseTextureEnabled = true;
  17347. StandardMaterial.AmbientTextureEnabled = true;
  17348. StandardMaterial.OpacityTextureEnabled = true;
  17349. StandardMaterial.ReflectionTextureEnabled = true;
  17350. StandardMaterial.EmissiveTextureEnabled = true;
  17351. StandardMaterial.SpecularTextureEnabled = true;
  17352. StandardMaterial.BumpTextureEnabled = true;
  17353. StandardMaterial.FresnelEnabled = true;
  17354. return StandardMaterial;
  17355. })(BABYLON.Material);
  17356. BABYLON.StandardMaterial = StandardMaterial;
  17357. })(BABYLON || (BABYLON = {}));
  17358. //# sourceMappingURL=babylon.standardMaterial.js.map
  17359. var __extends = this.__extends || function (d, b) {
  17360. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17361. function __() { this.constructor = d; }
  17362. __.prototype = b.prototype;
  17363. d.prototype = new __();
  17364. };
  17365. var BABYLON;
  17366. (function (BABYLON) {
  17367. var MultiMaterial = (function (_super) {
  17368. __extends(MultiMaterial, _super);
  17369. function MultiMaterial(name, scene) {
  17370. _super.call(this, name, scene, true);
  17371. this.subMaterials = new Array();
  17372. scene.multiMaterials.push(this);
  17373. }
  17374. // Properties
  17375. MultiMaterial.prototype.getSubMaterial = function (index) {
  17376. if (index < 0 || index >= this.subMaterials.length) {
  17377. return this.getScene().defaultMaterial;
  17378. }
  17379. return this.subMaterials[index];
  17380. };
  17381. // Methods
  17382. MultiMaterial.prototype.isReady = function (mesh) {
  17383. for (var index = 0; index < this.subMaterials.length; index++) {
  17384. var subMaterial = this.subMaterials[index];
  17385. if (subMaterial) {
  17386. if (!this.subMaterials[index].isReady(mesh)) {
  17387. return false;
  17388. }
  17389. }
  17390. }
  17391. return true;
  17392. };
  17393. return MultiMaterial;
  17394. })(BABYLON.Material);
  17395. BABYLON.MultiMaterial = MultiMaterial;
  17396. })(BABYLON || (BABYLON = {}));
  17397. //# sourceMappingURL=babylon.multiMaterial.js.map
  17398. var BABYLON;
  17399. (function (BABYLON) {
  17400. var SceneLoader = (function () {
  17401. function SceneLoader() {
  17402. }
  17403. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17404. get: function () {
  17405. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17406. },
  17407. set: function (value) {
  17408. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17409. },
  17410. enumerable: true,
  17411. configurable: true
  17412. });
  17413. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17414. get: function () {
  17415. return SceneLoader._ShowLoadingScreen;
  17416. },
  17417. set: function (value) {
  17418. SceneLoader._ShowLoadingScreen = value;
  17419. },
  17420. enumerable: true,
  17421. configurable: true
  17422. });
  17423. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17424. var dotPosition = sceneFilename.lastIndexOf(".");
  17425. var queryStringPosition = sceneFilename.indexOf("?");
  17426. if (queryStringPosition === -1) {
  17427. queryStringPosition = sceneFilename.length;
  17428. }
  17429. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17430. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17431. var plugin = this._registeredPlugins[index];
  17432. if (plugin.extensions.indexOf(extension) !== -1) {
  17433. return plugin;
  17434. }
  17435. }
  17436. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17437. };
  17438. // Public functions
  17439. SceneLoader.RegisterPlugin = function (plugin) {
  17440. plugin.extensions = plugin.extensions.toLowerCase();
  17441. SceneLoader._registeredPlugins.push(plugin);
  17442. };
  17443. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17444. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  17445. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  17446. return;
  17447. }
  17448. var manifestChecked = function (success) {
  17449. scene.database = database;
  17450. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17451. var importMeshFromData = function (data) {
  17452. var meshes = [];
  17453. var particleSystems = [];
  17454. var skeletons = [];
  17455. try {
  17456. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17457. if (onerror) {
  17458. onerror(scene, 'unable to load the scene');
  17459. }
  17460. return;
  17461. }
  17462. }
  17463. catch (e) {
  17464. if (onerror) {
  17465. onerror(scene, e);
  17466. }
  17467. return;
  17468. }
  17469. if (onsuccess) {
  17470. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17471. onsuccess(meshes, particleSystems, skeletons);
  17472. }
  17473. };
  17474. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17475. // Direct load
  17476. importMeshFromData(sceneFilename.substr(5));
  17477. return;
  17478. }
  17479. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17480. importMeshFromData(data);
  17481. }, progressCallBack, database);
  17482. };
  17483. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17484. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17485. };
  17486. /**
  17487. * Load a scene
  17488. * @param rootUrl a string that defines the root url for scene and resources
  17489. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17490. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17491. */
  17492. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17493. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17494. };
  17495. /**
  17496. * Append a scene
  17497. * @param rootUrl a string that defines the root url for scene and resources
  17498. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17499. * @param scene is the instance of BABYLON.Scene to append to
  17500. */
  17501. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17502. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  17503. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  17504. return;
  17505. }
  17506. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17507. var database;
  17508. if (SceneLoader.ShowLoadingScreen) {
  17509. scene.getEngine().displayLoadingUI();
  17510. }
  17511. var loadSceneFromData = function (data) {
  17512. scene.database = database;
  17513. if (!plugin.load(scene, data, rootUrl)) {
  17514. if (onerror) {
  17515. onerror(scene);
  17516. }
  17517. scene.getEngine().hideLoadingUI();
  17518. return;
  17519. }
  17520. if (onsuccess) {
  17521. onsuccess(scene);
  17522. }
  17523. if (SceneLoader.ShowLoadingScreen) {
  17524. scene.executeWhenReady(function () {
  17525. scene.getEngine().hideLoadingUI();
  17526. });
  17527. }
  17528. };
  17529. var manifestChecked = function (success) {
  17530. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17531. };
  17532. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17533. // Direct load
  17534. loadSceneFromData(sceneFilename.substr(5));
  17535. return;
  17536. }
  17537. if (rootUrl.indexOf("file:") === -1) {
  17538. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17539. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17540. }
  17541. else {
  17542. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17543. }
  17544. };
  17545. // Flags
  17546. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17547. SceneLoader._ShowLoadingScreen = true;
  17548. // Members
  17549. SceneLoader._registeredPlugins = new Array();
  17550. return SceneLoader;
  17551. })();
  17552. BABYLON.SceneLoader = SceneLoader;
  17553. ;
  17554. })(BABYLON || (BABYLON = {}));
  17555. //# sourceMappingURL=babylon.sceneLoader.js.map
  17556. var BABYLON;
  17557. (function (BABYLON) {
  17558. var Internals;
  17559. (function (Internals) {
  17560. var checkColors4 = function (colors, count) {
  17561. // Check if color3 was used
  17562. if (colors.length === count * 3) {
  17563. var colors4 = [];
  17564. for (var index = 0; index < colors.length; index += 3) {
  17565. var newIndex = (index / 3) * 4;
  17566. colors4[newIndex] = colors[index];
  17567. colors4[newIndex + 1] = colors[index + 1];
  17568. colors4[newIndex + 2] = colors[index + 2];
  17569. colors4[newIndex + 3] = 1.0;
  17570. }
  17571. return colors4;
  17572. }
  17573. return colors;
  17574. };
  17575. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  17576. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  17577. texture.name = parsedTexture.name;
  17578. texture.hasAlpha = parsedTexture.hasAlpha;
  17579. texture.level = parsedTexture.level;
  17580. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17581. return texture;
  17582. };
  17583. var loadTexture = function (rootUrl, parsedTexture, scene) {
  17584. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17585. return null;
  17586. }
  17587. if (parsedTexture.isCube) {
  17588. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17589. }
  17590. var texture;
  17591. if (parsedTexture.mirrorPlane) {
  17592. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17593. texture._waitingRenderList = parsedTexture.renderList;
  17594. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17595. }
  17596. else if (parsedTexture.isRenderTarget) {
  17597. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17598. texture._waitingRenderList = parsedTexture.renderList;
  17599. }
  17600. else {
  17601. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17602. }
  17603. texture.name = parsedTexture.name;
  17604. texture.hasAlpha = parsedTexture.hasAlpha;
  17605. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17606. texture.level = parsedTexture.level;
  17607. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17608. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17609. texture.uOffset = parsedTexture.uOffset;
  17610. texture.vOffset = parsedTexture.vOffset;
  17611. texture.uScale = parsedTexture.uScale;
  17612. texture.vScale = parsedTexture.vScale;
  17613. texture.uAng = parsedTexture.uAng;
  17614. texture.vAng = parsedTexture.vAng;
  17615. texture.wAng = parsedTexture.wAng;
  17616. texture.wrapU = parsedTexture.wrapU;
  17617. texture.wrapV = parsedTexture.wrapV;
  17618. // Animations
  17619. if (parsedTexture.animations) {
  17620. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17621. var parsedAnimation = parsedTexture.animations[animationIndex];
  17622. texture.animations.push(parseAnimation(parsedAnimation));
  17623. }
  17624. }
  17625. return texture;
  17626. };
  17627. var parseSkeleton = function (parsedSkeleton, scene) {
  17628. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  17629. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  17630. var parsedBone = parsedSkeleton.bones[index];
  17631. var parentBone = null;
  17632. if (parsedBone.parentBoneIndex > -1) {
  17633. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  17634. }
  17635. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  17636. if (parsedBone.animation) {
  17637. bone.animations.push(parseAnimation(parsedBone.animation));
  17638. }
  17639. }
  17640. return skeleton;
  17641. };
  17642. var parseFresnelParameters = function (parsedFresnelParameters) {
  17643. var fresnelParameters = new BABYLON.FresnelParameters();
  17644. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  17645. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  17646. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  17647. fresnelParameters.bias = parsedFresnelParameters.bias;
  17648. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  17649. return fresnelParameters;
  17650. };
  17651. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  17652. var material;
  17653. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  17654. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  17655. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  17656. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  17657. material.specularPower = parsedMaterial.specularPower;
  17658. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  17659. material.alpha = parsedMaterial.alpha;
  17660. material.id = parsedMaterial.id;
  17661. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  17662. material.backFaceCulling = parsedMaterial.backFaceCulling;
  17663. material.wireframe = parsedMaterial.wireframe;
  17664. if (parsedMaterial.diffuseTexture) {
  17665. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  17666. }
  17667. if (parsedMaterial.diffuseFresnelParameters) {
  17668. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  17669. }
  17670. if (parsedMaterial.ambientTexture) {
  17671. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  17672. }
  17673. if (parsedMaterial.opacityTexture) {
  17674. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  17675. }
  17676. if (parsedMaterial.opacityFresnelParameters) {
  17677. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  17678. }
  17679. if (parsedMaterial.reflectionTexture) {
  17680. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  17681. }
  17682. if (parsedMaterial.reflectionFresnelParameters) {
  17683. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  17684. }
  17685. if (parsedMaterial.emissiveTexture) {
  17686. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  17687. }
  17688. if (parsedMaterial.emissiveFresnelParameters) {
  17689. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  17690. }
  17691. if (parsedMaterial.specularTexture) {
  17692. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  17693. }
  17694. if (parsedMaterial.bumpTexture) {
  17695. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  17696. }
  17697. return material;
  17698. };
  17699. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  17700. for (var index = 0; index < parsedData.materials.length; index++) {
  17701. var parsedMaterial = parsedData.materials[index];
  17702. if (parsedMaterial.id === id) {
  17703. return parseMaterial(parsedMaterial, scene, rootUrl);
  17704. }
  17705. }
  17706. return null;
  17707. };
  17708. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  17709. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17710. multiMaterial.id = parsedMultiMaterial.id;
  17711. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17712. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17713. var subMatId = parsedMultiMaterial.materials[matIndex];
  17714. if (subMatId) {
  17715. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17716. }
  17717. else {
  17718. multiMaterial.subMaterials.push(null);
  17719. }
  17720. }
  17721. return multiMaterial;
  17722. };
  17723. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17724. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17725. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17726. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17727. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17728. var parsedFlare = parsedLensFlareSystem.flares[index];
  17729. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17730. }
  17731. return lensFlareSystem;
  17732. };
  17733. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17734. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17735. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17736. if (parsedParticleSystem.textureName) {
  17737. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17738. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17739. }
  17740. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17741. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17742. particleSystem.minSize = parsedParticleSystem.minSize;
  17743. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17744. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17745. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17746. particleSystem.emitter = emitter;
  17747. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17748. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17749. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17750. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17751. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17752. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17753. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17754. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17755. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17756. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17757. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17758. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17759. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17760. particleSystem.start();
  17761. return particleSystem;
  17762. };
  17763. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17764. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17765. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17766. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17767. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17768. shadowGenerator.getShadowMap().renderList.push(mesh);
  17769. }
  17770. if (parsedShadowGenerator.usePoissonSampling) {
  17771. shadowGenerator.usePoissonSampling = true;
  17772. }
  17773. else if (parsedShadowGenerator.useVarianceShadowMap) {
  17774. shadowGenerator.useVarianceShadowMap = true;
  17775. }
  17776. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  17777. shadowGenerator.useBlurVarianceShadowMap = true;
  17778. if (parsedShadowGenerator.blurScale) {
  17779. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  17780. }
  17781. if (parsedShadowGenerator.blurBoxOffset) {
  17782. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  17783. }
  17784. }
  17785. if (parsedShadowGenerator.bias !== undefined) {
  17786. shadowGenerator.bias = parsedShadowGenerator.bias;
  17787. }
  17788. return shadowGenerator;
  17789. };
  17790. var parseAnimation = function (parsedAnimation) {
  17791. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17792. var dataType = parsedAnimation.dataType;
  17793. var keys = [];
  17794. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17795. var key = parsedAnimation.keys[index];
  17796. var data;
  17797. switch (dataType) {
  17798. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17799. data = key.values[0];
  17800. break;
  17801. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17802. data = BABYLON.Quaternion.FromArray(key.values);
  17803. break;
  17804. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17805. data = BABYLON.Matrix.FromArray(key.values);
  17806. break;
  17807. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17808. default:
  17809. data = BABYLON.Vector3.FromArray(key.values);
  17810. break;
  17811. }
  17812. keys.push({
  17813. frame: key.frame,
  17814. value: data
  17815. });
  17816. }
  17817. animation.setKeys(keys);
  17818. return animation;
  17819. };
  17820. var parseLight = function (parsedLight, scene) {
  17821. var light;
  17822. switch (parsedLight.type) {
  17823. case 0:
  17824. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17825. break;
  17826. case 1:
  17827. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17828. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17829. break;
  17830. case 2:
  17831. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  17832. break;
  17833. case 3:
  17834. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17835. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  17836. break;
  17837. }
  17838. light.id = parsedLight.id;
  17839. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  17840. if (parsedLight.intensity !== undefined) {
  17841. light.intensity = parsedLight.intensity;
  17842. }
  17843. if (parsedLight.range) {
  17844. light.range = parsedLight.range;
  17845. }
  17846. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  17847. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  17848. if (parsedLight.excludedMeshesIds) {
  17849. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17850. }
  17851. // Parent
  17852. if (parsedLight.parentId) {
  17853. light._waitingParentId = parsedLight.parentId;
  17854. }
  17855. if (parsedLight.includedOnlyMeshesIds) {
  17856. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17857. }
  17858. // Animations
  17859. if (parsedLight.animations) {
  17860. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17861. var parsedAnimation = parsedLight.animations[animationIndex];
  17862. light.animations.push(parseAnimation(parsedAnimation));
  17863. }
  17864. }
  17865. if (parsedLight.autoAnimate) {
  17866. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  17867. }
  17868. };
  17869. var parseCamera = function (parsedCamera, scene) {
  17870. var camera;
  17871. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  17872. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  17873. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  17874. var alpha = parsedCamera.alpha;
  17875. var beta = parsedCamera.beta;
  17876. var radius = parsedCamera.radius;
  17877. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  17878. var eye_space = parsedCamera.eye_space;
  17879. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  17880. }
  17881. else {
  17882. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  17883. }
  17884. }
  17885. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  17886. eye_space = parsedCamera.eye_space;
  17887. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  17888. }
  17889. else if (parsedCamera.type === "DeviceOrientationCamera") {
  17890. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  17891. }
  17892. else if (parsedCamera.type === "FollowCamera") {
  17893. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  17894. camera.heightOffset = parsedCamera.heightOffset;
  17895. camera.radius = parsedCamera.radius;
  17896. camera.rotationOffset = parsedCamera.rotationOffset;
  17897. if (lockedTargetMesh)
  17898. camera.target = lockedTargetMesh;
  17899. }
  17900. else if (parsedCamera.type === "GamepadCamera") {
  17901. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  17902. }
  17903. else if (parsedCamera.type === "OculusCamera") {
  17904. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  17905. }
  17906. else if (parsedCamera.type === "OculusGamepadCamera") {
  17907. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  17908. }
  17909. else if (parsedCamera.type === "TouchCamera") {
  17910. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  17911. }
  17912. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  17913. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  17914. }
  17915. else if (parsedCamera.type === "WebVRCamera") {
  17916. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  17917. }
  17918. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  17919. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  17920. }
  17921. else {
  17922. // Free Camera is the default value
  17923. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  17924. }
  17925. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  17926. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  17927. camera.lockedTarget = lockedTargetMesh;
  17928. }
  17929. camera.id = parsedCamera.id;
  17930. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  17931. // Parent
  17932. if (parsedCamera.parentId) {
  17933. camera._waitingParentId = parsedCamera.parentId;
  17934. }
  17935. // Target
  17936. if (parsedCamera.target) {
  17937. if (camera.setTarget) {
  17938. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17939. }
  17940. else {
  17941. //For ArcRotate
  17942. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  17943. }
  17944. }
  17945. else {
  17946. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  17947. }
  17948. camera.fov = parsedCamera.fov;
  17949. camera.minZ = parsedCamera.minZ;
  17950. camera.maxZ = parsedCamera.maxZ;
  17951. camera.speed = parsedCamera.speed;
  17952. camera.inertia = parsedCamera.inertia;
  17953. camera.checkCollisions = parsedCamera.checkCollisions;
  17954. camera.applyGravity = parsedCamera.applyGravity;
  17955. if (parsedCamera.ellipsoid) {
  17956. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  17957. }
  17958. // Animations
  17959. if (parsedCamera.animations) {
  17960. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17961. var parsedAnimation = parsedCamera.animations[animationIndex];
  17962. camera.animations.push(parseAnimation(parsedAnimation));
  17963. }
  17964. }
  17965. if (parsedCamera.autoAnimate) {
  17966. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  17967. }
  17968. // Layer Mask
  17969. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  17970. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  17971. }
  17972. else {
  17973. camera.layerMask = 0xFFFFFFFF;
  17974. }
  17975. return camera;
  17976. };
  17977. var parseGeometry = function (parsedGeometry, scene) {
  17978. var id = parsedGeometry.id;
  17979. return scene.getGeometryByID(id);
  17980. };
  17981. var parseBox = function (parsedBox, scene) {
  17982. if (parseGeometry(parsedBox, scene)) {
  17983. return null; // null since geometry could be something else than a box...
  17984. }
  17985. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  17986. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  17987. scene.pushGeometry(box, true);
  17988. return box;
  17989. };
  17990. var parseSphere = function (parsedSphere, scene) {
  17991. if (parseGeometry(parsedSphere, scene)) {
  17992. return null; // null since geometry could be something else than a sphere...
  17993. }
  17994. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  17995. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  17996. scene.pushGeometry(sphere, true);
  17997. return sphere;
  17998. };
  17999. var parseCylinder = function (parsedCylinder, scene) {
  18000. if (parseGeometry(parsedCylinder, scene)) {
  18001. return null; // null since geometry could be something else than a cylinder...
  18002. }
  18003. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18004. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18005. scene.pushGeometry(cylinder, true);
  18006. return cylinder;
  18007. };
  18008. var parseTorus = function (parsedTorus, scene) {
  18009. if (parseGeometry(parsedTorus, scene)) {
  18010. return null; // null since geometry could be something else than a torus...
  18011. }
  18012. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18013. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18014. scene.pushGeometry(torus, true);
  18015. return torus;
  18016. };
  18017. var parseGround = function (parsedGround, scene) {
  18018. if (parseGeometry(parsedGround, scene)) {
  18019. return null; // null since geometry could be something else than a ground...
  18020. }
  18021. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18022. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18023. scene.pushGeometry(ground, true);
  18024. return ground;
  18025. };
  18026. var parsePlane = function (parsedPlane, scene) {
  18027. if (parseGeometry(parsedPlane, scene)) {
  18028. return null; // null since geometry could be something else than a plane...
  18029. }
  18030. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18031. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18032. scene.pushGeometry(plane, true);
  18033. return plane;
  18034. };
  18035. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18036. if (parseGeometry(parsedTorusKnot, scene)) {
  18037. return null; // null since geometry could be something else than a torusKnot...
  18038. }
  18039. 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);
  18040. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18041. scene.pushGeometry(torusKnot, true);
  18042. return torusKnot;
  18043. };
  18044. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18045. if (parseGeometry(parsedVertexData, scene)) {
  18046. return null; // null since geometry could be a primitive
  18047. }
  18048. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18049. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18050. if (parsedVertexData.delayLoadingFile) {
  18051. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18052. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18053. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18054. geometry._delayInfo = [];
  18055. if (parsedVertexData.hasUVs) {
  18056. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18057. }
  18058. if (parsedVertexData.hasUVs2) {
  18059. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18060. }
  18061. if (parsedVertexData.hasColors) {
  18062. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18063. }
  18064. if (parsedVertexData.hasMatricesIndices) {
  18065. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18066. }
  18067. if (parsedVertexData.hasMatricesWeights) {
  18068. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18069. }
  18070. geometry._delayLoadingFunction = importVertexData;
  18071. }
  18072. else {
  18073. importVertexData(parsedVertexData, geometry);
  18074. }
  18075. scene.pushGeometry(geometry, true);
  18076. return geometry;
  18077. };
  18078. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18079. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18080. mesh.id = parsedMesh.id;
  18081. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18082. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18083. if (parsedMesh.rotationQuaternion) {
  18084. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18085. }
  18086. else if (parsedMesh.rotation) {
  18087. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18088. }
  18089. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18090. if (parsedMesh.localMatrix) {
  18091. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18092. }
  18093. else if (parsedMesh.pivotMatrix) {
  18094. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18095. }
  18096. mesh.setEnabled(parsedMesh.isEnabled);
  18097. mesh.isVisible = parsedMesh.isVisible;
  18098. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18099. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18100. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18101. if (parsedMesh.applyFog !== undefined) {
  18102. mesh.applyFog = parsedMesh.applyFog;
  18103. }
  18104. if (parsedMesh.pickable !== undefined) {
  18105. mesh.isPickable = parsedMesh.pickable;
  18106. }
  18107. if (parsedMesh.alphaIndex !== undefined) {
  18108. mesh.alphaIndex = parsedMesh.alphaIndex;
  18109. }
  18110. mesh.receiveShadows = parsedMesh.receiveShadows;
  18111. mesh.billboardMode = parsedMesh.billboardMode;
  18112. if (parsedMesh.visibility !== undefined) {
  18113. mesh.visibility = parsedMesh.visibility;
  18114. }
  18115. mesh.checkCollisions = parsedMesh.checkCollisions;
  18116. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18117. // Parent
  18118. if (parsedMesh.parentId) {
  18119. mesh._waitingParentId = parsedMesh.parentId;
  18120. }
  18121. // Actions
  18122. if (parsedMesh.actions !== undefined) {
  18123. mesh._waitingActions = parsedMesh.actions;
  18124. }
  18125. // Geometry
  18126. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18127. if (parsedMesh.delayLoadingFile) {
  18128. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18129. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18130. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18131. if (parsedMesh._binaryInfo) {
  18132. mesh._binaryInfo = parsedMesh._binaryInfo;
  18133. }
  18134. mesh._delayInfo = [];
  18135. if (parsedMesh.hasUVs) {
  18136. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18137. }
  18138. if (parsedMesh.hasUVs2) {
  18139. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18140. }
  18141. if (parsedMesh.hasColors) {
  18142. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18143. }
  18144. if (parsedMesh.hasMatricesIndices) {
  18145. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18146. }
  18147. if (parsedMesh.hasMatricesWeights) {
  18148. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18149. }
  18150. mesh._delayLoadingFunction = importGeometry;
  18151. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18152. mesh._checkDelayState();
  18153. }
  18154. }
  18155. else {
  18156. importGeometry(parsedMesh, mesh);
  18157. }
  18158. // Material
  18159. if (parsedMesh.materialId) {
  18160. mesh.setMaterialByID(parsedMesh.materialId);
  18161. }
  18162. else {
  18163. mesh.material = null;
  18164. }
  18165. // Skeleton
  18166. if (parsedMesh.skeletonId > -1) {
  18167. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18168. }
  18169. // Physics
  18170. if (parsedMesh.physicsImpostor) {
  18171. if (!scene.isPhysicsEnabled()) {
  18172. scene.enablePhysics();
  18173. }
  18174. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18175. }
  18176. // Animations
  18177. if (parsedMesh.animations) {
  18178. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18179. var parsedAnimation = parsedMesh.animations[animationIndex];
  18180. mesh.animations.push(parseAnimation(parsedAnimation));
  18181. }
  18182. }
  18183. if (parsedMesh.autoAnimate) {
  18184. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18185. }
  18186. // Layer Mask
  18187. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18188. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18189. }
  18190. else {
  18191. mesh.layerMask = 0xFFFFFFFF;
  18192. }
  18193. // Instances
  18194. if (parsedMesh.instances) {
  18195. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18196. var parsedInstance = parsedMesh.instances[index];
  18197. var instance = mesh.createInstance(parsedInstance.name);
  18198. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18199. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18200. if (parsedInstance.rotationQuaternion) {
  18201. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18202. }
  18203. else if (parsedInstance.rotation) {
  18204. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18205. }
  18206. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18207. instance.checkCollisions = mesh.checkCollisions;
  18208. if (parsedMesh.animations) {
  18209. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18210. parsedAnimation = parsedMesh.animations[animationIndex];
  18211. instance.animations.push(parseAnimation(parsedAnimation));
  18212. }
  18213. }
  18214. }
  18215. }
  18216. return mesh;
  18217. };
  18218. var parseActions = function (parsedActions, object, scene) {
  18219. var actionManager = new BABYLON.ActionManager(scene);
  18220. if (object === null)
  18221. scene.actionManager = actionManager;
  18222. else
  18223. object.actionManager = actionManager;
  18224. // instanciate a new object
  18225. var instanciate = function (name, params) {
  18226. var newInstance = Object.create(BABYLON[name].prototype);
  18227. newInstance.constructor.apply(newInstance, params);
  18228. return newInstance;
  18229. };
  18230. var parseParameter = function (name, value, target, propertyPath) {
  18231. if (propertyPath === null) {
  18232. // String, boolean or float
  18233. var floatValue = parseFloat(value);
  18234. if (value === "true" || value === "false")
  18235. return value === "true";
  18236. else
  18237. return isNaN(floatValue) ? value : floatValue;
  18238. }
  18239. var effectiveTarget = propertyPath.split(".");
  18240. var values = value.split(",");
  18241. for (var i = 0; i < effectiveTarget.length; i++) {
  18242. target = target[effectiveTarget[i]];
  18243. }
  18244. // Return appropriate value with its type
  18245. if (typeof (target) === "boolean")
  18246. return values[0] === "true";
  18247. if (typeof (target) === "string")
  18248. return values[0];
  18249. // Parameters with multiple values such as Vector3 etc.
  18250. var split = new Array();
  18251. for (var i = 0; i < values.length; i++)
  18252. split.push(parseFloat(values[i]));
  18253. if (target instanceof BABYLON.Vector3)
  18254. return BABYLON.Vector3.FromArray(split);
  18255. if (target instanceof BABYLON.Vector4)
  18256. return BABYLON.Vector4.FromArray(split);
  18257. if (target instanceof BABYLON.Color3)
  18258. return BABYLON.Color3.FromArray(split);
  18259. if (target instanceof BABYLON.Color4)
  18260. return BABYLON.Color4.FromArray(split);
  18261. return parseFloat(values[0]);
  18262. };
  18263. // traverse graph per trigger
  18264. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  18265. if (combineArray === void 0) { combineArray = null; }
  18266. if (parsedAction.detached)
  18267. return;
  18268. var parameters = new Array();
  18269. var target = null;
  18270. var propertyPath = null;
  18271. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  18272. // Parameters
  18273. if (parsedAction.type === 2)
  18274. parameters.push(actionManager);
  18275. else
  18276. parameters.push(trigger);
  18277. if (combine) {
  18278. var actions = new Array();
  18279. for (var j = 0; j < parsedAction.combine.length; j++) {
  18280. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  18281. }
  18282. parameters.push(actions);
  18283. }
  18284. else {
  18285. for (var i = 0; i < parsedAction.properties.length; i++) {
  18286. var value = parsedAction.properties[i].value;
  18287. var name = parsedAction.properties[i].name;
  18288. var targetType = parsedAction.properties[i].targetType;
  18289. if (name === "target")
  18290. if (targetType !== null && targetType === "SceneProperties")
  18291. value = target = scene;
  18292. else
  18293. value = target = scene.getNodeByName(value);
  18294. else if (name === "parent")
  18295. value = scene.getNodeByName(value);
  18296. else if (name === "sound")
  18297. value = scene.getSoundByName(value);
  18298. else if (name !== "propertyPath") {
  18299. if (parsedAction.type === 2 && name === "operator")
  18300. value = BABYLON.ValueCondition[value];
  18301. else
  18302. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  18303. }
  18304. else {
  18305. propertyPath = value;
  18306. }
  18307. parameters.push(value);
  18308. }
  18309. }
  18310. if (combineArray === null) {
  18311. parameters.push(condition);
  18312. }
  18313. else {
  18314. parameters.push(null);
  18315. }
  18316. // If interpolate value action
  18317. if (parsedAction.name === "InterpolateValueAction") {
  18318. var param = parameters[parameters.length - 2];
  18319. parameters[parameters.length - 1] = param;
  18320. parameters[parameters.length - 2] = condition;
  18321. }
  18322. // Action or condition(s) and not CombineAction
  18323. var newAction = instanciate(parsedAction.name, parameters);
  18324. if (combineArray === null) {
  18325. if (newAction instanceof BABYLON.Condition) {
  18326. condition = newAction;
  18327. newAction = action;
  18328. }
  18329. else {
  18330. condition = null;
  18331. if (action)
  18332. action.then(newAction);
  18333. else
  18334. actionManager.registerAction(newAction);
  18335. }
  18336. }
  18337. else {
  18338. combineArray.push(newAction);
  18339. }
  18340. for (var i = 0; i < parsedAction.children.length; i++)
  18341. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  18342. };
  18343. for (var i = 0; i < parsedActions.children.length; i++) {
  18344. var triggerParams;
  18345. var trigger = parsedActions.children[i];
  18346. if (trigger.properties.length > 0) {
  18347. var param = trigger.properties[0].value;
  18348. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  18349. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  18350. }
  18351. else
  18352. triggerParams = BABYLON.ActionManager[trigger.name];
  18353. for (var j = 0; j < trigger.children.length; j++) {
  18354. if (!trigger.detached)
  18355. traverse(trigger.children[j], triggerParams, null, null);
  18356. }
  18357. }
  18358. };
  18359. var parseSound = function (parsedSound, scene, rootUrl) {
  18360. var soundName = parsedSound.name;
  18361. var soundUrl = rootUrl + soundName;
  18362. var options = {
  18363. autoplay: parsedSound.autoplay,
  18364. loop: parsedSound.loop,
  18365. volume: parsedSound.volume,
  18366. spatialSound: parsedSound.spatialSound,
  18367. maxDistance: parsedSound.maxDistance,
  18368. rolloffFactor: parsedSound.rolloffFactor,
  18369. refDistance: parsedSound.refDistance,
  18370. distanceModel: parsedSound.distanceModel,
  18371. playbackRate: parsedSound.playbackRate
  18372. };
  18373. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  18374. scene._removePendingData(newSound);
  18375. }, options);
  18376. scene._addPendingData(newSound);
  18377. if (parsedSound.position) {
  18378. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  18379. newSound.setPosition(soundPosition);
  18380. }
  18381. if (parsedSound.isDirectional) {
  18382. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  18383. if (parsedSound.localDirectionToMesh) {
  18384. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  18385. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  18386. }
  18387. }
  18388. if (parsedSound.connectedMeshId) {
  18389. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  18390. if (connectedMesh) {
  18391. newSound.attachToMesh(connectedMesh);
  18392. }
  18393. }
  18394. };
  18395. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18396. names = (names instanceof Array) ? names : [names];
  18397. for (var i in names) {
  18398. if (mesh.name === names[i]) {
  18399. hierarchyIds.push(mesh.id);
  18400. return true;
  18401. }
  18402. }
  18403. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18404. hierarchyIds.push(mesh.id);
  18405. return true;
  18406. }
  18407. return false;
  18408. };
  18409. var importVertexData = function (parsedVertexData, geometry) {
  18410. var vertexData = new BABYLON.VertexData();
  18411. // positions
  18412. var positions = parsedVertexData.positions;
  18413. if (positions) {
  18414. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18415. }
  18416. // normals
  18417. var normals = parsedVertexData.normals;
  18418. if (normals) {
  18419. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18420. }
  18421. // uvs
  18422. var uvs = parsedVertexData.uvs;
  18423. if (uvs) {
  18424. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18425. }
  18426. // uv2s
  18427. var uv2s = parsedVertexData.uv2s;
  18428. if (uv2s) {
  18429. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18430. }
  18431. // colors
  18432. var colors = parsedVertexData.colors;
  18433. if (colors) {
  18434. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18435. }
  18436. // matricesIndices
  18437. var matricesIndices = parsedVertexData.matricesIndices;
  18438. if (matricesIndices) {
  18439. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  18440. }
  18441. // matricesWeights
  18442. var matricesWeights = parsedVertexData.matricesWeights;
  18443. if (matricesWeights) {
  18444. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  18445. }
  18446. // indices
  18447. var indices = parsedVertexData.indices;
  18448. if (indices) {
  18449. vertexData.indices = indices;
  18450. }
  18451. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  18452. };
  18453. var importGeometry = function (parsedGeometry, mesh) {
  18454. var scene = mesh.getScene();
  18455. // Geometry
  18456. var geometryId = parsedGeometry.geometryId;
  18457. if (geometryId) {
  18458. var geometry = scene.getGeometryByID(geometryId);
  18459. if (geometry) {
  18460. geometry.applyToMesh(mesh);
  18461. }
  18462. }
  18463. else if (parsedGeometry instanceof ArrayBuffer) {
  18464. var binaryInfo = mesh._binaryInfo;
  18465. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  18466. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  18467. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  18468. }
  18469. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18470. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18471. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18472. }
  18473. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18474. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18475. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18476. }
  18477. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18478. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18479. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18480. }
  18481. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18482. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18483. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18484. }
  18485. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18486. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18487. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18488. }
  18489. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18490. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18491. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18492. }
  18493. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18494. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18495. mesh.setIndices(indicesData);
  18496. }
  18497. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18498. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18499. mesh.subMeshes = [];
  18500. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18501. var materialIndex = subMeshesData[(i * 5) + 0];
  18502. var verticesStart = subMeshesData[(i * 5) + 1];
  18503. var verticesCount = subMeshesData[(i * 5) + 2];
  18504. var indexStart = subMeshesData[(i * 5) + 3];
  18505. var indexCount = subMeshesData[(i * 5) + 4];
  18506. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18507. }
  18508. }
  18509. }
  18510. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18511. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18512. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18513. if (parsedGeometry.uvs) {
  18514. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  18515. }
  18516. if (parsedGeometry.uvs2) {
  18517. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  18518. }
  18519. if (parsedGeometry.colors) {
  18520. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  18521. }
  18522. if (parsedGeometry.matricesIndices) {
  18523. if (!parsedGeometry.matricesIndices._isExpanded) {
  18524. var floatIndices = [];
  18525. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  18526. var matricesIndex = parsedGeometry.matricesIndices[i];
  18527. floatIndices.push(matricesIndex & 0x000000FF);
  18528. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  18529. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  18530. floatIndices.push(matricesIndex >> 24);
  18531. }
  18532. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  18533. }
  18534. else {
  18535. delete parsedGeometry.matricesIndices._isExpanded;
  18536. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  18537. }
  18538. }
  18539. if (parsedGeometry.matricesWeights) {
  18540. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  18541. }
  18542. mesh.setIndices(parsedGeometry.indices);
  18543. // SubMeshes
  18544. if (parsedGeometry.subMeshes) {
  18545. mesh.subMeshes = [];
  18546. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  18547. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  18548. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  18549. }
  18550. }
  18551. }
  18552. // Flat shading
  18553. if (mesh._shouldGenerateFlatShading) {
  18554. mesh.convertToFlatShadedMesh();
  18555. delete mesh._shouldGenerateFlatShading;
  18556. }
  18557. // Update
  18558. mesh.computeWorldMatrix(true);
  18559. // Octree
  18560. if (scene._selectionOctree) {
  18561. scene._selectionOctree.addMesh(mesh);
  18562. }
  18563. };
  18564. BABYLON.SceneLoader.RegisterPlugin({
  18565. extensions: ".babylon",
  18566. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  18567. var parsedData = JSON.parse(data);
  18568. var loadedSkeletonsIds = [];
  18569. var loadedMaterialsIds = [];
  18570. var hierarchyIds = [];
  18571. for (var index = 0; index < parsedData.meshes.length; index++) {
  18572. var parsedMesh = parsedData.meshes[index];
  18573. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  18574. if (meshesNames instanceof Array) {
  18575. // Remove found mesh name from list.
  18576. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  18577. }
  18578. // Material ?
  18579. if (parsedMesh.materialId) {
  18580. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  18581. if (!materialFound) {
  18582. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  18583. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  18584. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  18585. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18586. var subMatId = parsedMultiMaterial.materials[matIndex];
  18587. loadedMaterialsIds.push(subMatId);
  18588. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  18589. }
  18590. loadedMaterialsIds.push(parsedMultiMaterial.id);
  18591. parseMultiMaterial(parsedMultiMaterial, scene);
  18592. materialFound = true;
  18593. break;
  18594. }
  18595. }
  18596. }
  18597. if (!materialFound) {
  18598. loadedMaterialsIds.push(parsedMesh.materialId);
  18599. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  18600. }
  18601. }
  18602. // Skeleton ?
  18603. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  18604. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  18605. if (!skeletonAlreadyLoaded) {
  18606. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  18607. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  18608. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  18609. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  18610. loadedSkeletonsIds.push(parsedSkeleton.id);
  18611. }
  18612. }
  18613. }
  18614. }
  18615. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  18616. meshes.push(mesh);
  18617. }
  18618. }
  18619. for (index = 0; index < scene.meshes.length; index++) {
  18620. var currentMesh = scene.meshes[index];
  18621. if (currentMesh._waitingParentId) {
  18622. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  18623. currentMesh._waitingParentId = undefined;
  18624. }
  18625. }
  18626. // Particles
  18627. if (parsedData.particleSystems) {
  18628. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18629. var parsedParticleSystem = parsedData.particleSystems[index];
  18630. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  18631. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  18632. }
  18633. }
  18634. }
  18635. return true;
  18636. },
  18637. load: function (scene, data, rootUrl) {
  18638. var parsedData = JSON.parse(data);
  18639. // Scene
  18640. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  18641. scene.autoClear = parsedData.autoClear;
  18642. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  18643. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  18644. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  18645. // Fog
  18646. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  18647. scene.fogMode = parsedData.fogMode;
  18648. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  18649. scene.fogStart = parsedData.fogStart;
  18650. scene.fogEnd = parsedData.fogEnd;
  18651. scene.fogDensity = parsedData.fogDensity;
  18652. }
  18653. for (var index = 0; index < parsedData.lights.length; index++) {
  18654. var parsedLight = parsedData.lights[index];
  18655. parseLight(parsedLight, scene);
  18656. }
  18657. // Materials
  18658. if (parsedData.materials) {
  18659. for (index = 0; index < parsedData.materials.length; index++) {
  18660. var parsedMaterial = parsedData.materials[index];
  18661. parseMaterial(parsedMaterial, scene, rootUrl);
  18662. }
  18663. }
  18664. if (parsedData.multiMaterials) {
  18665. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  18666. var parsedMultiMaterial = parsedData.multiMaterials[index];
  18667. parseMultiMaterial(parsedMultiMaterial, scene);
  18668. }
  18669. }
  18670. // Skeletons
  18671. if (parsedData.skeletons) {
  18672. for (index = 0; index < parsedData.skeletons.length; index++) {
  18673. var parsedSkeleton = parsedData.skeletons[index];
  18674. parseSkeleton(parsedSkeleton, scene);
  18675. }
  18676. }
  18677. // Geometries
  18678. var geometries = parsedData.geometries;
  18679. if (geometries) {
  18680. // Boxes
  18681. var boxes = geometries.boxes;
  18682. if (boxes) {
  18683. for (index = 0; index < boxes.length; index++) {
  18684. var parsedBox = boxes[index];
  18685. parseBox(parsedBox, scene);
  18686. }
  18687. }
  18688. // Spheres
  18689. var spheres = geometries.spheres;
  18690. if (spheres) {
  18691. for (index = 0; index < spheres.length; index++) {
  18692. var parsedSphere = spheres[index];
  18693. parseSphere(parsedSphere, scene);
  18694. }
  18695. }
  18696. // Cylinders
  18697. var cylinders = geometries.cylinders;
  18698. if (cylinders) {
  18699. for (index = 0; index < cylinders.length; index++) {
  18700. var parsedCylinder = cylinders[index];
  18701. parseCylinder(parsedCylinder, scene);
  18702. }
  18703. }
  18704. // Toruses
  18705. var toruses = geometries.toruses;
  18706. if (toruses) {
  18707. for (index = 0; index < toruses.length; index++) {
  18708. var parsedTorus = toruses[index];
  18709. parseTorus(parsedTorus, scene);
  18710. }
  18711. }
  18712. // Grounds
  18713. var grounds = geometries.grounds;
  18714. if (grounds) {
  18715. for (index = 0; index < grounds.length; index++) {
  18716. var parsedGround = grounds[index];
  18717. parseGround(parsedGround, scene);
  18718. }
  18719. }
  18720. // Planes
  18721. var planes = geometries.planes;
  18722. if (planes) {
  18723. for (index = 0; index < planes.length; index++) {
  18724. var parsedPlane = planes[index];
  18725. parsePlane(parsedPlane, scene);
  18726. }
  18727. }
  18728. // TorusKnots
  18729. var torusKnots = geometries.torusKnots;
  18730. if (torusKnots) {
  18731. for (index = 0; index < torusKnots.length; index++) {
  18732. var parsedTorusKnot = torusKnots[index];
  18733. parseTorusKnot(parsedTorusKnot, scene);
  18734. }
  18735. }
  18736. // VertexData
  18737. var vertexData = geometries.vertexData;
  18738. if (vertexData) {
  18739. for (index = 0; index < vertexData.length; index++) {
  18740. var parsedVertexData = vertexData[index];
  18741. parseVertexData(parsedVertexData, scene, rootUrl);
  18742. }
  18743. }
  18744. }
  18745. for (index = 0; index < parsedData.meshes.length; index++) {
  18746. var parsedMesh = parsedData.meshes[index];
  18747. parseMesh(parsedMesh, scene, rootUrl);
  18748. }
  18749. for (index = 0; index < parsedData.cameras.length; index++) {
  18750. var parsedCamera = parsedData.cameras[index];
  18751. parseCamera(parsedCamera, scene);
  18752. }
  18753. if (parsedData.activeCameraID) {
  18754. scene.setActiveCameraByID(parsedData.activeCameraID);
  18755. }
  18756. for (index = 0; index < scene.cameras.length; index++) {
  18757. var camera = scene.cameras[index];
  18758. if (camera._waitingParentId) {
  18759. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  18760. camera._waitingParentId = undefined;
  18761. }
  18762. }
  18763. for (index = 0; index < scene.lights.length; index++) {
  18764. var light = scene.lights[index];
  18765. if (light._waitingParentId) {
  18766. light.parent = scene.getLastEntryByID(light._waitingParentId);
  18767. light._waitingParentId = undefined;
  18768. }
  18769. }
  18770. // Sounds
  18771. if (parsedData.sounds) {
  18772. for (index = 0; index < parsedData.sounds.length; index++) {
  18773. var parsedSound = parsedData.sounds[index];
  18774. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  18775. parseSound(parsedSound, scene, rootUrl);
  18776. }
  18777. else {
  18778. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  18779. }
  18780. }
  18781. }
  18782. for (index = 0; index < scene.meshes.length; index++) {
  18783. var mesh = scene.meshes[index];
  18784. if (mesh._waitingParentId) {
  18785. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  18786. mesh._waitingParentId = undefined;
  18787. }
  18788. if (mesh._waitingActions) {
  18789. parseActions(mesh._waitingActions, mesh, scene);
  18790. mesh._waitingActions = undefined;
  18791. }
  18792. }
  18793. // Particles Systems
  18794. if (parsedData.particleSystems) {
  18795. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18796. var parsedParticleSystem = parsedData.particleSystems[index];
  18797. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  18798. }
  18799. }
  18800. // Lens flares
  18801. if (parsedData.lensFlareSystems) {
  18802. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  18803. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  18804. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  18805. }
  18806. }
  18807. // Shadows
  18808. if (parsedData.shadowGenerators) {
  18809. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  18810. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  18811. parseShadowGenerator(parsedShadowGenerator, scene);
  18812. }
  18813. }
  18814. // Actions (scene)
  18815. if (parsedData.actions) {
  18816. parseActions(parsedData.actions, null, scene);
  18817. }
  18818. // Finish
  18819. return true;
  18820. }
  18821. });
  18822. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  18823. })(BABYLON || (BABYLON = {}));
  18824. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  18825. var BABYLON;
  18826. (function (BABYLON) {
  18827. var SpriteManager = (function () {
  18828. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  18829. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18830. this.name = name;
  18831. this.cellSize = cellSize;
  18832. this.sprites = new Array();
  18833. this.renderingGroupId = 0;
  18834. this.fogEnabled = true;
  18835. this._vertexDeclaration = [4, 4, 4, 4];
  18836. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  18837. this._capacity = capacity;
  18838. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  18839. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18840. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18841. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  18842. this._scene = scene;
  18843. this._scene.spriteManagers.push(this);
  18844. // VBO
  18845. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  18846. var indices = [];
  18847. var index = 0;
  18848. for (var count = 0; count < capacity; count++) {
  18849. indices.push(index);
  18850. indices.push(index + 1);
  18851. indices.push(index + 2);
  18852. indices.push(index);
  18853. indices.push(index + 2);
  18854. indices.push(index + 3);
  18855. index += 4;
  18856. }
  18857. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18858. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  18859. // Effects
  18860. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  18861. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  18862. }
  18863. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  18864. var arrayOffset = index * 16;
  18865. if (offsetX === 0)
  18866. offsetX = this._epsilon;
  18867. else if (offsetX === 1)
  18868. offsetX = 1 - this._epsilon;
  18869. if (offsetY === 0)
  18870. offsetY = this._epsilon;
  18871. else if (offsetY === 1)
  18872. offsetY = 1 - this._epsilon;
  18873. this._vertices[arrayOffset] = sprite.position.x;
  18874. this._vertices[arrayOffset + 1] = sprite.position.y;
  18875. this._vertices[arrayOffset + 2] = sprite.position.z;
  18876. this._vertices[arrayOffset + 3] = sprite.angle;
  18877. this._vertices[arrayOffset + 4] = sprite.width;
  18878. this._vertices[arrayOffset + 5] = sprite.height;
  18879. this._vertices[arrayOffset + 6] = offsetX;
  18880. this._vertices[arrayOffset + 7] = offsetY;
  18881. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  18882. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  18883. var offset = (sprite.cellIndex / rowSize) >> 0;
  18884. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  18885. this._vertices[arrayOffset + 11] = offset;
  18886. // Color
  18887. this._vertices[arrayOffset + 12] = sprite.color.r;
  18888. this._vertices[arrayOffset + 13] = sprite.color.g;
  18889. this._vertices[arrayOffset + 14] = sprite.color.b;
  18890. this._vertices[arrayOffset + 15] = sprite.color.a;
  18891. };
  18892. SpriteManager.prototype.render = function () {
  18893. // Check
  18894. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  18895. return;
  18896. var engine = this._scene.getEngine();
  18897. var baseSize = this._spriteTexture.getBaseSize();
  18898. // Sprites
  18899. var deltaTime = engine.getDeltaTime();
  18900. var max = Math.min(this._capacity, this.sprites.length);
  18901. var rowSize = baseSize.width / this.cellSize;
  18902. var offset = 0;
  18903. for (var index = 0; index < max; index++) {
  18904. var sprite = this.sprites[index];
  18905. if (!sprite) {
  18906. continue;
  18907. }
  18908. sprite._animate(deltaTime);
  18909. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  18910. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  18911. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  18912. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  18913. }
  18914. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  18915. // Render
  18916. var effect = this._effectBase;
  18917. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18918. effect = this._effectFog;
  18919. }
  18920. engine.enableEffect(effect);
  18921. var viewMatrix = this._scene.getViewMatrix();
  18922. effect.setTexture("diffuseSampler", this._spriteTexture);
  18923. effect.setMatrix("view", viewMatrix);
  18924. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  18925. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  18926. // Fog
  18927. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18928. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  18929. effect.setColor3("vFogColor", this._scene.fogColor);
  18930. }
  18931. // VBOs
  18932. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  18933. // Draw order
  18934. engine.setDepthFunctionToLessOrEqual();
  18935. effect.setBool("alphaTest", true);
  18936. engine.setColorWrite(false);
  18937. engine.draw(true, 0, max * 6);
  18938. engine.setColorWrite(true);
  18939. effect.setBool("alphaTest", false);
  18940. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  18941. engine.draw(true, 0, max * 6);
  18942. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18943. };
  18944. SpriteManager.prototype.dispose = function () {
  18945. if (this._vertexBuffer) {
  18946. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  18947. this._vertexBuffer = null;
  18948. }
  18949. if (this._indexBuffer) {
  18950. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  18951. this._indexBuffer = null;
  18952. }
  18953. if (this._spriteTexture) {
  18954. this._spriteTexture.dispose();
  18955. this._spriteTexture = null;
  18956. }
  18957. // Remove from scene
  18958. var index = this._scene.spriteManagers.indexOf(this);
  18959. this._scene.spriteManagers.splice(index, 1);
  18960. // Callback
  18961. if (this.onDispose) {
  18962. this.onDispose();
  18963. }
  18964. };
  18965. return SpriteManager;
  18966. })();
  18967. BABYLON.SpriteManager = SpriteManager;
  18968. })(BABYLON || (BABYLON = {}));
  18969. //# sourceMappingURL=babylon.spriteManager.js.map
  18970. var BABYLON;
  18971. (function (BABYLON) {
  18972. var Sprite = (function () {
  18973. function Sprite(name, manager) {
  18974. this.name = name;
  18975. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  18976. this.width = 1.0;
  18977. this.height = 1.0;
  18978. this.angle = 0;
  18979. this.cellIndex = 0;
  18980. this.invertU = 0;
  18981. this.invertV = 0;
  18982. this.animations = new Array();
  18983. this._animationStarted = false;
  18984. this._loopAnimation = false;
  18985. this._fromIndex = 0;
  18986. this._toIndex = 0;
  18987. this._delay = 0;
  18988. this._direction = 1;
  18989. this._frameCount = 0;
  18990. this._time = 0;
  18991. this._manager = manager;
  18992. this._manager.sprites.push(this);
  18993. this.position = BABYLON.Vector3.Zero();
  18994. }
  18995. Object.defineProperty(Sprite.prototype, "size", {
  18996. get: function () {
  18997. return this.width;
  18998. },
  18999. set: function (value) {
  19000. this.width = value;
  19001. this.height = value;
  19002. },
  19003. enumerable: true,
  19004. configurable: true
  19005. });
  19006. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  19007. this._fromIndex = from;
  19008. this._toIndex = to;
  19009. this._loopAnimation = loop;
  19010. this._delay = delay;
  19011. this._animationStarted = true;
  19012. this._direction = from < to ? 1 : -1;
  19013. this.cellIndex = from;
  19014. this._time = 0;
  19015. };
  19016. Sprite.prototype.stopAnimation = function () {
  19017. this._animationStarted = false;
  19018. };
  19019. Sprite.prototype._animate = function (deltaTime) {
  19020. if (!this._animationStarted)
  19021. return;
  19022. this._time += deltaTime;
  19023. if (this._time > this._delay) {
  19024. this._time = this._time % this._delay;
  19025. this.cellIndex += this._direction;
  19026. if (this.cellIndex == this._toIndex) {
  19027. if (this._loopAnimation) {
  19028. this.cellIndex = this._fromIndex;
  19029. }
  19030. else {
  19031. this._animationStarted = false;
  19032. if (this.disposeWhenFinishedAnimating) {
  19033. this.dispose();
  19034. }
  19035. }
  19036. }
  19037. }
  19038. };
  19039. Sprite.prototype.dispose = function () {
  19040. for (var i = 0; i < this._manager.sprites.length; i++) {
  19041. if (this._manager.sprites[i] == this) {
  19042. this._manager.sprites.splice(i, 1);
  19043. }
  19044. }
  19045. };
  19046. return Sprite;
  19047. })();
  19048. BABYLON.Sprite = Sprite;
  19049. })(BABYLON || (BABYLON = {}));
  19050. //# sourceMappingURL=babylon.sprite.js.map
  19051. var BABYLON;
  19052. (function (BABYLON) {
  19053. var Layer = (function () {
  19054. function Layer(name, imgUrl, scene, isBackground, color) {
  19055. this.name = name;
  19056. this._vertexDeclaration = [2];
  19057. this._vertexStrideSize = 2 * 4;
  19058. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  19059. this.isBackground = isBackground === undefined ? true : isBackground;
  19060. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  19061. this._scene = scene;
  19062. this._scene.layers.push(this);
  19063. // VBO
  19064. var vertices = [];
  19065. vertices.push(1, 1);
  19066. vertices.push(-1, 1);
  19067. vertices.push(-1, -1);
  19068. vertices.push(1, -1);
  19069. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  19070. // Indices
  19071. var indices = [];
  19072. indices.push(0);
  19073. indices.push(1);
  19074. indices.push(2);
  19075. indices.push(0);
  19076. indices.push(2);
  19077. indices.push(3);
  19078. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  19079. // Effects
  19080. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  19081. }
  19082. Layer.prototype.render = function () {
  19083. // Check
  19084. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  19085. return;
  19086. var engine = this._scene.getEngine();
  19087. // Render
  19088. engine.enableEffect(this._effect);
  19089. engine.setState(false);
  19090. // Texture
  19091. this._effect.setTexture("textureSampler", this.texture);
  19092. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  19093. // Color
  19094. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  19095. // VBOs
  19096. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  19097. // Draw order
  19098. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19099. engine.draw(true, 0, 6);
  19100. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19101. };
  19102. Layer.prototype.dispose = function () {
  19103. if (this._vertexBuffer) {
  19104. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  19105. this._vertexBuffer = null;
  19106. }
  19107. if (this._indexBuffer) {
  19108. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  19109. this._indexBuffer = null;
  19110. }
  19111. if (this.texture) {
  19112. this.texture.dispose();
  19113. this.texture = null;
  19114. }
  19115. // Remove from scene
  19116. var index = this._scene.layers.indexOf(this);
  19117. this._scene.layers.splice(index, 1);
  19118. // Callback
  19119. if (this.onDispose) {
  19120. this.onDispose();
  19121. }
  19122. };
  19123. return Layer;
  19124. })();
  19125. BABYLON.Layer = Layer;
  19126. })(BABYLON || (BABYLON = {}));
  19127. //# sourceMappingURL=babylon.layer.js.map
  19128. var BABYLON;
  19129. (function (BABYLON) {
  19130. var Particle = (function () {
  19131. function Particle() {
  19132. this.position = BABYLON.Vector3.Zero();
  19133. this.direction = BABYLON.Vector3.Zero();
  19134. this.color = new BABYLON.Color4(0, 0, 0, 0);
  19135. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  19136. this.lifeTime = 1.0;
  19137. this.age = 0;
  19138. this.size = 0;
  19139. this.angle = 0;
  19140. this.angularSpeed = 0;
  19141. }
  19142. Particle.prototype.copyTo = function (other) {
  19143. other.position.copyFrom(this.position);
  19144. other.direction.copyFrom(this.direction);
  19145. other.color.copyFrom(this.color);
  19146. other.colorStep.copyFrom(this.colorStep);
  19147. other.lifeTime = this.lifeTime;
  19148. other.age = this.age;
  19149. other.size = this.size;
  19150. other.angle = this.angle;
  19151. other.angularSpeed = this.angularSpeed;
  19152. };
  19153. return Particle;
  19154. })();
  19155. BABYLON.Particle = Particle;
  19156. })(BABYLON || (BABYLON = {}));
  19157. //# sourceMappingURL=babylon.particle.js.map
  19158. var BABYLON;
  19159. (function (BABYLON) {
  19160. var randomNumber = function (min, max) {
  19161. if (min === max) {
  19162. return (min);
  19163. }
  19164. var random = Math.random();
  19165. return ((random * (max - min)) + min);
  19166. };
  19167. var ParticleSystem = (function () {
  19168. function ParticleSystem(name, capacity, scene, customEffect) {
  19169. var _this = this;
  19170. this.name = name;
  19171. this.renderingGroupId = 0;
  19172. this.emitter = null;
  19173. this.emitRate = 10;
  19174. this.manualEmitCount = -1;
  19175. this.updateSpeed = 0.01;
  19176. this.targetStopDuration = 0;
  19177. this.disposeOnStop = false;
  19178. this.minEmitPower = 1;
  19179. this.maxEmitPower = 1;
  19180. this.minLifeTime = 1;
  19181. this.maxLifeTime = 1;
  19182. this.minSize = 1;
  19183. this.maxSize = 1;
  19184. this.minAngularSpeed = 0;
  19185. this.maxAngularSpeed = 0;
  19186. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  19187. this.forceDepthWrite = false;
  19188. this.gravity = BABYLON.Vector3.Zero();
  19189. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  19190. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  19191. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  19192. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  19193. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19194. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19195. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  19196. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19197. this.particles = new Array();
  19198. this._vertexDeclaration = [3, 4, 4];
  19199. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  19200. this._stockParticles = new Array();
  19201. this._newPartsExcess = 0;
  19202. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  19203. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  19204. this._scaledDirection = BABYLON.Vector3.Zero();
  19205. this._scaledGravity = BABYLON.Vector3.Zero();
  19206. this._currentRenderId = -1;
  19207. this._started = false;
  19208. this._stopped = false;
  19209. this._actualFrame = 0;
  19210. this.id = name;
  19211. this._capacity = capacity;
  19212. this._scene = scene;
  19213. this._customEffect = customEffect;
  19214. scene.particleSystems.push(this);
  19215. // VBO
  19216. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  19217. var indices = [];
  19218. var index = 0;
  19219. for (var count = 0; count < capacity; count++) {
  19220. indices.push(index);
  19221. indices.push(index + 1);
  19222. indices.push(index + 2);
  19223. indices.push(index);
  19224. indices.push(index + 2);
  19225. indices.push(index + 3);
  19226. index += 4;
  19227. }
  19228. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  19229. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  19230. // Default behaviors
  19231. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  19232. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  19233. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  19234. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  19235. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  19236. };
  19237. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  19238. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  19239. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  19240. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  19241. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  19242. };
  19243. this.updateFunction = function (particles) {
  19244. for (var index = 0; index < particles.length; index++) {
  19245. var particle = particles[index];
  19246. particle.age += _this._scaledUpdateSpeed;
  19247. if (particle.age >= particle.lifeTime) {
  19248. _this.recycleParticle(particle);
  19249. index--;
  19250. continue;
  19251. }
  19252. else {
  19253. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  19254. particle.color.addInPlace(_this._scaledColorStep);
  19255. if (particle.color.a < 0)
  19256. particle.color.a = 0;
  19257. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  19258. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  19259. particle.position.addInPlace(_this._scaledDirection);
  19260. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  19261. particle.direction.addInPlace(_this._scaledGravity);
  19262. }
  19263. }
  19264. };
  19265. }
  19266. ParticleSystem.prototype.recycleParticle = function (particle) {
  19267. var lastParticle = this.particles.pop();
  19268. if (lastParticle !== particle) {
  19269. lastParticle.copyTo(particle);
  19270. this._stockParticles.push(lastParticle);
  19271. }
  19272. };
  19273. ParticleSystem.prototype.getCapacity = function () {
  19274. return this._capacity;
  19275. };
  19276. ParticleSystem.prototype.isAlive = function () {
  19277. return this._alive;
  19278. };
  19279. ParticleSystem.prototype.isStarted = function () {
  19280. return this._started;
  19281. };
  19282. ParticleSystem.prototype.start = function () {
  19283. this._started = true;
  19284. this._stopped = false;
  19285. this._actualFrame = 0;
  19286. };
  19287. ParticleSystem.prototype.stop = function () {
  19288. this._stopped = true;
  19289. };
  19290. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  19291. var offset = index * 11;
  19292. this._vertices[offset] = particle.position.x;
  19293. this._vertices[offset + 1] = particle.position.y;
  19294. this._vertices[offset + 2] = particle.position.z;
  19295. this._vertices[offset + 3] = particle.color.r;
  19296. this._vertices[offset + 4] = particle.color.g;
  19297. this._vertices[offset + 5] = particle.color.b;
  19298. this._vertices[offset + 6] = particle.color.a;
  19299. this._vertices[offset + 7] = particle.angle;
  19300. this._vertices[offset + 8] = particle.size;
  19301. this._vertices[offset + 9] = offsetX;
  19302. this._vertices[offset + 10] = offsetY;
  19303. };
  19304. ParticleSystem.prototype._update = function (newParticles) {
  19305. // Update current
  19306. this._alive = this.particles.length > 0;
  19307. this.updateFunction(this.particles);
  19308. // Add new ones
  19309. var worldMatrix;
  19310. if (this.emitter.position) {
  19311. worldMatrix = this.emitter.getWorldMatrix();
  19312. }
  19313. else {
  19314. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  19315. }
  19316. for (var index = 0; index < newParticles; index++) {
  19317. if (this.particles.length === this._capacity) {
  19318. break;
  19319. }
  19320. if (this._stockParticles.length !== 0) {
  19321. var particle = this._stockParticles.pop();
  19322. particle.age = 0;
  19323. }
  19324. else {
  19325. particle = new BABYLON.Particle();
  19326. }
  19327. this.particles.push(particle);
  19328. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  19329. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  19330. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  19331. particle.size = randomNumber(this.minSize, this.maxSize);
  19332. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  19333. this.startPositionFunction(worldMatrix, particle.position);
  19334. var step = randomNumber(0, 1.0);
  19335. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  19336. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  19337. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  19338. }
  19339. };
  19340. ParticleSystem.prototype._getEffect = function () {
  19341. if (this._customEffect) {
  19342. return this._customEffect;
  19343. }
  19344. ;
  19345. var defines = [];
  19346. if (this._scene.clipPlane) {
  19347. defines.push("#define CLIPPLANE");
  19348. }
  19349. // Effect
  19350. var join = defines.join("\n");
  19351. if (this._cachedDefines !== join) {
  19352. this._cachedDefines = join;
  19353. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  19354. }
  19355. return this._effect;
  19356. };
  19357. ParticleSystem.prototype.animate = function () {
  19358. if (!this._started)
  19359. return;
  19360. var effect = this._getEffect();
  19361. // Check
  19362. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  19363. return;
  19364. if (this._currentRenderId === this._scene.getRenderId()) {
  19365. return;
  19366. }
  19367. this._currentRenderId = this._scene.getRenderId();
  19368. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  19369. // determine the number of particles we need to create
  19370. var emitCout;
  19371. if (this.manualEmitCount > -1) {
  19372. emitCout = this.manualEmitCount;
  19373. this.manualEmitCount = 0;
  19374. }
  19375. else {
  19376. emitCout = this.emitRate;
  19377. }
  19378. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  19379. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  19380. if (this._newPartsExcess > 1.0) {
  19381. newParticles += this._newPartsExcess >> 0;
  19382. this._newPartsExcess -= this._newPartsExcess >> 0;
  19383. }
  19384. this._alive = false;
  19385. if (!this._stopped) {
  19386. this._actualFrame += this._scaledUpdateSpeed;
  19387. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  19388. this.stop();
  19389. }
  19390. else {
  19391. newParticles = 0;
  19392. }
  19393. this._update(newParticles);
  19394. // Stopped?
  19395. if (this._stopped) {
  19396. if (!this._alive) {
  19397. this._started = false;
  19398. if (this.disposeOnStop) {
  19399. this._scene._toBeDisposed.push(this);
  19400. }
  19401. }
  19402. }
  19403. // Update VBO
  19404. var offset = 0;
  19405. for (var index = 0; index < this.particles.length; index++) {
  19406. var particle = this.particles[index];
  19407. this._appendParticleVertex(offset++, particle, 0, 0);
  19408. this._appendParticleVertex(offset++, particle, 1, 0);
  19409. this._appendParticleVertex(offset++, particle, 1, 1);
  19410. this._appendParticleVertex(offset++, particle, 0, 1);
  19411. }
  19412. var engine = this._scene.getEngine();
  19413. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  19414. };
  19415. ParticleSystem.prototype.render = function () {
  19416. var effect = this._getEffect();
  19417. // Check
  19418. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  19419. return 0;
  19420. var engine = this._scene.getEngine();
  19421. // Render
  19422. engine.enableEffect(effect);
  19423. engine.setState(false);
  19424. var viewMatrix = this._scene.getViewMatrix();
  19425. effect.setTexture("diffuseSampler", this.particleTexture);
  19426. effect.setMatrix("view", viewMatrix);
  19427. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  19428. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  19429. if (this._scene.clipPlane) {
  19430. var clipPlane = this._scene.clipPlane;
  19431. var invView = viewMatrix.clone();
  19432. invView.invert();
  19433. effect.setMatrix("invView", invView);
  19434. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19435. }
  19436. // VBOs
  19437. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  19438. // Draw order
  19439. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  19440. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  19441. }
  19442. else {
  19443. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19444. }
  19445. if (this.forceDepthWrite) {
  19446. engine.setDepthWrite(true);
  19447. }
  19448. engine.draw(true, 0, this.particles.length * 6);
  19449. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19450. return this.particles.length;
  19451. };
  19452. ParticleSystem.prototype.dispose = function () {
  19453. if (this._vertexBuffer) {
  19454. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  19455. this._vertexBuffer = null;
  19456. }
  19457. if (this._indexBuffer) {
  19458. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  19459. this._indexBuffer = null;
  19460. }
  19461. if (this.particleTexture) {
  19462. this.particleTexture.dispose();
  19463. this.particleTexture = null;
  19464. }
  19465. // Remove from scene
  19466. var index = this._scene.particleSystems.indexOf(this);
  19467. this._scene.particleSystems.splice(index, 1);
  19468. // Callback
  19469. if (this.onDispose) {
  19470. this.onDispose();
  19471. }
  19472. };
  19473. // Clone
  19474. ParticleSystem.prototype.clone = function (name, newEmitter) {
  19475. var result = new ParticleSystem(name, this._capacity, this._scene);
  19476. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  19477. if (newEmitter === undefined) {
  19478. newEmitter = this.emitter;
  19479. }
  19480. result.emitter = newEmitter;
  19481. if (this.particleTexture) {
  19482. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  19483. }
  19484. result.start();
  19485. return result;
  19486. };
  19487. // Statics
  19488. ParticleSystem.BLENDMODE_ONEONE = 0;
  19489. ParticleSystem.BLENDMODE_STANDARD = 1;
  19490. return ParticleSystem;
  19491. })();
  19492. BABYLON.ParticleSystem = ParticleSystem;
  19493. })(BABYLON || (BABYLON = {}));
  19494. //# sourceMappingURL=babylon.particleSystem.js.map
  19495. var BABYLON;
  19496. (function (BABYLON) {
  19497. var Animation = (function () {
  19498. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  19499. this.name = name;
  19500. this.targetProperty = targetProperty;
  19501. this.framePerSecond = framePerSecond;
  19502. this.dataType = dataType;
  19503. this.loopMode = loopMode;
  19504. this._offsetsCache = {};
  19505. this._highLimitsCache = {};
  19506. this._stopped = false;
  19507. this.targetPropertyPath = targetProperty.split(".");
  19508. this.dataType = dataType;
  19509. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  19510. }
  19511. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  19512. var dataType = undefined;
  19513. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  19514. dataType = Animation.ANIMATIONTYPE_FLOAT;
  19515. }
  19516. else if (from instanceof BABYLON.Quaternion) {
  19517. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  19518. }
  19519. else if (from instanceof BABYLON.Vector3) {
  19520. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  19521. }
  19522. else if (from instanceof BABYLON.Vector2) {
  19523. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  19524. }
  19525. else if (from instanceof BABYLON.Color3) {
  19526. dataType = Animation.ANIMATIONTYPE_COLOR3;
  19527. }
  19528. if (dataType == undefined) {
  19529. return null;
  19530. }
  19531. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  19532. var keys = [];
  19533. keys.push({ frame: 0, value: from });
  19534. keys.push({ frame: totalFrame, value: to });
  19535. animation.setKeys(keys);
  19536. mesh.animations.push(animation);
  19537. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  19538. };
  19539. // Methods
  19540. Animation.prototype.isStopped = function () {
  19541. return this._stopped;
  19542. };
  19543. Animation.prototype.getKeys = function () {
  19544. return this._keys;
  19545. };
  19546. Animation.prototype.getEasingFunction = function () {
  19547. return this._easingFunction;
  19548. };
  19549. Animation.prototype.setEasingFunction = function (easingFunction) {
  19550. this._easingFunction = easingFunction;
  19551. };
  19552. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  19553. return startValue + (endValue - startValue) * gradient;
  19554. };
  19555. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  19556. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  19557. };
  19558. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  19559. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  19560. };
  19561. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  19562. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  19563. };
  19564. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  19565. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  19566. };
  19567. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  19568. var startScale = new BABYLON.Vector3(0, 0, 0);
  19569. var startRotation = new BABYLON.Quaternion();
  19570. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  19571. startValue.decompose(startScale, startRotation, startTranslation);
  19572. var endScale = new BABYLON.Vector3(0, 0, 0);
  19573. var endRotation = new BABYLON.Quaternion();
  19574. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  19575. endValue.decompose(endScale, endRotation, endTranslation);
  19576. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  19577. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  19578. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  19579. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  19580. return result;
  19581. };
  19582. Animation.prototype.clone = function () {
  19583. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  19584. clone.setKeys(this._keys);
  19585. return clone;
  19586. };
  19587. Animation.prototype.setKeys = function (values) {
  19588. this._keys = values.slice(0);
  19589. this._offsetsCache = {};
  19590. this._highLimitsCache = {};
  19591. };
  19592. Animation.prototype._getKeyValue = function (value) {
  19593. if (typeof value === "function") {
  19594. return value();
  19595. }
  19596. return value;
  19597. };
  19598. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  19599. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  19600. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  19601. }
  19602. this.currentFrame = currentFrame;
  19603. // Try to get a hash to find the right key
  19604. 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));
  19605. if (this._keys[startKey].frame >= currentFrame) {
  19606. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  19607. startKey--;
  19608. }
  19609. }
  19610. for (var key = startKey; key < this._keys.length; key++) {
  19611. if (this._keys[key + 1].frame >= currentFrame) {
  19612. var startValue = this._getKeyValue(this._keys[key].value);
  19613. var endValue = this._getKeyValue(this._keys[key + 1].value);
  19614. // gradient : percent of currentFrame between the frame inf and the frame sup
  19615. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  19616. // check for easingFunction and correction of gradient
  19617. if (this._easingFunction != null) {
  19618. gradient = this._easingFunction.ease(gradient);
  19619. }
  19620. switch (this.dataType) {
  19621. case Animation.ANIMATIONTYPE_FLOAT:
  19622. switch (loopMode) {
  19623. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19624. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19625. return this.floatInterpolateFunction(startValue, endValue, gradient);
  19626. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19627. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  19628. }
  19629. break;
  19630. case Animation.ANIMATIONTYPE_QUATERNION:
  19631. var quaternion = null;
  19632. switch (loopMode) {
  19633. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19634. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19635. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  19636. break;
  19637. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19638. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19639. break;
  19640. }
  19641. return quaternion;
  19642. case Animation.ANIMATIONTYPE_VECTOR3:
  19643. switch (loopMode) {
  19644. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19645. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19646. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  19647. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19648. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19649. }
  19650. case Animation.ANIMATIONTYPE_VECTOR2:
  19651. switch (loopMode) {
  19652. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19653. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19654. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  19655. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19656. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19657. }
  19658. case Animation.ANIMATIONTYPE_COLOR3:
  19659. switch (loopMode) {
  19660. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19661. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19662. return this.color3InterpolateFunction(startValue, endValue, gradient);
  19663. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19664. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19665. }
  19666. case Animation.ANIMATIONTYPE_MATRIX:
  19667. switch (loopMode) {
  19668. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19669. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19670. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19671. return startValue;
  19672. }
  19673. default:
  19674. break;
  19675. }
  19676. break;
  19677. }
  19678. }
  19679. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  19680. };
  19681. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  19682. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  19683. this._stopped = true;
  19684. return false;
  19685. }
  19686. var returnValue = true;
  19687. // Adding a start key at frame 0 if missing
  19688. if (this._keys[0].frame !== 0) {
  19689. var newKey = { frame: 0, value: this._keys[0].value };
  19690. this._keys.splice(0, 0, newKey);
  19691. }
  19692. // Check limits
  19693. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  19694. from = this._keys[0].frame;
  19695. }
  19696. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  19697. to = this._keys[this._keys.length - 1].frame;
  19698. }
  19699. // Compute ratio
  19700. var range = to - from;
  19701. var offsetValue;
  19702. // ratio represents the frame delta between from and to
  19703. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  19704. var highLimitValue = 0;
  19705. if (ratio > range && !loop) {
  19706. returnValue = false;
  19707. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  19708. }
  19709. else {
  19710. // Get max value if required
  19711. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  19712. var keyOffset = to.toString() + from.toString();
  19713. if (!this._offsetsCache[keyOffset]) {
  19714. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  19715. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  19716. switch (this.dataType) {
  19717. case Animation.ANIMATIONTYPE_FLOAT:
  19718. this._offsetsCache[keyOffset] = toValue - fromValue;
  19719. break;
  19720. case Animation.ANIMATIONTYPE_QUATERNION:
  19721. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19722. break;
  19723. case Animation.ANIMATIONTYPE_VECTOR3:
  19724. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19725. case Animation.ANIMATIONTYPE_VECTOR2:
  19726. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19727. case Animation.ANIMATIONTYPE_COLOR3:
  19728. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19729. default:
  19730. break;
  19731. }
  19732. this._highLimitsCache[keyOffset] = toValue;
  19733. }
  19734. highLimitValue = this._highLimitsCache[keyOffset];
  19735. offsetValue = this._offsetsCache[keyOffset];
  19736. }
  19737. }
  19738. if (offsetValue === undefined) {
  19739. switch (this.dataType) {
  19740. case Animation.ANIMATIONTYPE_FLOAT:
  19741. offsetValue = 0;
  19742. break;
  19743. case Animation.ANIMATIONTYPE_QUATERNION:
  19744. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  19745. break;
  19746. case Animation.ANIMATIONTYPE_VECTOR3:
  19747. offsetValue = BABYLON.Vector3.Zero();
  19748. break;
  19749. case Animation.ANIMATIONTYPE_VECTOR2:
  19750. offsetValue = BABYLON.Vector2.Zero();
  19751. break;
  19752. case Animation.ANIMATIONTYPE_COLOR3:
  19753. offsetValue = BABYLON.Color3.Black();
  19754. }
  19755. }
  19756. // Compute value
  19757. var repeatCount = (ratio / range) >> 0;
  19758. var currentFrame = returnValue ? from + ratio % range : to;
  19759. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  19760. // Set value
  19761. if (this.targetPropertyPath.length > 1) {
  19762. var property = this._target[this.targetPropertyPath[0]];
  19763. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  19764. property = property[this.targetPropertyPath[index]];
  19765. }
  19766. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  19767. }
  19768. else {
  19769. this._target[this.targetPropertyPath[0]] = currentValue;
  19770. }
  19771. if (this._target.markAsDirty) {
  19772. this._target.markAsDirty(this.targetProperty);
  19773. }
  19774. if (!returnValue) {
  19775. this._stopped = true;
  19776. }
  19777. return returnValue;
  19778. };
  19779. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  19780. get: function () {
  19781. return Animation._ANIMATIONTYPE_FLOAT;
  19782. },
  19783. enumerable: true,
  19784. configurable: true
  19785. });
  19786. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  19787. get: function () {
  19788. return Animation._ANIMATIONTYPE_VECTOR3;
  19789. },
  19790. enumerable: true,
  19791. configurable: true
  19792. });
  19793. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  19794. get: function () {
  19795. return Animation._ANIMATIONTYPE_VECTOR2;
  19796. },
  19797. enumerable: true,
  19798. configurable: true
  19799. });
  19800. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  19801. get: function () {
  19802. return Animation._ANIMATIONTYPE_QUATERNION;
  19803. },
  19804. enumerable: true,
  19805. configurable: true
  19806. });
  19807. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  19808. get: function () {
  19809. return Animation._ANIMATIONTYPE_MATRIX;
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  19815. get: function () {
  19816. return Animation._ANIMATIONTYPE_COLOR3;
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  19822. get: function () {
  19823. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  19824. },
  19825. enumerable: true,
  19826. configurable: true
  19827. });
  19828. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  19829. get: function () {
  19830. return Animation._ANIMATIONLOOPMODE_CYCLE;
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  19836. get: function () {
  19837. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  19838. },
  19839. enumerable: true,
  19840. configurable: true
  19841. });
  19842. // Statics
  19843. Animation._ANIMATIONTYPE_FLOAT = 0;
  19844. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  19845. Animation._ANIMATIONTYPE_QUATERNION = 2;
  19846. Animation._ANIMATIONTYPE_MATRIX = 3;
  19847. Animation._ANIMATIONTYPE_COLOR3 = 4;
  19848. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  19849. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  19850. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  19851. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  19852. return Animation;
  19853. })();
  19854. BABYLON.Animation = Animation;
  19855. })(BABYLON || (BABYLON = {}));
  19856. //# sourceMappingURL=babylon.animation.js.map
  19857. var BABYLON;
  19858. (function (BABYLON) {
  19859. var Animatable = (function () {
  19860. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  19861. if (fromFrame === void 0) { fromFrame = 0; }
  19862. if (toFrame === void 0) { toFrame = 100; }
  19863. if (loopAnimation === void 0) { loopAnimation = false; }
  19864. if (speedRatio === void 0) { speedRatio = 1.0; }
  19865. this.target = target;
  19866. this.fromFrame = fromFrame;
  19867. this.toFrame = toFrame;
  19868. this.loopAnimation = loopAnimation;
  19869. this.speedRatio = speedRatio;
  19870. this.onAnimationEnd = onAnimationEnd;
  19871. this._animations = new Array();
  19872. this._paused = false;
  19873. this.animationStarted = false;
  19874. if (animations) {
  19875. this.appendAnimations(target, animations);
  19876. }
  19877. this._scene = scene;
  19878. scene._activeAnimatables.push(this);
  19879. }
  19880. // Methods
  19881. Animatable.prototype.appendAnimations = function (target, animations) {
  19882. for (var index = 0; index < animations.length; index++) {
  19883. var animation = animations[index];
  19884. animation._target = target;
  19885. this._animations.push(animation);
  19886. }
  19887. };
  19888. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  19889. var animations = this._animations;
  19890. for (var index = 0; index < animations.length; index++) {
  19891. if (animations[index].targetProperty === property) {
  19892. return animations[index];
  19893. }
  19894. }
  19895. return null;
  19896. };
  19897. Animatable.prototype.pause = function () {
  19898. if (this._paused) {
  19899. return;
  19900. }
  19901. this._paused = true;
  19902. };
  19903. Animatable.prototype.restart = function () {
  19904. this._paused = false;
  19905. };
  19906. Animatable.prototype.stop = function () {
  19907. var index = this._scene._activeAnimatables.indexOf(this);
  19908. if (index > -1) {
  19909. this._scene._activeAnimatables.splice(index, 1);
  19910. }
  19911. if (this.onAnimationEnd) {
  19912. this.onAnimationEnd();
  19913. }
  19914. };
  19915. Animatable.prototype._animate = function (delay) {
  19916. if (this._paused) {
  19917. if (!this._pausedDelay) {
  19918. this._pausedDelay = delay;
  19919. }
  19920. return true;
  19921. }
  19922. if (!this._localDelayOffset) {
  19923. this._localDelayOffset = delay;
  19924. }
  19925. else if (this._pausedDelay) {
  19926. this._localDelayOffset += delay - this._pausedDelay;
  19927. this._pausedDelay = null;
  19928. }
  19929. // Animating
  19930. var running = false;
  19931. var animations = this._animations;
  19932. for (var index = 0; index < animations.length; index++) {
  19933. var animation = animations[index];
  19934. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  19935. running = running || isRunning;
  19936. }
  19937. if (!running) {
  19938. // Remove from active animatables
  19939. index = this._scene._activeAnimatables.indexOf(this);
  19940. this._scene._activeAnimatables.splice(index, 1);
  19941. }
  19942. if (!running && this.onAnimationEnd) {
  19943. this.onAnimationEnd();
  19944. }
  19945. return running;
  19946. };
  19947. return Animatable;
  19948. })();
  19949. BABYLON.Animatable = Animatable;
  19950. })(BABYLON || (BABYLON = {}));
  19951. //# sourceMappingURL=babylon.animatable.js.map
  19952. var __extends = this.__extends || function (d, b) {
  19953. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19954. function __() { this.constructor = d; }
  19955. __.prototype = b.prototype;
  19956. d.prototype = new __();
  19957. };
  19958. var BABYLON;
  19959. (function (BABYLON) {
  19960. var EasingFunction = (function () {
  19961. function EasingFunction() {
  19962. // Properties
  19963. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  19964. }
  19965. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  19966. get: function () {
  19967. return EasingFunction._EASINGMODE_EASEIN;
  19968. },
  19969. enumerable: true,
  19970. configurable: true
  19971. });
  19972. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  19973. get: function () {
  19974. return EasingFunction._EASINGMODE_EASEOUT;
  19975. },
  19976. enumerable: true,
  19977. configurable: true
  19978. });
  19979. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  19980. get: function () {
  19981. return EasingFunction._EASINGMODE_EASEINOUT;
  19982. },
  19983. enumerable: true,
  19984. configurable: true
  19985. });
  19986. EasingFunction.prototype.setEasingMode = function (easingMode) {
  19987. var n = Math.min(Math.max(easingMode, 0), 2);
  19988. this._easingMode = n;
  19989. };
  19990. EasingFunction.prototype.getEasingMode = function () {
  19991. return this._easingMode;
  19992. };
  19993. EasingFunction.prototype.easeInCore = function (gradient) {
  19994. throw new Error('You must implement this method');
  19995. };
  19996. EasingFunction.prototype.ease = function (gradient) {
  19997. switch (this._easingMode) {
  19998. case EasingFunction.EASINGMODE_EASEIN:
  19999. return this.easeInCore(gradient);
  20000. case EasingFunction.EASINGMODE_EASEOUT:
  20001. return (1 - this.easeInCore(1 - gradient));
  20002. }
  20003. if (gradient >= 0.5) {
  20004. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  20005. }
  20006. return (this.easeInCore(gradient * 2) * 0.5);
  20007. };
  20008. //Statics
  20009. EasingFunction._EASINGMODE_EASEIN = 0;
  20010. EasingFunction._EASINGMODE_EASEOUT = 1;
  20011. EasingFunction._EASINGMODE_EASEINOUT = 2;
  20012. return EasingFunction;
  20013. })();
  20014. BABYLON.EasingFunction = EasingFunction;
  20015. var CircleEase = (function (_super) {
  20016. __extends(CircleEase, _super);
  20017. function CircleEase() {
  20018. _super.apply(this, arguments);
  20019. }
  20020. CircleEase.prototype.easeInCore = function (gradient) {
  20021. gradient = Math.max(0, Math.min(1, gradient));
  20022. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  20023. };
  20024. return CircleEase;
  20025. })(EasingFunction);
  20026. BABYLON.CircleEase = CircleEase;
  20027. var BackEase = (function (_super) {
  20028. __extends(BackEase, _super);
  20029. function BackEase(amplitude) {
  20030. if (amplitude === void 0) { amplitude = 1; }
  20031. _super.call(this);
  20032. this.amplitude = amplitude;
  20033. }
  20034. BackEase.prototype.easeInCore = function (gradient) {
  20035. var num = Math.max(0, this.amplitude);
  20036. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  20037. };
  20038. return BackEase;
  20039. })(EasingFunction);
  20040. BABYLON.BackEase = BackEase;
  20041. var BounceEase = (function (_super) {
  20042. __extends(BounceEase, _super);
  20043. function BounceEase(bounces, bounciness) {
  20044. if (bounces === void 0) { bounces = 3; }
  20045. if (bounciness === void 0) { bounciness = 2; }
  20046. _super.call(this);
  20047. this.bounces = bounces;
  20048. this.bounciness = bounciness;
  20049. }
  20050. BounceEase.prototype.easeInCore = function (gradient) {
  20051. var y = Math.max(0.0, this.bounces);
  20052. var bounciness = this.bounciness;
  20053. if (bounciness <= 1.0) {
  20054. bounciness = 1.001;
  20055. }
  20056. var num9 = Math.pow(bounciness, y);
  20057. var num5 = 1.0 - bounciness;
  20058. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  20059. var num15 = gradient * num4;
  20060. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  20061. var num3 = Math.floor(num65);
  20062. var num13 = num3 + 1.0;
  20063. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  20064. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  20065. var num7 = (num8 + num12) * 0.5;
  20066. var num6 = gradient - num7;
  20067. var num2 = num7 - num8;
  20068. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  20069. };
  20070. return BounceEase;
  20071. })(EasingFunction);
  20072. BABYLON.BounceEase = BounceEase;
  20073. var CubicEase = (function (_super) {
  20074. __extends(CubicEase, _super);
  20075. function CubicEase() {
  20076. _super.apply(this, arguments);
  20077. }
  20078. CubicEase.prototype.easeInCore = function (gradient) {
  20079. return (gradient * gradient * gradient);
  20080. };
  20081. return CubicEase;
  20082. })(EasingFunction);
  20083. BABYLON.CubicEase = CubicEase;
  20084. var ElasticEase = (function (_super) {
  20085. __extends(ElasticEase, _super);
  20086. function ElasticEase(oscillations, springiness) {
  20087. if (oscillations === void 0) { oscillations = 3; }
  20088. if (springiness === void 0) { springiness = 3; }
  20089. _super.call(this);
  20090. this.oscillations = oscillations;
  20091. this.springiness = springiness;
  20092. }
  20093. ElasticEase.prototype.easeInCore = function (gradient) {
  20094. var num2;
  20095. var num3 = Math.max(0.0, this.oscillations);
  20096. var num = Math.max(0.0, this.springiness);
  20097. if (num == 0) {
  20098. num2 = gradient;
  20099. }
  20100. else {
  20101. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  20102. }
  20103. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  20104. };
  20105. return ElasticEase;
  20106. })(EasingFunction);
  20107. BABYLON.ElasticEase = ElasticEase;
  20108. var ExponentialEase = (function (_super) {
  20109. __extends(ExponentialEase, _super);
  20110. function ExponentialEase(exponent) {
  20111. if (exponent === void 0) { exponent = 2; }
  20112. _super.call(this);
  20113. this.exponent = exponent;
  20114. }
  20115. ExponentialEase.prototype.easeInCore = function (gradient) {
  20116. if (this.exponent <= 0) {
  20117. return gradient;
  20118. }
  20119. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  20120. };
  20121. return ExponentialEase;
  20122. })(EasingFunction);
  20123. BABYLON.ExponentialEase = ExponentialEase;
  20124. var PowerEase = (function (_super) {
  20125. __extends(PowerEase, _super);
  20126. function PowerEase(power) {
  20127. if (power === void 0) { power = 2; }
  20128. _super.call(this);
  20129. this.power = power;
  20130. }
  20131. PowerEase.prototype.easeInCore = function (gradient) {
  20132. var y = Math.max(0.0, this.power);
  20133. return Math.pow(gradient, y);
  20134. };
  20135. return PowerEase;
  20136. })(EasingFunction);
  20137. BABYLON.PowerEase = PowerEase;
  20138. var QuadraticEase = (function (_super) {
  20139. __extends(QuadraticEase, _super);
  20140. function QuadraticEase() {
  20141. _super.apply(this, arguments);
  20142. }
  20143. QuadraticEase.prototype.easeInCore = function (gradient) {
  20144. return (gradient * gradient);
  20145. };
  20146. return QuadraticEase;
  20147. })(EasingFunction);
  20148. BABYLON.QuadraticEase = QuadraticEase;
  20149. var QuarticEase = (function (_super) {
  20150. __extends(QuarticEase, _super);
  20151. function QuarticEase() {
  20152. _super.apply(this, arguments);
  20153. }
  20154. QuarticEase.prototype.easeInCore = function (gradient) {
  20155. return (gradient * gradient * gradient * gradient);
  20156. };
  20157. return QuarticEase;
  20158. })(EasingFunction);
  20159. BABYLON.QuarticEase = QuarticEase;
  20160. var QuinticEase = (function (_super) {
  20161. __extends(QuinticEase, _super);
  20162. function QuinticEase() {
  20163. _super.apply(this, arguments);
  20164. }
  20165. QuinticEase.prototype.easeInCore = function (gradient) {
  20166. return (gradient * gradient * gradient * gradient * gradient);
  20167. };
  20168. return QuinticEase;
  20169. })(EasingFunction);
  20170. BABYLON.QuinticEase = QuinticEase;
  20171. var SineEase = (function (_super) {
  20172. __extends(SineEase, _super);
  20173. function SineEase() {
  20174. _super.apply(this, arguments);
  20175. }
  20176. SineEase.prototype.easeInCore = function (gradient) {
  20177. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  20178. };
  20179. return SineEase;
  20180. })(EasingFunction);
  20181. BABYLON.SineEase = SineEase;
  20182. var BezierCurveEase = (function (_super) {
  20183. __extends(BezierCurveEase, _super);
  20184. function BezierCurveEase(x1, y1, x2, y2) {
  20185. if (x1 === void 0) { x1 = 0; }
  20186. if (y1 === void 0) { y1 = 0; }
  20187. if (x2 === void 0) { x2 = 1; }
  20188. if (y2 === void 0) { y2 = 1; }
  20189. _super.call(this);
  20190. this.x1 = x1;
  20191. this.y1 = y1;
  20192. this.x2 = x2;
  20193. this.y2 = y2;
  20194. }
  20195. BezierCurveEase.prototype.easeInCore = function (gradient) {
  20196. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  20197. };
  20198. return BezierCurveEase;
  20199. })(EasingFunction);
  20200. BABYLON.BezierCurveEase = BezierCurveEase;
  20201. })(BABYLON || (BABYLON = {}));
  20202. //# sourceMappingURL=babylon.easing.js.map
  20203. var BABYLON;
  20204. (function (BABYLON) {
  20205. var Octree = (function () {
  20206. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  20207. if (maxDepth === void 0) { maxDepth = 2; }
  20208. this.maxDepth = maxDepth;
  20209. this.dynamicContent = new Array();
  20210. this._maxBlockCapacity = maxBlockCapacity || 64;
  20211. this._selectionContent = new BABYLON.SmartArray(1024);
  20212. this._creationFunc = creationFunc;
  20213. }
  20214. // Methods
  20215. Octree.prototype.update = function (worldMin, worldMax, entries) {
  20216. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  20217. };
  20218. Octree.prototype.addMesh = function (entry) {
  20219. for (var index = 0; index < this.blocks.length; index++) {
  20220. var block = this.blocks[index];
  20221. block.addEntry(entry);
  20222. }
  20223. };
  20224. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  20225. this._selectionContent.reset();
  20226. for (var index = 0; index < this.blocks.length; index++) {
  20227. var block = this.blocks[index];
  20228. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  20229. }
  20230. if (allowDuplicate) {
  20231. this._selectionContent.concat(this.dynamicContent);
  20232. }
  20233. else {
  20234. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  20235. }
  20236. return this._selectionContent;
  20237. };
  20238. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  20239. this._selectionContent.reset();
  20240. for (var index = 0; index < this.blocks.length; index++) {
  20241. var block = this.blocks[index];
  20242. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  20243. }
  20244. if (allowDuplicate) {
  20245. this._selectionContent.concat(this.dynamicContent);
  20246. }
  20247. else {
  20248. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  20249. }
  20250. return this._selectionContent;
  20251. };
  20252. Octree.prototype.intersectsRay = function (ray) {
  20253. this._selectionContent.reset();
  20254. for (var index = 0; index < this.blocks.length; index++) {
  20255. var block = this.blocks[index];
  20256. block.intersectsRay(ray, this._selectionContent);
  20257. }
  20258. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  20259. return this._selectionContent;
  20260. };
  20261. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  20262. target.blocks = new Array();
  20263. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  20264. for (var x = 0; x < 2; x++) {
  20265. for (var y = 0; y < 2; y++) {
  20266. for (var z = 0; z < 2; z++) {
  20267. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  20268. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  20269. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  20270. block.addEntries(entries);
  20271. target.blocks.push(block);
  20272. }
  20273. }
  20274. }
  20275. };
  20276. Octree.CreationFuncForMeshes = function (entry, block) {
  20277. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  20278. block.entries.push(entry);
  20279. }
  20280. };
  20281. Octree.CreationFuncForSubMeshes = function (entry, block) {
  20282. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  20283. block.entries.push(entry);
  20284. }
  20285. };
  20286. return Octree;
  20287. })();
  20288. BABYLON.Octree = Octree;
  20289. })(BABYLON || (BABYLON = {}));
  20290. //# sourceMappingURL=babylon.octree.js.map
  20291. var BABYLON;
  20292. (function (BABYLON) {
  20293. var OctreeBlock = (function () {
  20294. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  20295. this.entries = new Array();
  20296. this._boundingVectors = new Array();
  20297. this._capacity = capacity;
  20298. this._depth = depth;
  20299. this._maxDepth = maxDepth;
  20300. this._creationFunc = creationFunc;
  20301. this._minPoint = minPoint;
  20302. this._maxPoint = maxPoint;
  20303. this._boundingVectors.push(minPoint.clone());
  20304. this._boundingVectors.push(maxPoint.clone());
  20305. this._boundingVectors.push(minPoint.clone());
  20306. this._boundingVectors[2].x = maxPoint.x;
  20307. this._boundingVectors.push(minPoint.clone());
  20308. this._boundingVectors[3].y = maxPoint.y;
  20309. this._boundingVectors.push(minPoint.clone());
  20310. this._boundingVectors[4].z = maxPoint.z;
  20311. this._boundingVectors.push(maxPoint.clone());
  20312. this._boundingVectors[5].z = minPoint.z;
  20313. this._boundingVectors.push(maxPoint.clone());
  20314. this._boundingVectors[6].x = minPoint.x;
  20315. this._boundingVectors.push(maxPoint.clone());
  20316. this._boundingVectors[7].y = minPoint.y;
  20317. }
  20318. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  20319. // Property
  20320. get: function () {
  20321. return this._capacity;
  20322. },
  20323. enumerable: true,
  20324. configurable: true
  20325. });
  20326. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  20327. get: function () {
  20328. return this._minPoint;
  20329. },
  20330. enumerable: true,
  20331. configurable: true
  20332. });
  20333. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  20334. get: function () {
  20335. return this._maxPoint;
  20336. },
  20337. enumerable: true,
  20338. configurable: true
  20339. });
  20340. // Methods
  20341. OctreeBlock.prototype.addEntry = function (entry) {
  20342. if (this.blocks) {
  20343. for (var index = 0; index < this.blocks.length; index++) {
  20344. var block = this.blocks[index];
  20345. block.addEntry(entry);
  20346. }
  20347. return;
  20348. }
  20349. this._creationFunc(entry, this);
  20350. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  20351. this.createInnerBlocks();
  20352. }
  20353. };
  20354. OctreeBlock.prototype.addEntries = function (entries) {
  20355. for (var index = 0; index < entries.length; index++) {
  20356. var mesh = entries[index];
  20357. this.addEntry(mesh);
  20358. }
  20359. };
  20360. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  20361. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  20362. if (this.blocks) {
  20363. for (var index = 0; index < this.blocks.length; index++) {
  20364. var block = this.blocks[index];
  20365. block.select(frustumPlanes, selection, allowDuplicate);
  20366. }
  20367. return;
  20368. }
  20369. if (allowDuplicate) {
  20370. selection.concat(this.entries);
  20371. }
  20372. else {
  20373. selection.concatWithNoDuplicate(this.entries);
  20374. }
  20375. }
  20376. };
  20377. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  20378. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  20379. if (this.blocks) {
  20380. for (var index = 0; index < this.blocks.length; index++) {
  20381. var block = this.blocks[index];
  20382. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  20383. }
  20384. return;
  20385. }
  20386. if (allowDuplicate) {
  20387. selection.concat(this.entries);
  20388. }
  20389. else {
  20390. selection.concatWithNoDuplicate(this.entries);
  20391. }
  20392. }
  20393. };
  20394. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  20395. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  20396. if (this.blocks) {
  20397. for (var index = 0; index < this.blocks.length; index++) {
  20398. var block = this.blocks[index];
  20399. block.intersectsRay(ray, selection);
  20400. }
  20401. return;
  20402. }
  20403. selection.concatWithNoDuplicate(this.entries);
  20404. }
  20405. };
  20406. OctreeBlock.prototype.createInnerBlocks = function () {
  20407. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  20408. };
  20409. return OctreeBlock;
  20410. })();
  20411. BABYLON.OctreeBlock = OctreeBlock;
  20412. })(BABYLON || (BABYLON = {}));
  20413. //# sourceMappingURL=babylon.octreeBlock.js.map
  20414. var BABYLON;
  20415. (function (BABYLON) {
  20416. var Bone = (function () {
  20417. function Bone(name, skeleton, parentBone, matrix) {
  20418. this.name = name;
  20419. this.children = new Array();
  20420. this.animations = new Array();
  20421. this._worldTransform = new BABYLON.Matrix();
  20422. this._absoluteTransform = new BABYLON.Matrix();
  20423. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  20424. this._skeleton = skeleton;
  20425. this._matrix = matrix;
  20426. this._baseMatrix = matrix;
  20427. skeleton.bones.push(this);
  20428. if (parentBone) {
  20429. this._parent = parentBone;
  20430. parentBone.children.push(this);
  20431. }
  20432. else {
  20433. this._parent = null;
  20434. }
  20435. this._updateDifferenceMatrix();
  20436. }
  20437. // Members
  20438. Bone.prototype.getParent = function () {
  20439. return this._parent;
  20440. };
  20441. Bone.prototype.getLocalMatrix = function () {
  20442. return this._matrix;
  20443. };
  20444. Bone.prototype.getBaseMatrix = function () {
  20445. return this._baseMatrix;
  20446. };
  20447. Bone.prototype.getWorldMatrix = function () {
  20448. return this._worldTransform;
  20449. };
  20450. Bone.prototype.getInvertedAbsoluteTransform = function () {
  20451. return this._invertedAbsoluteTransform;
  20452. };
  20453. Bone.prototype.getAbsoluteMatrix = function () {
  20454. var matrix = this._matrix.clone();
  20455. var parent = this._parent;
  20456. while (parent) {
  20457. matrix = matrix.multiply(parent.getLocalMatrix());
  20458. parent = parent.getParent();
  20459. }
  20460. return matrix;
  20461. };
  20462. // Methods
  20463. Bone.prototype.updateMatrix = function (matrix) {
  20464. this._matrix = matrix;
  20465. this._skeleton._markAsDirty();
  20466. this._updateDifferenceMatrix();
  20467. };
  20468. Bone.prototype._updateDifferenceMatrix = function () {
  20469. if (this._parent) {
  20470. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  20471. }
  20472. else {
  20473. this._absoluteTransform.copyFrom(this._matrix);
  20474. }
  20475. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  20476. for (var index = 0; index < this.children.length; index++) {
  20477. this.children[index]._updateDifferenceMatrix();
  20478. }
  20479. };
  20480. Bone.prototype.markAsDirty = function () {
  20481. this._skeleton._markAsDirty();
  20482. };
  20483. return Bone;
  20484. })();
  20485. BABYLON.Bone = Bone;
  20486. })(BABYLON || (BABYLON = {}));
  20487. //# sourceMappingURL=babylon.bone.js.map
  20488. var BABYLON;
  20489. (function (BABYLON) {
  20490. var Skeleton = (function () {
  20491. function Skeleton(name, id, scene) {
  20492. this.name = name;
  20493. this.id = id;
  20494. this.bones = new Array();
  20495. this._isDirty = true;
  20496. this._identity = BABYLON.Matrix.Identity();
  20497. this.bones = [];
  20498. this._scene = scene;
  20499. scene.skeletons.push(this);
  20500. this.prepare();
  20501. //make sure it will recalculate the matrix next time prepare is called.
  20502. this._isDirty = true;
  20503. }
  20504. // Members
  20505. Skeleton.prototype.getTransformMatrices = function () {
  20506. return this._transformMatrices;
  20507. };
  20508. // Methods
  20509. Skeleton.prototype._markAsDirty = function () {
  20510. this._isDirty = true;
  20511. };
  20512. Skeleton.prototype.prepare = function () {
  20513. if (!this._isDirty) {
  20514. return;
  20515. }
  20516. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  20517. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  20518. }
  20519. for (var index = 0; index < this.bones.length; index++) {
  20520. var bone = this.bones[index];
  20521. var parentBone = bone.getParent();
  20522. if (parentBone) {
  20523. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  20524. }
  20525. else {
  20526. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  20527. }
  20528. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  20529. }
  20530. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  20531. this._isDirty = false;
  20532. this._scene._activeBones += this.bones.length;
  20533. };
  20534. Skeleton.prototype.getAnimatables = function () {
  20535. if (!this._animatables || this._animatables.length !== this.bones.length) {
  20536. this._animatables = [];
  20537. for (var index = 0; index < this.bones.length; index++) {
  20538. this._animatables.push(this.bones[index]);
  20539. }
  20540. }
  20541. return this._animatables;
  20542. };
  20543. Skeleton.prototype.clone = function (name, id) {
  20544. var result = new Skeleton(name, id || name, this._scene);
  20545. for (var index = 0; index < this.bones.length; index++) {
  20546. var source = this.bones[index];
  20547. var parentBone = null;
  20548. if (source.getParent()) {
  20549. var parentIndex = this.bones.indexOf(source.getParent());
  20550. parentBone = result.bones[parentIndex];
  20551. }
  20552. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  20553. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  20554. }
  20555. return result;
  20556. };
  20557. return Skeleton;
  20558. })();
  20559. BABYLON.Skeleton = Skeleton;
  20560. })(BABYLON || (BABYLON = {}));
  20561. //# sourceMappingURL=babylon.skeleton.js.map
  20562. var BABYLON;
  20563. (function (BABYLON) {
  20564. var PostProcess = (function () {
  20565. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  20566. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  20567. this.name = name;
  20568. this.width = -1;
  20569. this.height = -1;
  20570. this._reusable = false;
  20571. this._textures = new BABYLON.SmartArray(2);
  20572. this._currentRenderTextureInd = 0;
  20573. if (camera != null) {
  20574. this._camera = camera;
  20575. this._scene = camera.getScene();
  20576. camera.attachPostProcess(this);
  20577. this._engine = this._scene.getEngine();
  20578. }
  20579. else {
  20580. this._engine = engine;
  20581. }
  20582. this._renderRatio = ratio;
  20583. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  20584. this._reusable = reusable || false;
  20585. samplers = samplers || [];
  20586. samplers.push("textureSampler");
  20587. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  20588. }
  20589. PostProcess.prototype.isReusable = function () {
  20590. return this._reusable;
  20591. };
  20592. PostProcess.prototype.activate = function (camera, sourceTexture) {
  20593. camera = camera || this._camera;
  20594. var scene = camera.getScene();
  20595. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  20596. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  20597. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  20598. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  20599. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  20600. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  20601. if (this._textures.length > 0) {
  20602. for (var i = 0; i < this._textures.length; i++) {
  20603. this._engine._releaseTexture(this._textures.data[i]);
  20604. }
  20605. this._textures.reset();
  20606. }
  20607. this.width = desiredWidth;
  20608. this.height = desiredHeight;
  20609. 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 }));
  20610. if (this._reusable) {
  20611. 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 }));
  20612. }
  20613. if (this.onSizeChanged) {
  20614. this.onSizeChanged();
  20615. }
  20616. }
  20617. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  20618. if (this.onActivate) {
  20619. this.onActivate(camera);
  20620. }
  20621. // Clear
  20622. if (this.clearColor) {
  20623. this._engine.clear(this.clearColor, true, true);
  20624. }
  20625. else {
  20626. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  20627. }
  20628. if (this._reusable) {
  20629. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  20630. }
  20631. };
  20632. PostProcess.prototype.apply = function () {
  20633. // Check
  20634. if (!this._effect.isReady())
  20635. return null;
  20636. // States
  20637. this._engine.enableEffect(this._effect);
  20638. this._engine.setState(false);
  20639. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20640. this._engine.setDepthBuffer(false);
  20641. this._engine.setDepthWrite(false);
  20642. // Texture
  20643. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  20644. // Parameters
  20645. if (this.onApply) {
  20646. this.onApply(this._effect);
  20647. }
  20648. return this._effect;
  20649. };
  20650. PostProcess.prototype.dispose = function (camera) {
  20651. camera = camera || this._camera;
  20652. if (this._textures.length > 0) {
  20653. for (var i = 0; i < this._textures.length; i++) {
  20654. this._engine._releaseTexture(this._textures.data[i]);
  20655. }
  20656. this._textures.reset();
  20657. }
  20658. if (!camera) {
  20659. return;
  20660. }
  20661. camera.detachPostProcess(this);
  20662. var index = camera._postProcesses.indexOf(this);
  20663. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  20664. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  20665. }
  20666. };
  20667. return PostProcess;
  20668. })();
  20669. BABYLON.PostProcess = PostProcess;
  20670. })(BABYLON || (BABYLON = {}));
  20671. //# sourceMappingURL=babylon.postProcess.js.map
  20672. var BABYLON;
  20673. (function (BABYLON) {
  20674. var PostProcessManager = (function () {
  20675. function PostProcessManager(scene) {
  20676. this._vertexDeclaration = [2];
  20677. this._vertexStrideSize = 2 * 4;
  20678. this._scene = scene;
  20679. }
  20680. PostProcessManager.prototype._prepareBuffers = function () {
  20681. if (this._vertexBuffer) {
  20682. return;
  20683. }
  20684. // VBO
  20685. var vertices = [];
  20686. vertices.push(1, 1);
  20687. vertices.push(-1, 1);
  20688. vertices.push(-1, -1);
  20689. vertices.push(1, -1);
  20690. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  20691. // Indices
  20692. var indices = [];
  20693. indices.push(0);
  20694. indices.push(1);
  20695. indices.push(2);
  20696. indices.push(0);
  20697. indices.push(2);
  20698. indices.push(3);
  20699. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  20700. };
  20701. // Methods
  20702. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  20703. var postProcesses = this._scene.activeCamera._postProcesses;
  20704. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  20705. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  20706. return false;
  20707. }
  20708. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  20709. return true;
  20710. };
  20711. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  20712. var engine = this._scene.getEngine();
  20713. for (var index = 0; index < postProcesses.length; index++) {
  20714. if (index < postProcesses.length - 1) {
  20715. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  20716. }
  20717. else {
  20718. if (targetTexture) {
  20719. engine.bindFramebuffer(targetTexture);
  20720. }
  20721. else {
  20722. engine.restoreDefaultFramebuffer();
  20723. }
  20724. }
  20725. var pp = postProcesses[index];
  20726. var effect = pp.apply();
  20727. if (effect) {
  20728. if (pp.onBeforeRender) {
  20729. pp.onBeforeRender(effect);
  20730. }
  20731. // VBOs
  20732. this._prepareBuffers();
  20733. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20734. // Draw order
  20735. engine.draw(true, 0, 6);
  20736. }
  20737. }
  20738. // Restore depth buffer
  20739. engine.setDepthBuffer(true);
  20740. engine.setDepthWrite(true);
  20741. };
  20742. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  20743. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  20744. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  20745. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  20746. return;
  20747. }
  20748. var engine = this._scene.getEngine();
  20749. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  20750. if (index < postProcessesTakenIndices.length - 1) {
  20751. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  20752. }
  20753. else {
  20754. if (targetTexture) {
  20755. engine.bindFramebuffer(targetTexture);
  20756. }
  20757. else {
  20758. engine.restoreDefaultFramebuffer();
  20759. }
  20760. }
  20761. if (doNotPresent) {
  20762. break;
  20763. }
  20764. var pp = postProcesses[postProcessesTakenIndices[index]];
  20765. var effect = pp.apply();
  20766. if (effect) {
  20767. if (pp.onBeforeRender) {
  20768. pp.onBeforeRender(effect);
  20769. }
  20770. // VBOs
  20771. this._prepareBuffers();
  20772. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20773. // Draw order
  20774. engine.draw(true, 0, 6);
  20775. }
  20776. }
  20777. // Restore depth buffer
  20778. engine.setDepthBuffer(true);
  20779. engine.setDepthWrite(true);
  20780. };
  20781. PostProcessManager.prototype.dispose = function () {
  20782. if (this._vertexBuffer) {
  20783. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20784. this._vertexBuffer = null;
  20785. }
  20786. if (this._indexBuffer) {
  20787. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20788. this._indexBuffer = null;
  20789. }
  20790. };
  20791. return PostProcessManager;
  20792. })();
  20793. BABYLON.PostProcessManager = PostProcessManager;
  20794. })(BABYLON || (BABYLON = {}));
  20795. //# sourceMappingURL=babylon.postProcessManager.js.map
  20796. var __extends = this.__extends || function (d, b) {
  20797. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20798. function __() { this.constructor = d; }
  20799. __.prototype = b.prototype;
  20800. d.prototype = new __();
  20801. };
  20802. var BABYLON;
  20803. (function (BABYLON) {
  20804. var PassPostProcess = (function (_super) {
  20805. __extends(PassPostProcess, _super);
  20806. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20807. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  20808. }
  20809. return PassPostProcess;
  20810. })(BABYLON.PostProcess);
  20811. BABYLON.PassPostProcess = PassPostProcess;
  20812. })(BABYLON || (BABYLON = {}));
  20813. //# sourceMappingURL=babylon.passPostProcess.js.map
  20814. var __extends = this.__extends || function (d, b) {
  20815. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20816. function __() { this.constructor = d; }
  20817. __.prototype = b.prototype;
  20818. d.prototype = new __();
  20819. };
  20820. var BABYLON;
  20821. (function (BABYLON) {
  20822. var BlurPostProcess = (function (_super) {
  20823. __extends(BlurPostProcess, _super);
  20824. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  20825. var _this = this;
  20826. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  20827. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  20828. this.direction = direction;
  20829. this.blurWidth = blurWidth;
  20830. this.onApply = function (effect) {
  20831. effect.setFloat2("screenSize", _this.width, _this.height);
  20832. effect.setVector2("direction", _this.direction);
  20833. effect.setFloat("blurWidth", _this.blurWidth);
  20834. };
  20835. }
  20836. return BlurPostProcess;
  20837. })(BABYLON.PostProcess);
  20838. BABYLON.BlurPostProcess = BlurPostProcess;
  20839. })(BABYLON || (BABYLON = {}));
  20840. //# sourceMappingURL=babylon.blurPostProcess.js.map
  20841. var __extends = this.__extends || function (d, b) {
  20842. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20843. function __() { this.constructor = d; }
  20844. __.prototype = b.prototype;
  20845. d.prototype = new __();
  20846. };
  20847. var BABYLON;
  20848. (function (BABYLON) {
  20849. var RefractionPostProcess = (function (_super) {
  20850. __extends(RefractionPostProcess, _super);
  20851. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  20852. var _this = this;
  20853. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  20854. this.color = color;
  20855. this.depth = depth;
  20856. this.colorLevel = colorLevel;
  20857. this.onActivate = function (cam) {
  20858. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  20859. };
  20860. this.onApply = function (effect) {
  20861. effect.setColor3("baseColor", _this.color);
  20862. effect.setFloat("depth", _this.depth);
  20863. effect.setFloat("colorLevel", _this.colorLevel);
  20864. effect.setTexture("refractionSampler", _this._refRexture);
  20865. };
  20866. }
  20867. // Methods
  20868. RefractionPostProcess.prototype.dispose = function (camera) {
  20869. if (this._refRexture) {
  20870. this._refRexture.dispose();
  20871. }
  20872. _super.prototype.dispose.call(this, camera);
  20873. };
  20874. return RefractionPostProcess;
  20875. })(BABYLON.PostProcess);
  20876. BABYLON.RefractionPostProcess = RefractionPostProcess;
  20877. })(BABYLON || (BABYLON = {}));
  20878. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  20879. var __extends = this.__extends || function (d, b) {
  20880. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20881. function __() { this.constructor = d; }
  20882. __.prototype = b.prototype;
  20883. d.prototype = new __();
  20884. };
  20885. var BABYLON;
  20886. (function (BABYLON) {
  20887. var BlackAndWhitePostProcess = (function (_super) {
  20888. __extends(BlackAndWhitePostProcess, _super);
  20889. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20890. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  20891. }
  20892. return BlackAndWhitePostProcess;
  20893. })(BABYLON.PostProcess);
  20894. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  20895. })(BABYLON || (BABYLON = {}));
  20896. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  20897. var __extends = this.__extends || function (d, b) {
  20898. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20899. function __() { this.constructor = d; }
  20900. __.prototype = b.prototype;
  20901. d.prototype = new __();
  20902. };
  20903. var BABYLON;
  20904. (function (BABYLON) {
  20905. var ConvolutionPostProcess = (function (_super) {
  20906. __extends(ConvolutionPostProcess, _super);
  20907. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  20908. var _this = this;
  20909. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  20910. this.kernel = kernel;
  20911. this.onApply = function (effect) {
  20912. effect.setFloat2("screenSize", _this.width, _this.height);
  20913. effect.setArray("kernel", _this.kernel);
  20914. };
  20915. }
  20916. // Statics
  20917. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  20918. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  20919. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  20920. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  20921. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  20922. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  20923. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  20924. return ConvolutionPostProcess;
  20925. })(BABYLON.PostProcess);
  20926. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  20927. })(BABYLON || (BABYLON = {}));
  20928. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  20929. var __extends = this.__extends || function (d, b) {
  20930. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20931. function __() { this.constructor = d; }
  20932. __.prototype = b.prototype;
  20933. d.prototype = new __();
  20934. };
  20935. var BABYLON;
  20936. (function (BABYLON) {
  20937. var FilterPostProcess = (function (_super) {
  20938. __extends(FilterPostProcess, _super);
  20939. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  20940. var _this = this;
  20941. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  20942. this.kernelMatrix = kernelMatrix;
  20943. this.onApply = function (effect) {
  20944. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  20945. };
  20946. }
  20947. return FilterPostProcess;
  20948. })(BABYLON.PostProcess);
  20949. BABYLON.FilterPostProcess = FilterPostProcess;
  20950. })(BABYLON || (BABYLON = {}));
  20951. //# sourceMappingURL=babylon.filterPostProcess.js.map
  20952. var __extends = this.__extends || function (d, b) {
  20953. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20954. function __() { this.constructor = d; }
  20955. __.prototype = b.prototype;
  20956. d.prototype = new __();
  20957. };
  20958. var BABYLON;
  20959. (function (BABYLON) {
  20960. var FxaaPostProcess = (function (_super) {
  20961. __extends(FxaaPostProcess, _super);
  20962. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20963. var _this = this;
  20964. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  20965. this.onSizeChanged = function () {
  20966. _this.texelWidth = 1.0 / _this.width;
  20967. _this.texelHeight = 1.0 / _this.height;
  20968. };
  20969. this.onApply = function (effect) {
  20970. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  20971. };
  20972. }
  20973. return FxaaPostProcess;
  20974. })(BABYLON.PostProcess);
  20975. BABYLON.FxaaPostProcess = FxaaPostProcess;
  20976. })(BABYLON || (BABYLON = {}));
  20977. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  20978. var BABYLON;
  20979. (function (BABYLON) {
  20980. var LensFlare = (function () {
  20981. function LensFlare(size, position, color, imgUrl, system) {
  20982. this.size = size;
  20983. this.position = position;
  20984. this.dispose = function () {
  20985. if (this.texture) {
  20986. this.texture.dispose();
  20987. }
  20988. // Remove from scene
  20989. var index = this._system.lensFlares.indexOf(this);
  20990. this._system.lensFlares.splice(index, 1);
  20991. };
  20992. this.color = color || new BABYLON.Color3(1, 1, 1);
  20993. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  20994. this._system = system;
  20995. system.lensFlares.push(this);
  20996. }
  20997. return LensFlare;
  20998. })();
  20999. BABYLON.LensFlare = LensFlare;
  21000. })(BABYLON || (BABYLON = {}));
  21001. //# sourceMappingURL=babylon.lensFlare.js.map
  21002. var BABYLON;
  21003. (function (BABYLON) {
  21004. var LensFlareSystem = (function () {
  21005. function LensFlareSystem(name, emitter, scene) {
  21006. this.name = name;
  21007. this.lensFlares = new Array();
  21008. this.borderLimit = 300;
  21009. this._vertexDeclaration = [2];
  21010. this._vertexStrideSize = 2 * 4;
  21011. this._isEnabled = true;
  21012. this._scene = scene;
  21013. this._emitter = emitter;
  21014. scene.lensFlareSystems.push(this);
  21015. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  21016. // VBO
  21017. var vertices = [];
  21018. vertices.push(1, 1);
  21019. vertices.push(-1, 1);
  21020. vertices.push(-1, -1);
  21021. vertices.push(1, -1);
  21022. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21023. // Indices
  21024. var indices = [];
  21025. indices.push(0);
  21026. indices.push(1);
  21027. indices.push(2);
  21028. indices.push(0);
  21029. indices.push(2);
  21030. indices.push(3);
  21031. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21032. // Effects
  21033. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  21034. }
  21035. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  21036. get: function () {
  21037. return this._isEnabled;
  21038. },
  21039. set: function (value) {
  21040. this._isEnabled = value;
  21041. },
  21042. enumerable: true,
  21043. configurable: true
  21044. });
  21045. LensFlareSystem.prototype.getScene = function () {
  21046. return this._scene;
  21047. };
  21048. LensFlareSystem.prototype.getEmitter = function () {
  21049. return this._emitter;
  21050. };
  21051. LensFlareSystem.prototype.getEmitterPosition = function () {
  21052. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  21053. };
  21054. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  21055. var position = this.getEmitterPosition();
  21056. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  21057. this._positionX = position.x;
  21058. this._positionY = position.y;
  21059. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  21060. if (position.z > 0) {
  21061. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  21062. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  21063. return true;
  21064. }
  21065. }
  21066. return false;
  21067. };
  21068. LensFlareSystem.prototype._isVisible = function () {
  21069. if (!this._isEnabled) {
  21070. return false;
  21071. }
  21072. var emitterPosition = this.getEmitterPosition();
  21073. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  21074. var distance = direction.length();
  21075. direction.normalize();
  21076. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  21077. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  21078. return !pickInfo.hit || pickInfo.distance > distance;
  21079. };
  21080. LensFlareSystem.prototype.render = function () {
  21081. if (!this._effect.isReady())
  21082. return false;
  21083. var engine = this._scene.getEngine();
  21084. var viewport = this._scene.activeCamera.viewport;
  21085. var globalViewport = viewport.toGlobal(engine);
  21086. // Position
  21087. if (!this.computeEffectivePosition(globalViewport)) {
  21088. return false;
  21089. }
  21090. // Visibility
  21091. if (!this._isVisible()) {
  21092. return false;
  21093. }
  21094. // Intensity
  21095. var awayX;
  21096. var awayY;
  21097. if (this._positionX < this.borderLimit + globalViewport.x) {
  21098. awayX = this.borderLimit + globalViewport.x - this._positionX;
  21099. }
  21100. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  21101. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  21102. }
  21103. else {
  21104. awayX = 0;
  21105. }
  21106. if (this._positionY < this.borderLimit + globalViewport.y) {
  21107. awayY = this.borderLimit + globalViewport.y - this._positionY;
  21108. }
  21109. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  21110. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  21111. }
  21112. else {
  21113. awayY = 0;
  21114. }
  21115. var away = (awayX > awayY) ? awayX : awayY;
  21116. if (away > this.borderLimit) {
  21117. away = this.borderLimit;
  21118. }
  21119. var intensity = 1.0 - (away / this.borderLimit);
  21120. if (intensity < 0) {
  21121. return false;
  21122. }
  21123. if (intensity > 1.0) {
  21124. intensity = 1.0;
  21125. }
  21126. // Position
  21127. var centerX = globalViewport.x + globalViewport.width / 2;
  21128. var centerY = globalViewport.y + globalViewport.height / 2;
  21129. var distX = centerX - this._positionX;
  21130. var distY = centerY - this._positionY;
  21131. // Effects
  21132. engine.enableEffect(this._effect);
  21133. engine.setState(false);
  21134. engine.setDepthBuffer(false);
  21135. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  21136. // VBOs
  21137. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21138. for (var index = 0; index < this.lensFlares.length; index++) {
  21139. var flare = this.lensFlares[index];
  21140. var x = centerX - (distX * flare.position);
  21141. var y = centerY - (distY * flare.position);
  21142. var cw = flare.size;
  21143. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  21144. var cx = 2 * (x / globalViewport.width) - 1.0;
  21145. var cy = 1.0 - 2 * (y / globalViewport.height);
  21146. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  21147. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  21148. // Texture
  21149. this._effect.setTexture("textureSampler", flare.texture);
  21150. // Color
  21151. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  21152. // Draw order
  21153. engine.draw(true, 0, 6);
  21154. }
  21155. engine.setDepthBuffer(true);
  21156. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21157. return true;
  21158. };
  21159. LensFlareSystem.prototype.dispose = function () {
  21160. if (this._vertexBuffer) {
  21161. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21162. this._vertexBuffer = null;
  21163. }
  21164. if (this._indexBuffer) {
  21165. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21166. this._indexBuffer = null;
  21167. }
  21168. while (this.lensFlares.length) {
  21169. this.lensFlares[0].dispose();
  21170. }
  21171. // Remove from scene
  21172. var index = this._scene.lensFlareSystems.indexOf(this);
  21173. this._scene.lensFlareSystems.splice(index, 1);
  21174. };
  21175. return LensFlareSystem;
  21176. })();
  21177. BABYLON.LensFlareSystem = LensFlareSystem;
  21178. })(BABYLON || (BABYLON = {}));
  21179. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  21180. var BABYLON;
  21181. (function (BABYLON) {
  21182. var CannonJSPlugin = (function () {
  21183. function CannonJSPlugin() {
  21184. this._registeredMeshes = [];
  21185. this._physicsMaterials = [];
  21186. this.updateBodyPosition = function (mesh) {
  21187. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21188. var registeredMesh = this._registeredMeshes[index];
  21189. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21190. var body = registeredMesh.body;
  21191. var center = mesh.getBoundingInfo().boundingBox.center;
  21192. body.position.set(center.x, center.z, center.y);
  21193. body.quaternion.x = mesh.rotationQuaternion.x;
  21194. body.quaternion.z = mesh.rotationQuaternion.y;
  21195. body.quaternion.y = mesh.rotationQuaternion.z;
  21196. body.quaternion.w = -mesh.rotationQuaternion.w;
  21197. return;
  21198. }
  21199. }
  21200. };
  21201. }
  21202. CannonJSPlugin.prototype.initialize = function (iterations) {
  21203. if (iterations === void 0) { iterations = 10; }
  21204. this._world = new CANNON.World();
  21205. this._world.broadphase = new CANNON.NaiveBroadphase();
  21206. this._world.solver.iterations = iterations;
  21207. };
  21208. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  21209. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21210. };
  21211. CannonJSPlugin.prototype.runOneStep = function (delta) {
  21212. this._world.step(delta);
  21213. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21214. var registeredMesh = this._registeredMeshes[index];
  21215. if (registeredMesh.isChild) {
  21216. continue;
  21217. }
  21218. // Body position
  21219. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  21220. var deltaPos = registeredMesh.delta;
  21221. if (deltaPos) {
  21222. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  21223. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  21224. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  21225. }
  21226. else {
  21227. registeredMesh.mesh.position.x = bodyX;
  21228. registeredMesh.mesh.position.y = bodyZ;
  21229. registeredMesh.mesh.position.z = bodyY;
  21230. }
  21231. if (!registeredMesh.mesh.rotationQuaternion) {
  21232. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21233. }
  21234. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  21235. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  21236. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  21237. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  21238. }
  21239. };
  21240. CannonJSPlugin.prototype.setGravity = function (gravity) {
  21241. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  21242. };
  21243. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21244. this.unregisterMesh(mesh);
  21245. mesh.computeWorldMatrix(true);
  21246. switch (impostor) {
  21247. case BABYLON.PhysicsEngine.SphereImpostor:
  21248. var bbox = mesh.getBoundingInfo().boundingBox;
  21249. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21250. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21251. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21252. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  21253. case BABYLON.PhysicsEngine.BoxImpostor:
  21254. bbox = mesh.getBoundingInfo().boundingBox;
  21255. var min = bbox.minimumWorld;
  21256. var max = bbox.maximumWorld;
  21257. var box = max.subtract(min).scale(0.5);
  21258. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  21259. case BABYLON.PhysicsEngine.PlaneImpostor:
  21260. return this._createPlane(mesh, options);
  21261. case BABYLON.PhysicsEngine.MeshImpostor:
  21262. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21263. var rawFaces = mesh.getIndices();
  21264. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  21265. }
  21266. return null;
  21267. };
  21268. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  21269. var shape = new CANNON.Sphere(radius);
  21270. if (!options) {
  21271. return shape;
  21272. }
  21273. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21274. };
  21275. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  21276. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  21277. if (!options) {
  21278. return shape;
  21279. }
  21280. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21281. };
  21282. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  21283. var shape = new CANNON.Plane();
  21284. if (!options) {
  21285. return shape;
  21286. }
  21287. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21288. };
  21289. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  21290. var verts = [], faces = [];
  21291. mesh.computeWorldMatrix(true);
  21292. for (var i = 0; i < rawVerts.length; i += 3) {
  21293. var transformed = BABYLON.Vector3.Zero();
  21294. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  21295. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  21296. }
  21297. for (var j = 0; j < rawFaces.length; j += 3) {
  21298. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  21299. }
  21300. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  21301. if (!options) {
  21302. return shape;
  21303. }
  21304. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21305. };
  21306. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  21307. var index;
  21308. var mat;
  21309. for (index = 0; index < this._physicsMaterials.length; index++) {
  21310. mat = this._physicsMaterials[index];
  21311. if (mat.friction === friction && mat.restitution === restitution) {
  21312. return mat;
  21313. }
  21314. }
  21315. var currentMat = new CANNON.Material();
  21316. currentMat.friction = friction;
  21317. currentMat.restitution = restitution;
  21318. this._physicsMaterials.push(currentMat);
  21319. for (index = 0; index < this._physicsMaterials.length; index++) {
  21320. mat = this._physicsMaterials[index];
  21321. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  21322. contactMaterial.contactEquationStiffness = 1e10;
  21323. contactMaterial.contactEquationRegularizationTime = 10;
  21324. this._world.addContactMaterial(contactMaterial);
  21325. }
  21326. return currentMat;
  21327. };
  21328. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  21329. var initialRotation = null;
  21330. if (mesh.rotationQuaternion) {
  21331. initialRotation = mesh.rotationQuaternion.clone();
  21332. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21333. }
  21334. // The delta between the mesh position and the mesh bounding box center
  21335. var bbox = mesh.getBoundingInfo().boundingBox;
  21336. var deltaPosition = mesh.position.subtract(bbox.center);
  21337. var material = this._addMaterial(friction, restitution);
  21338. var body = new CANNON.RigidBody(mass, shape, material);
  21339. if (initialRotation) {
  21340. body.quaternion.x = initialRotation.x;
  21341. body.quaternion.z = initialRotation.y;
  21342. body.quaternion.y = initialRotation.z;
  21343. body.quaternion.w = -initialRotation.w;
  21344. }
  21345. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  21346. this._world.add(body);
  21347. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  21348. return body;
  21349. };
  21350. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21351. var compoundShape = new CANNON.Compound();
  21352. for (var index = 0; index < parts.length; index++) {
  21353. var mesh = parts[index].mesh;
  21354. var shape = this.registerMesh(mesh, parts[index].impostor);
  21355. if (index == 0) {
  21356. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  21357. }
  21358. else {
  21359. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  21360. }
  21361. }
  21362. var initialMesh = parts[0].mesh;
  21363. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  21364. body.parts = parts;
  21365. return body;
  21366. };
  21367. CannonJSPlugin.prototype._unbindBody = function (body) {
  21368. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21369. var registeredMesh = this._registeredMeshes[index];
  21370. if (registeredMesh.body === body) {
  21371. registeredMesh.body = null;
  21372. registeredMesh.delta = 0;
  21373. }
  21374. }
  21375. };
  21376. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  21377. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21378. var registeredMesh = this._registeredMeshes[index];
  21379. if (registeredMesh.mesh === mesh) {
  21380. // Remove body
  21381. if (registeredMesh.body) {
  21382. this._world.remove(registeredMesh.body);
  21383. this._unbindBody(registeredMesh.body);
  21384. }
  21385. this._registeredMeshes.splice(index, 1);
  21386. return;
  21387. }
  21388. }
  21389. };
  21390. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21391. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  21392. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  21393. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21394. var registeredMesh = this._registeredMeshes[index];
  21395. if (registeredMesh.mesh === mesh) {
  21396. registeredMesh.body.applyImpulse(impulse, worldPoint);
  21397. return;
  21398. }
  21399. }
  21400. };
  21401. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  21402. var body1 = null, body2 = null;
  21403. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21404. var registeredMesh = this._registeredMeshes[index];
  21405. if (registeredMesh.mesh === mesh1) {
  21406. body1 = registeredMesh.body;
  21407. }
  21408. else if (registeredMesh.mesh === mesh2) {
  21409. body2 = registeredMesh.body;
  21410. }
  21411. }
  21412. if (!body1 || !body2) {
  21413. return false;
  21414. }
  21415. 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));
  21416. this._world.addConstraint(constraint);
  21417. return true;
  21418. };
  21419. CannonJSPlugin.prototype.dispose = function () {
  21420. while (this._registeredMeshes.length) {
  21421. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21422. }
  21423. };
  21424. CannonJSPlugin.prototype.isSupported = function () {
  21425. return window.CANNON !== undefined;
  21426. };
  21427. return CannonJSPlugin;
  21428. })();
  21429. BABYLON.CannonJSPlugin = CannonJSPlugin;
  21430. })(BABYLON || (BABYLON = {}));
  21431. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  21432. var BABYLON;
  21433. (function (BABYLON) {
  21434. var OimoJSPlugin = (function () {
  21435. function OimoJSPlugin() {
  21436. this._registeredMeshes = [];
  21437. /**
  21438. * Update the body position according to the mesh position
  21439. * @param mesh
  21440. */
  21441. this.updateBodyPosition = function (mesh) {
  21442. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21443. var registeredMesh = this._registeredMeshes[index];
  21444. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21445. var body = registeredMesh.body.body;
  21446. mesh.computeWorldMatrix(true);
  21447. var center = mesh.getBoundingInfo().boundingBox.center;
  21448. body.setPosition(center.x, center.y, center.z);
  21449. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  21450. return;
  21451. }
  21452. // Case where the parent has been updated
  21453. if (registeredMesh.mesh.parent === mesh) {
  21454. mesh.computeWorldMatrix(true);
  21455. registeredMesh.mesh.computeWorldMatrix(true);
  21456. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  21457. var absoluteRotation = mesh.rotation;
  21458. body = registeredMesh.body.body;
  21459. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  21460. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  21461. return;
  21462. }
  21463. }
  21464. };
  21465. }
  21466. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  21467. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21468. };
  21469. OimoJSPlugin.prototype.initialize = function (iterations) {
  21470. this._world = new OIMO.World();
  21471. this._world.clear();
  21472. };
  21473. OimoJSPlugin.prototype.setGravity = function (gravity) {
  21474. this._world.gravity = gravity;
  21475. };
  21476. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21477. var body = null;
  21478. this.unregisterMesh(mesh);
  21479. mesh.computeWorldMatrix(true);
  21480. var initialRotation = null;
  21481. if (mesh.rotationQuaternion) {
  21482. initialRotation = mesh.rotationQuaternion.clone();
  21483. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21484. mesh.computeWorldMatrix(true);
  21485. }
  21486. var bbox = mesh.getBoundingInfo().boundingBox;
  21487. // The delta between the mesh position and the mesh bounding box center
  21488. var deltaPosition = mesh.position.subtract(bbox.center);
  21489. // Transform delta position with the rotation
  21490. if (initialRotation) {
  21491. var m = new BABYLON.Matrix();
  21492. initialRotation.toRotationMatrix(m);
  21493. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  21494. }
  21495. switch (impostor) {
  21496. case BABYLON.PhysicsEngine.SphereImpostor:
  21497. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21498. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21499. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21500. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  21501. body = new OIMO.Body({
  21502. type: 'sphere',
  21503. size: [size],
  21504. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  21505. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  21506. move: options.mass != 0,
  21507. config: [options.mass, options.friction, options.restitution],
  21508. world: this._world
  21509. });
  21510. break;
  21511. case BABYLON.PhysicsEngine.PlaneImpostor:
  21512. case BABYLON.PhysicsEngine.CylinderImpostor:
  21513. case BABYLON.PhysicsEngine.BoxImpostor:
  21514. var min = bbox.minimumWorld;
  21515. var max = bbox.maximumWorld;
  21516. var box = max.subtract(min);
  21517. var sizeX = this._checkWithEpsilon(box.x);
  21518. var sizeY = this._checkWithEpsilon(box.y);
  21519. var sizeZ = this._checkWithEpsilon(box.z);
  21520. body = new OIMO.Body({
  21521. type: 'box',
  21522. size: [sizeX, sizeY, sizeZ],
  21523. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  21524. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  21525. move: options.mass != 0,
  21526. config: [options.mass, options.friction, options.restitution],
  21527. world: this._world
  21528. });
  21529. break;
  21530. }
  21531. //If quaternion was set as the rotation of the object
  21532. if (initialRotation) {
  21533. //We have to access the rigid body's properties to set the quaternion.
  21534. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  21535. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  21536. //update the internal rotation matrix
  21537. body.body.syncShapes();
  21538. }
  21539. this._registeredMeshes.push({
  21540. mesh: mesh,
  21541. body: body,
  21542. delta: deltaPosition
  21543. });
  21544. return body;
  21545. };
  21546. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21547. var types = [], sizes = [], positions = [], rotations = [];
  21548. var initialMesh = parts[0].mesh;
  21549. for (var index = 0; index < parts.length; index++) {
  21550. var part = parts[index];
  21551. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  21552. types.push(bodyParameters.type);
  21553. sizes.push.apply(sizes, bodyParameters.size);
  21554. positions.push.apply(positions, bodyParameters.pos);
  21555. rotations.push.apply(rotations, bodyParameters.rot);
  21556. }
  21557. var body = new OIMO.Body({
  21558. type: types,
  21559. size: sizes,
  21560. pos: positions,
  21561. rot: rotations,
  21562. move: options.mass != 0,
  21563. config: [options.mass, options.friction, options.restitution],
  21564. world: this._world
  21565. });
  21566. this._registeredMeshes.push({
  21567. mesh: initialMesh,
  21568. body: body
  21569. });
  21570. return body;
  21571. };
  21572. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  21573. var bodyParameters = null;
  21574. var mesh = part.mesh;
  21575. // We need the bounding box/sphere info to compute the physics body
  21576. mesh.computeWorldMatrix();
  21577. switch (part.impostor) {
  21578. case BABYLON.PhysicsEngine.SphereImpostor:
  21579. var bbox = mesh.getBoundingInfo().boundingBox;
  21580. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21581. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21582. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21583. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  21584. bodyParameters = {
  21585. type: 'sphere',
  21586. /* bug with oimo : sphere needs 3 sizes in this case */
  21587. size: [size, -1, -1],
  21588. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  21589. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  21590. };
  21591. break;
  21592. case BABYLON.PhysicsEngine.PlaneImpostor:
  21593. case BABYLON.PhysicsEngine.BoxImpostor:
  21594. bbox = mesh.getBoundingInfo().boundingBox;
  21595. var min = bbox.minimumWorld;
  21596. var max = bbox.maximumWorld;
  21597. var box = max.subtract(min);
  21598. var sizeX = this._checkWithEpsilon(box.x);
  21599. var sizeY = this._checkWithEpsilon(box.y);
  21600. var sizeZ = this._checkWithEpsilon(box.z);
  21601. var relativePosition = mesh.position;
  21602. bodyParameters = {
  21603. type: 'box',
  21604. size: [sizeX, sizeY, sizeZ],
  21605. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  21606. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  21607. };
  21608. break;
  21609. }
  21610. return bodyParameters;
  21611. };
  21612. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  21613. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21614. var registeredMesh = this._registeredMeshes[index];
  21615. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21616. if (registeredMesh.body) {
  21617. this._world.removeRigidBody(registeredMesh.body.body);
  21618. this._unbindBody(registeredMesh.body);
  21619. }
  21620. this._registeredMeshes.splice(index, 1);
  21621. return;
  21622. }
  21623. }
  21624. };
  21625. OimoJSPlugin.prototype._unbindBody = function (body) {
  21626. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21627. var registeredMesh = this._registeredMeshes[index];
  21628. if (registeredMesh.body === body) {
  21629. registeredMesh.body = null;
  21630. }
  21631. }
  21632. };
  21633. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21634. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21635. var registeredMesh = this._registeredMeshes[index];
  21636. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21637. // Get object mass to have a behaviour similar to cannon.js
  21638. var mass = registeredMesh.body.body.massInfo.mass;
  21639. // The force is scaled with the mass of object
  21640. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  21641. return;
  21642. }
  21643. }
  21644. };
  21645. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  21646. var body1 = null, body2 = null;
  21647. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21648. var registeredMesh = this._registeredMeshes[index];
  21649. if (registeredMesh.mesh === mesh1) {
  21650. body1 = registeredMesh.body.body;
  21651. }
  21652. else if (registeredMesh.mesh === mesh2) {
  21653. body2 = registeredMesh.body.body;
  21654. }
  21655. }
  21656. if (!body1 || !body2) {
  21657. return false;
  21658. }
  21659. if (!options) {
  21660. options = {};
  21661. }
  21662. new OIMO.Link({
  21663. type: options.type,
  21664. body1: body1,
  21665. body2: body2,
  21666. min: options.min,
  21667. max: options.max,
  21668. axe1: options.axe1,
  21669. axe2: options.axe2,
  21670. pos1: [pivot1.x, pivot1.y, pivot1.z],
  21671. pos2: [pivot2.x, pivot2.y, pivot2.z],
  21672. collision: options.collision,
  21673. spring: options.spring,
  21674. world: this._world
  21675. });
  21676. return true;
  21677. };
  21678. OimoJSPlugin.prototype.dispose = function () {
  21679. this._world.clear();
  21680. while (this._registeredMeshes.length) {
  21681. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21682. }
  21683. };
  21684. OimoJSPlugin.prototype.isSupported = function () {
  21685. return OIMO !== undefined;
  21686. };
  21687. OimoJSPlugin.prototype._getLastShape = function (body) {
  21688. var lastShape = body.shapes;
  21689. while (lastShape.next) {
  21690. lastShape = lastShape.next;
  21691. }
  21692. return lastShape;
  21693. };
  21694. OimoJSPlugin.prototype.runOneStep = function (time) {
  21695. this._world.step();
  21696. // Update the position of all registered meshes
  21697. var i = this._registeredMeshes.length;
  21698. var m;
  21699. while (i--) {
  21700. var body = this._registeredMeshes[i].body.body;
  21701. var mesh = this._registeredMeshes[i].mesh;
  21702. var delta = this._registeredMeshes[i].delta;
  21703. if (!body.sleeping) {
  21704. if (body.shapes.next) {
  21705. var parentShape = this._getLastShape(body);
  21706. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  21707. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  21708. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  21709. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  21710. if (!mesh.rotationQuaternion) {
  21711. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21712. }
  21713. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  21714. mesh.computeWorldMatrix();
  21715. }
  21716. else {
  21717. m = body.getMatrix();
  21718. mtx = BABYLON.Matrix.FromArray(m);
  21719. // Body position
  21720. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  21721. if (!delta) {
  21722. mesh.position.x = bodyX;
  21723. mesh.position.y = bodyY;
  21724. mesh.position.z = bodyZ;
  21725. }
  21726. else {
  21727. mesh.position.x = bodyX + delta.x;
  21728. mesh.position.y = bodyY + delta.y;
  21729. mesh.position.z = bodyZ + delta.z;
  21730. }
  21731. if (!mesh.rotationQuaternion) {
  21732. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21733. }
  21734. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  21735. mesh.computeWorldMatrix();
  21736. }
  21737. }
  21738. }
  21739. };
  21740. return OimoJSPlugin;
  21741. })();
  21742. BABYLON.OimoJSPlugin = OimoJSPlugin;
  21743. })(BABYLON || (BABYLON = {}));
  21744. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  21745. var BABYLON;
  21746. (function (BABYLON) {
  21747. var PhysicsEngine = (function () {
  21748. function PhysicsEngine(plugin) {
  21749. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  21750. }
  21751. PhysicsEngine.prototype._initialize = function (gravity) {
  21752. this._currentPlugin.initialize();
  21753. this._setGravity(gravity);
  21754. };
  21755. PhysicsEngine.prototype._runOneStep = function (delta) {
  21756. if (delta > 0.1) {
  21757. delta = 0.1;
  21758. }
  21759. else if (delta <= 0) {
  21760. delta = 1.0 / 60.0;
  21761. }
  21762. this._currentPlugin.runOneStep(delta);
  21763. };
  21764. PhysicsEngine.prototype._setGravity = function (gravity) {
  21765. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  21766. this._currentPlugin.setGravity(this.gravity);
  21767. };
  21768. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  21769. return this._currentPlugin.registerMesh(mesh, impostor, options);
  21770. };
  21771. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  21772. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  21773. };
  21774. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  21775. this._currentPlugin.unregisterMesh(mesh);
  21776. };
  21777. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  21778. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  21779. };
  21780. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  21781. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  21782. };
  21783. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  21784. this._currentPlugin.updateBodyPosition(mesh);
  21785. };
  21786. PhysicsEngine.prototype.dispose = function () {
  21787. this._currentPlugin.dispose();
  21788. };
  21789. PhysicsEngine.prototype.isSupported = function () {
  21790. return this._currentPlugin.isSupported();
  21791. };
  21792. // Statics
  21793. PhysicsEngine.NoImpostor = 0;
  21794. PhysicsEngine.SphereImpostor = 1;
  21795. PhysicsEngine.BoxImpostor = 2;
  21796. PhysicsEngine.PlaneImpostor = 3;
  21797. PhysicsEngine.MeshImpostor = 4;
  21798. PhysicsEngine.CapsuleImpostor = 5;
  21799. PhysicsEngine.ConeImpostor = 6;
  21800. PhysicsEngine.CylinderImpostor = 7;
  21801. PhysicsEngine.ConvexHullImpostor = 8;
  21802. PhysicsEngine.Epsilon = 0.001;
  21803. return PhysicsEngine;
  21804. })();
  21805. BABYLON.PhysicsEngine = PhysicsEngine;
  21806. })(BABYLON || (BABYLON = {}));
  21807. //# sourceMappingURL=babylon.physicsEngine.js.map
  21808. var BABYLON;
  21809. (function (BABYLON) {
  21810. var serializeLight = function (light) {
  21811. var serializationObject = {};
  21812. serializationObject.name = light.name;
  21813. serializationObject.id = light.id;
  21814. serializationObject.tags = BABYLON.Tags.GetTags(light);
  21815. if (light instanceof BABYLON.PointLight) {
  21816. serializationObject.type = 0;
  21817. serializationObject.position = light.position.asArray();
  21818. }
  21819. else if (light instanceof BABYLON.DirectionalLight) {
  21820. serializationObject.type = 1;
  21821. var directionalLight = light;
  21822. serializationObject.position = directionalLight.position.asArray();
  21823. serializationObject.direction = directionalLight.direction.asArray();
  21824. }
  21825. else if (light instanceof BABYLON.SpotLight) {
  21826. serializationObject.type = 2;
  21827. var spotLight = light;
  21828. serializationObject.position = spotLight.position.asArray();
  21829. serializationObject.direction = spotLight.position.asArray();
  21830. serializationObject.angle = spotLight.angle;
  21831. serializationObject.exponent = spotLight.exponent;
  21832. }
  21833. else if (light instanceof BABYLON.HemisphericLight) {
  21834. serializationObject.type = 3;
  21835. var hemisphericLight = light;
  21836. serializationObject.direction = hemisphericLight.direction.asArray();
  21837. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  21838. }
  21839. if (light.intensity) {
  21840. serializationObject.intensity = light.intensity;
  21841. }
  21842. serializationObject.range = light.range;
  21843. serializationObject.diffuse = light.diffuse.asArray();
  21844. serializationObject.specular = light.specular.asArray();
  21845. return serializationObject;
  21846. };
  21847. var serializeFresnelParameter = function (fresnelParameter) {
  21848. var serializationObject = {};
  21849. serializationObject.isEnabled = fresnelParameter.isEnabled;
  21850. serializationObject.leftColor = fresnelParameter.leftColor;
  21851. serializationObject.rightColor = fresnelParameter.rightColor;
  21852. serializationObject.bias = fresnelParameter.bias;
  21853. serializationObject.power = fresnelParameter.power;
  21854. return serializationObject;
  21855. };
  21856. var appendAnimations = function (source, destination) {
  21857. if (source.animations) {
  21858. destination.animations = [];
  21859. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  21860. var animation = source.animations[animationIndex];
  21861. destination.animations.push(serializeAnimation(animation));
  21862. }
  21863. }
  21864. };
  21865. var serializeCamera = function (camera) {
  21866. var serializationObject = {};
  21867. serializationObject.name = camera.name;
  21868. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  21869. serializationObject.id = camera.id;
  21870. serializationObject.position = camera.position.asArray();
  21871. // Parent
  21872. if (camera.parent) {
  21873. serializationObject.parentId = camera.parent.id;
  21874. }
  21875. serializationObject.fov = camera.fov;
  21876. serializationObject.minZ = camera.minZ;
  21877. serializationObject.maxZ = camera.maxZ;
  21878. serializationObject.inertia = camera.inertia;
  21879. //setting the type
  21880. if (camera instanceof BABYLON.FreeCamera) {
  21881. serializationObject.type = "FreeCamera";
  21882. }
  21883. else if (camera instanceof BABYLON.ArcRotateCamera) {
  21884. serializationObject.type = "ArcRotateCamera";
  21885. }
  21886. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  21887. serializationObject.type = "AnaglyphArcRotateCamera";
  21888. }
  21889. else if (camera instanceof BABYLON.GamepadCamera) {
  21890. serializationObject.type = "GamepadCamera";
  21891. }
  21892. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  21893. serializationObject.type = "AnaglyphFreeCamera";
  21894. }
  21895. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  21896. serializationObject.type = "DeviceOrientationCamera";
  21897. }
  21898. else if (camera instanceof BABYLON.FollowCamera) {
  21899. serializationObject.type = "FollowCamera";
  21900. }
  21901. else if (camera instanceof BABYLON.OculusCamera) {
  21902. serializationObject.type = "OculusCamera";
  21903. }
  21904. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  21905. serializationObject.type = "OculusGamepadCamera";
  21906. }
  21907. else if (camera instanceof BABYLON.TouchCamera) {
  21908. serializationObject.type = "TouchCamera";
  21909. }
  21910. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  21911. serializationObject.type = "VirtualJoysticksCamera";
  21912. }
  21913. else if (camera instanceof BABYLON.WebVRCamera) {
  21914. serializationObject.type = "WebVRCamera";
  21915. }
  21916. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  21917. serializationObject.type = "VRDeviceOrientationCamera";
  21918. }
  21919. //special properties of specific cameras
  21920. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  21921. var arcCamera = camera;
  21922. serializationObject.alpha = arcCamera.alpha;
  21923. serializationObject.beta = arcCamera.beta;
  21924. serializationObject.radius = arcCamera.radius;
  21925. if (arcCamera.target && arcCamera.target.id) {
  21926. serializationObject.lockedTargetId = arcCamera.target.id;
  21927. }
  21928. }
  21929. else if (camera instanceof BABYLON.FollowCamera) {
  21930. var followCam = camera;
  21931. serializationObject.radius = followCam.radius;
  21932. serializationObject.heightOffset = followCam.heightOffset;
  21933. serializationObject.rotationOffset = followCam.rotationOffset;
  21934. }
  21935. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  21936. //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.
  21937. if (camera['_eyeSpace'] !== undefined) {
  21938. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  21939. }
  21940. }
  21941. //general properties that not all cameras have. The [] is due to typescript's type safety
  21942. if (camera['speed'] !== undefined) {
  21943. serializationObject.speed = camera['speed'];
  21944. }
  21945. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  21946. serializationObject.target = camera['target'].asArray();
  21947. }
  21948. // Target
  21949. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  21950. serializationObject.rotation = camera['rotation'].asArray();
  21951. }
  21952. // Locked target
  21953. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  21954. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  21955. }
  21956. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  21957. serializationObject.applyGravity = camera['applyGravity'] || false;
  21958. if (camera['ellipsoid']) {
  21959. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  21960. }
  21961. // Animations
  21962. appendAnimations(camera, serializationObject);
  21963. // Layer mask
  21964. serializationObject.layerMask = camera.layerMask;
  21965. return serializationObject;
  21966. };
  21967. var serializeAnimation = function (animation) {
  21968. var serializationObject = {};
  21969. serializationObject.name = animation.name;
  21970. serializationObject.property = animation.targetProperty;
  21971. serializationObject.framePerSecond = animation.framePerSecond;
  21972. serializationObject.dataType = animation.dataType;
  21973. serializationObject.loopBehavior = animation.loopMode;
  21974. var dataType = animation.dataType;
  21975. serializationObject.keys = [];
  21976. var keys = animation.getKeys();
  21977. for (var index = 0; index < keys.length; index++) {
  21978. var animationKey = keys[index];
  21979. var key = {};
  21980. key.frame = animationKey.frame;
  21981. switch (dataType) {
  21982. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  21983. key.values = [animationKey.value];
  21984. break;
  21985. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  21986. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  21987. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  21988. key.values = animationKey.value.asArray();
  21989. break;
  21990. }
  21991. serializationObject.keys.push(key);
  21992. }
  21993. return serializationObject;
  21994. };
  21995. var serializeMultiMaterial = function (material) {
  21996. var serializationObject = {};
  21997. serializationObject.name = material.name;
  21998. serializationObject.id = material.id;
  21999. serializationObject.tags = BABYLON.Tags.GetTags(material);
  22000. serializationObject.materials = [];
  22001. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  22002. var subMat = material.subMaterials[matIndex];
  22003. if (subMat) {
  22004. serializationObject.materials.push(subMat.id);
  22005. }
  22006. else {
  22007. serializationObject.materials.push(null);
  22008. }
  22009. }
  22010. return serializationObject;
  22011. };
  22012. var serializeMaterial = function (material) {
  22013. var serializationObject = {};
  22014. serializationObject.name = material.name;
  22015. serializationObject.ambient = material.ambientColor.asArray();
  22016. serializationObject.diffuse = material.diffuseColor.asArray();
  22017. serializationObject.specular = material.specularColor.asArray();
  22018. serializationObject.specularPower = material.specularPower;
  22019. serializationObject.emissive = material.emissiveColor.asArray();
  22020. serializationObject.alpha = material.alpha;
  22021. serializationObject.id = material.id;
  22022. serializationObject.tags = BABYLON.Tags.GetTags(material);
  22023. serializationObject.backFaceCulling = material.backFaceCulling;
  22024. if (material.diffuseTexture) {
  22025. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  22026. }
  22027. if (material.diffuseFresnelParameters) {
  22028. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  22029. }
  22030. if (material.ambientTexture) {
  22031. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  22032. }
  22033. if (material.opacityTexture) {
  22034. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  22035. }
  22036. if (material.opacityFresnelParameters) {
  22037. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  22038. }
  22039. if (material.reflectionTexture) {
  22040. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  22041. }
  22042. if (material.reflectionFresnelParameters) {
  22043. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  22044. }
  22045. if (material.emissiveTexture) {
  22046. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  22047. }
  22048. if (material.emissiveFresnelParameters) {
  22049. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  22050. }
  22051. if (material.specularTexture) {
  22052. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  22053. }
  22054. if (material.bumpTexture) {
  22055. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  22056. }
  22057. return serializationObject;
  22058. };
  22059. var serializeTexture = function (texture) {
  22060. var serializationObject = {};
  22061. if (!texture.name) {
  22062. return null;
  22063. }
  22064. if (texture instanceof BABYLON.CubeTexture) {
  22065. serializationObject.name = texture.name;
  22066. serializationObject.hasAlpha = texture.hasAlpha;
  22067. serializationObject.level = texture.level;
  22068. serializationObject.coordinatesMode = texture.coordinatesMode;
  22069. return serializationObject;
  22070. }
  22071. if (texture instanceof BABYLON.MirrorTexture) {
  22072. var mirrorTexture = texture;
  22073. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  22074. serializationObject.renderList = [];
  22075. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  22076. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  22077. }
  22078. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  22079. }
  22080. else if (texture instanceof BABYLON.RenderTargetTexture) {
  22081. var renderTargetTexture = texture;
  22082. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  22083. serializationObject.renderList = [];
  22084. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  22085. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  22086. }
  22087. }
  22088. var regularTexture = texture;
  22089. serializationObject.name = texture.name;
  22090. serializationObject.hasAlpha = texture.hasAlpha;
  22091. serializationObject.level = texture.level;
  22092. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  22093. serializationObject.coordinatesMode = texture.coordinatesMode;
  22094. serializationObject.uOffset = regularTexture.uOffset;
  22095. serializationObject.vOffset = regularTexture.vOffset;
  22096. serializationObject.uScale = regularTexture.uScale;
  22097. serializationObject.vScale = regularTexture.vScale;
  22098. serializationObject.uAng = regularTexture.uAng;
  22099. serializationObject.vAng = regularTexture.vAng;
  22100. serializationObject.wAng = regularTexture.wAng;
  22101. serializationObject.wrapU = texture.wrapU;
  22102. serializationObject.wrapV = texture.wrapV;
  22103. // Animations
  22104. appendAnimations(texture, serializationObject);
  22105. return serializationObject;
  22106. };
  22107. var serializeSkeleton = function (skeleton) {
  22108. var serializationObject = {};
  22109. serializationObject.name = skeleton.name;
  22110. serializationObject.id = skeleton.id;
  22111. serializationObject.bones = [];
  22112. for (var index = 0; index < skeleton.bones.length; index++) {
  22113. var bone = skeleton.bones[index];
  22114. var serializedBone = {
  22115. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  22116. name: bone.name,
  22117. matrix: bone.getLocalMatrix().toArray()
  22118. };
  22119. serializationObject.bones.push(serializedBone);
  22120. if (bone.animations && bone.animations.length > 0) {
  22121. serializedBone.animation = serializeAnimation(bone.animations[0]);
  22122. }
  22123. }
  22124. return serializationObject;
  22125. };
  22126. var serializeParticleSystem = function (particleSystem) {
  22127. var serializationObject = {};
  22128. serializationObject.emitterId = particleSystem.emitter.id;
  22129. serializationObject.capacity = particleSystem.getCapacity();
  22130. if (particleSystem.particleTexture) {
  22131. serializationObject.textureName = particleSystem.particleTexture.name;
  22132. }
  22133. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  22134. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  22135. serializationObject.minSize = particleSystem.minSize;
  22136. serializationObject.maxSize = particleSystem.maxSize;
  22137. serializationObject.minLifeTime = particleSystem.minLifeTime;
  22138. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  22139. serializationObject.emitRate = particleSystem.emitRate;
  22140. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  22141. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  22142. serializationObject.gravity = particleSystem.gravity.asArray();
  22143. serializationObject.direction1 = particleSystem.direction1.asArray();
  22144. serializationObject.direction2 = particleSystem.direction2.asArray();
  22145. serializationObject.color1 = particleSystem.color1.asArray();
  22146. serializationObject.color2 = particleSystem.color2.asArray();
  22147. serializationObject.colorDead = particleSystem.colorDead.asArray();
  22148. serializationObject.updateSpeed = particleSystem.updateSpeed;
  22149. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  22150. serializationObject.textureMask = particleSystem.textureMask.asArray();
  22151. serializationObject.blendMode = particleSystem.blendMode;
  22152. return serializationObject;
  22153. };
  22154. var serializeLensFlareSystem = function (lensFlareSystem) {
  22155. var serializationObject = {};
  22156. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  22157. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  22158. serializationObject.flares = [];
  22159. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  22160. var flare = lensFlareSystem.lensFlares[index];
  22161. serializationObject.flares.push({
  22162. size: flare.size,
  22163. position: flare.position,
  22164. color: flare.color.asArray(),
  22165. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  22166. });
  22167. }
  22168. return serializationObject;
  22169. };
  22170. var serializeShadowGenerator = function (light) {
  22171. var serializationObject = {};
  22172. var shadowGenerator = light.getShadowGenerator();
  22173. serializationObject.lightId = light.id;
  22174. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  22175. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  22176. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  22177. serializationObject.renderList = [];
  22178. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  22179. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  22180. serializationObject.renderList.push(mesh.id);
  22181. }
  22182. return serializationObject;
  22183. };
  22184. var serializedGeometries = [];
  22185. var serializeGeometry = function (geometry, serializationGeometries) {
  22186. if (serializedGeometries[geometry.id]) {
  22187. return;
  22188. }
  22189. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  22190. serializationGeometries.boxes.push(serializeBox(geometry));
  22191. }
  22192. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  22193. serializationGeometries.spheres.push(serializeSphere(geometry));
  22194. }
  22195. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  22196. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  22197. }
  22198. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  22199. serializationGeometries.toruses.push(serializeTorus(geometry));
  22200. }
  22201. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  22202. serializationGeometries.grounds.push(serializeGround(geometry));
  22203. }
  22204. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  22205. serializationGeometries.planes.push(serializePlane(geometry));
  22206. }
  22207. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  22208. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  22209. }
  22210. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  22211. throw new Error("Unknow primitive type");
  22212. }
  22213. else {
  22214. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  22215. }
  22216. serializedGeometries[geometry.id] = true;
  22217. };
  22218. var serializeGeometryBase = function (geometry) {
  22219. var serializationObject = {};
  22220. serializationObject.id = geometry.id;
  22221. if (BABYLON.Tags.HasTags(geometry)) {
  22222. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  22223. }
  22224. return serializationObject;
  22225. };
  22226. var serializeVertexData = function (vertexData) {
  22227. var serializationObject = serializeGeometryBase(vertexData);
  22228. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22229. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22230. }
  22231. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22232. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22233. }
  22234. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22235. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22236. }
  22237. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22238. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  22239. }
  22240. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22241. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  22242. }
  22243. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22244. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22245. serializationObject.matricesIndices._isExpanded = true;
  22246. }
  22247. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22248. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22249. }
  22250. serializationObject.indices = vertexData.getIndices();
  22251. return serializationObject;
  22252. };
  22253. var serializePrimitive = function (primitive) {
  22254. var serializationObject = serializeGeometryBase(primitive);
  22255. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  22256. return serializationObject;
  22257. };
  22258. var serializeBox = function (box) {
  22259. var serializationObject = serializePrimitive(box);
  22260. serializationObject.size = box.size;
  22261. return serializationObject;
  22262. };
  22263. var serializeSphere = function (sphere) {
  22264. var serializationObject = serializePrimitive(sphere);
  22265. serializationObject.segments = sphere.segments;
  22266. serializationObject.diameter = sphere.diameter;
  22267. return serializationObject;
  22268. };
  22269. var serializeCylinder = function (cylinder) {
  22270. var serializationObject = serializePrimitive(cylinder);
  22271. serializationObject.height = cylinder.height;
  22272. serializationObject.diameterTop = cylinder.diameterTop;
  22273. serializationObject.diameterBottom = cylinder.diameterBottom;
  22274. serializationObject.tessellation = cylinder.tessellation;
  22275. return serializationObject;
  22276. };
  22277. var serializeTorus = function (torus) {
  22278. var serializationObject = serializePrimitive(torus);
  22279. serializationObject.diameter = torus.diameter;
  22280. serializationObject.thickness = torus.thickness;
  22281. serializationObject.tessellation = torus.tessellation;
  22282. return serializationObject;
  22283. };
  22284. var serializeGround = function (ground) {
  22285. var serializationObject = serializePrimitive(ground);
  22286. serializationObject.width = ground.width;
  22287. serializationObject.height = ground.height;
  22288. serializationObject.subdivisions = ground.subdivisions;
  22289. return serializationObject;
  22290. };
  22291. var serializePlane = function (plane) {
  22292. var serializationObject = serializePrimitive(plane);
  22293. serializationObject.size = plane.size;
  22294. return serializationObject;
  22295. };
  22296. var serializeTorusKnot = function (torusKnot) {
  22297. var serializationObject = serializePrimitive(torusKnot);
  22298. serializationObject.radius = torusKnot.radius;
  22299. serializationObject.tube = torusKnot.tube;
  22300. serializationObject.radialSegments = torusKnot.radialSegments;
  22301. serializationObject.tubularSegments = torusKnot.tubularSegments;
  22302. serializationObject.p = torusKnot.p;
  22303. serializationObject.q = torusKnot.q;
  22304. return serializationObject;
  22305. };
  22306. var serializeMesh = function (mesh, serializationScene) {
  22307. var serializationObject = {};
  22308. serializationObject.name = mesh.name;
  22309. serializationObject.id = mesh.id;
  22310. if (BABYLON.Tags.HasTags(mesh)) {
  22311. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  22312. }
  22313. serializationObject.position = mesh.position.asArray();
  22314. if (mesh.rotationQuaternion) {
  22315. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  22316. }
  22317. else if (mesh.rotation) {
  22318. serializationObject.rotation = mesh.rotation.asArray();
  22319. }
  22320. serializationObject.scaling = mesh.scaling.asArray();
  22321. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  22322. serializationObject.isEnabled = mesh.isEnabled();
  22323. serializationObject.isVisible = mesh.isVisible;
  22324. serializationObject.infiniteDistance = mesh.infiniteDistance;
  22325. serializationObject.pickable = mesh.isPickable;
  22326. serializationObject.receiveShadows = mesh.receiveShadows;
  22327. serializationObject.billboardMode = mesh.billboardMode;
  22328. serializationObject.visibility = mesh.visibility;
  22329. serializationObject.checkCollisions = mesh.checkCollisions;
  22330. // Parent
  22331. if (mesh.parent) {
  22332. serializationObject.parentId = mesh.parent.id;
  22333. }
  22334. // Geometry
  22335. var geometry = mesh._geometry;
  22336. if (geometry) {
  22337. var geometryId = geometry.id;
  22338. serializationObject.geometryId = geometryId;
  22339. if (!mesh.getScene().getGeometryByID(geometryId)) {
  22340. // 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
  22341. serializeGeometry(geometry, serializationScene.geometries);
  22342. }
  22343. // SubMeshes
  22344. serializationObject.subMeshes = [];
  22345. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  22346. var subMesh = mesh.subMeshes[subIndex];
  22347. serializationObject.subMeshes.push({
  22348. materialIndex: subMesh.materialIndex,
  22349. verticesStart: subMesh.verticesStart,
  22350. verticesCount: subMesh.verticesCount,
  22351. indexStart: subMesh.indexStart,
  22352. indexCount: subMesh.indexCount
  22353. });
  22354. }
  22355. }
  22356. // Material
  22357. if (mesh.material) {
  22358. serializationObject.materialId = mesh.material.id;
  22359. }
  22360. else {
  22361. mesh.material = null;
  22362. }
  22363. // Skeleton
  22364. if (mesh.skeleton) {
  22365. serializationObject.skeletonId = mesh.skeleton.id;
  22366. }
  22367. // Physics
  22368. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  22369. serializationObject.physicsMass = mesh.getPhysicsMass();
  22370. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  22371. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  22372. switch (mesh.getPhysicsImpostor()) {
  22373. case BABYLON.PhysicsEngine.BoxImpostor:
  22374. serializationObject.physicsImpostor = 1;
  22375. break;
  22376. case BABYLON.PhysicsEngine.SphereImpostor:
  22377. serializationObject.physicsImpostor = 2;
  22378. break;
  22379. }
  22380. }
  22381. // Instances
  22382. serializationObject.instances = [];
  22383. for (var index = 0; index < mesh.instances.length; index++) {
  22384. var instance = mesh.instances[index];
  22385. var serializationInstance = {
  22386. name: instance.name,
  22387. position: instance.position,
  22388. rotation: instance.rotation,
  22389. rotationQuaternion: instance.rotationQuaternion,
  22390. scaling: instance.scaling
  22391. };
  22392. serializationObject.instances.push(serializationInstance);
  22393. // Animations
  22394. appendAnimations(instance, serializationInstance);
  22395. }
  22396. // Animations
  22397. appendAnimations(mesh, serializationObject);
  22398. // Layer mask
  22399. serializationObject.layerMask = mesh.layerMask;
  22400. return serializationObject;
  22401. };
  22402. var SceneSerializer = (function () {
  22403. function SceneSerializer() {
  22404. }
  22405. SceneSerializer.Serialize = function (scene) {
  22406. var serializationObject = {};
  22407. // Scene
  22408. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  22409. serializationObject.autoClear = scene.autoClear;
  22410. serializationObject.clearColor = scene.clearColor.asArray();
  22411. serializationObject.ambientColor = scene.ambientColor.asArray();
  22412. serializationObject.gravity = scene.gravity.asArray();
  22413. // Fog
  22414. if (scene.fogMode && scene.fogMode !== 0) {
  22415. serializationObject.fogMode = scene.fogMode;
  22416. serializationObject.fogColor = scene.fogColor.asArray();
  22417. serializationObject.fogStart = scene.fogStart;
  22418. serializationObject.fogEnd = scene.fogEnd;
  22419. serializationObject.fogDensity = scene.fogDensity;
  22420. }
  22421. // Lights
  22422. serializationObject.lights = [];
  22423. for (var index = 0; index < scene.lights.length; index++) {
  22424. var light = scene.lights[index];
  22425. serializationObject.lights.push(serializeLight(light));
  22426. }
  22427. // Cameras
  22428. serializationObject.cameras = [];
  22429. for (index = 0; index < scene.cameras.length; index++) {
  22430. var camera = scene.cameras[index];
  22431. serializationObject.cameras.push(serializeCamera(camera));
  22432. }
  22433. if (scene.activeCamera) {
  22434. serializationObject.activeCameraID = scene.activeCamera.id;
  22435. }
  22436. // Materials
  22437. serializationObject.materials = [];
  22438. serializationObject.multiMaterials = [];
  22439. for (index = 0; index < scene.materials.length; index++) {
  22440. var material = scene.materials[index];
  22441. if (material instanceof BABYLON.StandardMaterial) {
  22442. serializationObject.materials.push(serializeMaterial(material));
  22443. }
  22444. else if (material instanceof BABYLON.MultiMaterial) {
  22445. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  22446. }
  22447. }
  22448. // Skeletons
  22449. serializationObject.skeletons = [];
  22450. for (index = 0; index < scene.skeletons.length; index++) {
  22451. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  22452. }
  22453. // Geometries
  22454. serializationObject.geometries = {};
  22455. serializationObject.geometries.boxes = [];
  22456. serializationObject.geometries.spheres = [];
  22457. serializationObject.geometries.cylinders = [];
  22458. serializationObject.geometries.toruses = [];
  22459. serializationObject.geometries.grounds = [];
  22460. serializationObject.geometries.planes = [];
  22461. serializationObject.geometries.torusKnots = [];
  22462. serializationObject.geometries.vertexData = [];
  22463. serializedGeometries = [];
  22464. var geometries = scene.getGeometries();
  22465. for (index = 0; index < geometries.length; index++) {
  22466. var geometry = geometries[index];
  22467. if (geometry.isReady()) {
  22468. serializeGeometry(geometry, serializationObject.geometries);
  22469. }
  22470. }
  22471. // Meshes
  22472. serializationObject.meshes = [];
  22473. for (index = 0; index < scene.meshes.length; index++) {
  22474. var abstractMesh = scene.meshes[index];
  22475. if (abstractMesh instanceof BABYLON.Mesh) {
  22476. var mesh = abstractMesh;
  22477. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  22478. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  22479. }
  22480. }
  22481. }
  22482. // Particles Systems
  22483. serializationObject.particleSystems = [];
  22484. for (index = 0; index < scene.particleSystems.length; index++) {
  22485. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  22486. }
  22487. // Lens flares
  22488. serializationObject.lensFlareSystems = [];
  22489. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  22490. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  22491. }
  22492. // Shadows
  22493. serializationObject.shadowGenerators = [];
  22494. for (index = 0; index < scene.lights.length; index++) {
  22495. light = scene.lights[index];
  22496. if (light.getShadowGenerator()) {
  22497. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  22498. }
  22499. }
  22500. return serializationObject;
  22501. };
  22502. return SceneSerializer;
  22503. })();
  22504. BABYLON.SceneSerializer = SceneSerializer;
  22505. })(BABYLON || (BABYLON = {}));
  22506. //# sourceMappingURL=babylon.sceneSerializer.js.map
  22507. var BABYLON;
  22508. (function (BABYLON) {
  22509. // Unique ID when we import meshes from Babylon to CSG
  22510. var currentCSGMeshId = 0;
  22511. // # class Vertex
  22512. // Represents a vertex of a polygon. Use your own vertex class instead of this
  22513. // one to provide additional features like texture coordinates and vertex
  22514. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  22515. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  22516. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  22517. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  22518. // is not used anywhere else.
  22519. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  22520. var Vertex = (function () {
  22521. function Vertex(pos, normal, uv) {
  22522. this.pos = pos;
  22523. this.normal = normal;
  22524. this.uv = uv;
  22525. }
  22526. Vertex.prototype.clone = function () {
  22527. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  22528. };
  22529. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  22530. // orientation of a polygon is flipped.
  22531. Vertex.prototype.flip = function () {
  22532. this.normal = this.normal.scale(-1);
  22533. };
  22534. // Create a new vertex between this vertex and `other` by linearly
  22535. // interpolating all properties using a parameter of `t`. Subclasses should
  22536. // override this to interpolate additional properties.
  22537. Vertex.prototype.interpolate = function (other, t) {
  22538. 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));
  22539. };
  22540. return Vertex;
  22541. })();
  22542. // # class Plane
  22543. // Represents a plane in 3D space.
  22544. var Plane = (function () {
  22545. function Plane(normal, w) {
  22546. this.normal = normal;
  22547. this.w = w;
  22548. }
  22549. Plane.FromPoints = function (a, b, c) {
  22550. var v0 = c.subtract(a);
  22551. var v1 = b.subtract(a);
  22552. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  22553. return null;
  22554. }
  22555. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  22556. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  22557. };
  22558. Plane.prototype.clone = function () {
  22559. return new Plane(this.normal.clone(), this.w);
  22560. };
  22561. Plane.prototype.flip = function () {
  22562. this.normal.scaleInPlace(-1);
  22563. this.w = -this.w;
  22564. };
  22565. // Split `polygon` by this plane if needed, then put the polygon or polygon
  22566. // fragments in the appropriate lists. Coplanar polygons go into either
  22567. // `coplanarFront` or `coplanarBack` depending on their orientation with
  22568. // respect to this plane. Polygons in front or in back of this plane go into
  22569. // either `front` or `back`.
  22570. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  22571. var COPLANAR = 0;
  22572. var FRONT = 1;
  22573. var BACK = 2;
  22574. var SPANNING = 3;
  22575. // Classify each point as well as the entire polygon into one of the above
  22576. // four classes.
  22577. var polygonType = 0;
  22578. var types = [];
  22579. for (var i = 0; i < polygon.vertices.length; i++) {
  22580. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  22581. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  22582. polygonType |= type;
  22583. types.push(type);
  22584. }
  22585. switch (polygonType) {
  22586. case COPLANAR:
  22587. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  22588. break;
  22589. case FRONT:
  22590. front.push(polygon);
  22591. break;
  22592. case BACK:
  22593. back.push(polygon);
  22594. break;
  22595. case SPANNING:
  22596. var f = [], b = [];
  22597. for (i = 0; i < polygon.vertices.length; i++) {
  22598. var j = (i + 1) % polygon.vertices.length;
  22599. var ti = types[i], tj = types[j];
  22600. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  22601. if (ti != BACK)
  22602. f.push(vi);
  22603. if (ti != FRONT)
  22604. b.push(ti != BACK ? vi.clone() : vi);
  22605. if ((ti | tj) == SPANNING) {
  22606. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  22607. var v = vi.interpolate(vj, t);
  22608. f.push(v);
  22609. b.push(v.clone());
  22610. }
  22611. }
  22612. if (f.length >= 3) {
  22613. var poly = new Polygon(f, polygon.shared);
  22614. if (poly.plane)
  22615. front.push(poly);
  22616. }
  22617. if (b.length >= 3) {
  22618. poly = new Polygon(b, polygon.shared);
  22619. if (poly.plane)
  22620. back.push(poly);
  22621. }
  22622. break;
  22623. }
  22624. };
  22625. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  22626. // point is on the plane.
  22627. Plane.EPSILON = 1e-5;
  22628. return Plane;
  22629. })();
  22630. // # class Polygon
  22631. // Represents a convex polygon. The vertices used to initialize a polygon must
  22632. // be coplanar and form a convex loop.
  22633. //
  22634. // Each convex polygon has a `shared` property, which is shared between all
  22635. // polygons that are clones of each other or were split from the same polygon.
  22636. // This can be used to define per-polygon properties (such as surface color).
  22637. var Polygon = (function () {
  22638. function Polygon(vertices, shared) {
  22639. this.vertices = vertices;
  22640. this.shared = shared;
  22641. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  22642. }
  22643. Polygon.prototype.clone = function () {
  22644. var vertices = this.vertices.map(function (v) { return v.clone(); });
  22645. return new Polygon(vertices, this.shared);
  22646. };
  22647. Polygon.prototype.flip = function () {
  22648. this.vertices.reverse().map(function (v) {
  22649. v.flip();
  22650. });
  22651. this.plane.flip();
  22652. };
  22653. return Polygon;
  22654. })();
  22655. // # class Node
  22656. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  22657. // by picking a polygon to split along. That polygon (and all other coplanar
  22658. // polygons) are added directly to that node and the other polygons are added to
  22659. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  22660. // no distinction between internal and leaf nodes.
  22661. var Node = (function () {
  22662. function Node(polygons) {
  22663. this.plane = null;
  22664. this.front = null;
  22665. this.back = null;
  22666. this.polygons = [];
  22667. if (polygons) {
  22668. this.build(polygons);
  22669. }
  22670. }
  22671. Node.prototype.clone = function () {
  22672. var node = new Node();
  22673. node.plane = this.plane && this.plane.clone();
  22674. node.front = this.front && this.front.clone();
  22675. node.back = this.back && this.back.clone();
  22676. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  22677. return node;
  22678. };
  22679. // Convert solid space to empty space and empty space to solid space.
  22680. Node.prototype.invert = function () {
  22681. for (var i = 0; i < this.polygons.length; i++) {
  22682. this.polygons[i].flip();
  22683. }
  22684. if (this.plane) {
  22685. this.plane.flip();
  22686. }
  22687. if (this.front) {
  22688. this.front.invert();
  22689. }
  22690. if (this.back) {
  22691. this.back.invert();
  22692. }
  22693. var temp = this.front;
  22694. this.front = this.back;
  22695. this.back = temp;
  22696. };
  22697. // Recursively remove all polygons in `polygons` that are inside this BSP
  22698. // tree.
  22699. Node.prototype.clipPolygons = function (polygons) {
  22700. if (!this.plane)
  22701. return polygons.slice();
  22702. var front = [], back = [];
  22703. for (var i = 0; i < polygons.length; i++) {
  22704. this.plane.splitPolygon(polygons[i], front, back, front, back);
  22705. }
  22706. if (this.front) {
  22707. front = this.front.clipPolygons(front);
  22708. }
  22709. if (this.back) {
  22710. back = this.back.clipPolygons(back);
  22711. }
  22712. else {
  22713. back = [];
  22714. }
  22715. return front.concat(back);
  22716. };
  22717. // Remove all polygons in this BSP tree that are inside the other BSP tree
  22718. // `bsp`.
  22719. Node.prototype.clipTo = function (bsp) {
  22720. this.polygons = bsp.clipPolygons(this.polygons);
  22721. if (this.front)
  22722. this.front.clipTo(bsp);
  22723. if (this.back)
  22724. this.back.clipTo(bsp);
  22725. };
  22726. // Return a list of all polygons in this BSP tree.
  22727. Node.prototype.allPolygons = function () {
  22728. var polygons = this.polygons.slice();
  22729. if (this.front)
  22730. polygons = polygons.concat(this.front.allPolygons());
  22731. if (this.back)
  22732. polygons = polygons.concat(this.back.allPolygons());
  22733. return polygons;
  22734. };
  22735. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  22736. // new polygons are filtered down to the bottom of the tree and become new
  22737. // nodes there. Each set of polygons is partitioned using the first polygon
  22738. // (no heuristic is used to pick a good split).
  22739. Node.prototype.build = function (polygons) {
  22740. if (!polygons.length)
  22741. return;
  22742. if (!this.plane)
  22743. this.plane = polygons[0].plane.clone();
  22744. var front = [], back = [];
  22745. for (var i = 0; i < polygons.length; i++) {
  22746. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  22747. }
  22748. if (front.length) {
  22749. if (!this.front)
  22750. this.front = new Node();
  22751. this.front.build(front);
  22752. }
  22753. if (back.length) {
  22754. if (!this.back)
  22755. this.back = new Node();
  22756. this.back.build(back);
  22757. }
  22758. };
  22759. return Node;
  22760. })();
  22761. var CSG = (function () {
  22762. function CSG() {
  22763. this.polygons = new Array();
  22764. }
  22765. // Convert BABYLON.Mesh to BABYLON.CSG
  22766. CSG.FromMesh = function (mesh) {
  22767. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  22768. if (mesh instanceof BABYLON.Mesh) {
  22769. mesh.computeWorldMatrix(true);
  22770. var matrix = mesh.getWorldMatrix();
  22771. var meshPosition = mesh.position.clone();
  22772. var meshRotation = mesh.rotation.clone();
  22773. var meshScaling = mesh.scaling.clone();
  22774. }
  22775. else {
  22776. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  22777. }
  22778. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22779. var subMeshes = mesh.subMeshes;
  22780. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  22781. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  22782. vertices = [];
  22783. for (var j = 0; j < 3; j++) {
  22784. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  22785. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  22786. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  22787. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  22788. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  22789. vertex = new Vertex(position, normal, uv);
  22790. vertices.push(vertex);
  22791. }
  22792. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  22793. // To handle the case of degenerated triangle
  22794. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  22795. if (polygon.plane)
  22796. polygons.push(polygon);
  22797. }
  22798. }
  22799. var csg = CSG.FromPolygons(polygons);
  22800. csg.matrix = matrix;
  22801. csg.position = meshPosition;
  22802. csg.rotation = meshRotation;
  22803. csg.scaling = meshScaling;
  22804. currentCSGMeshId++;
  22805. return csg;
  22806. };
  22807. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  22808. CSG.FromPolygons = function (polygons) {
  22809. var csg = new BABYLON.CSG();
  22810. csg.polygons = polygons;
  22811. return csg;
  22812. };
  22813. CSG.prototype.clone = function () {
  22814. var csg = new BABYLON.CSG();
  22815. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  22816. csg.copyTransformAttributes(this);
  22817. return csg;
  22818. };
  22819. CSG.prototype.toPolygons = function () {
  22820. return this.polygons;
  22821. };
  22822. CSG.prototype.union = function (csg) {
  22823. var a = new Node(this.clone().polygons);
  22824. var b = new Node(csg.clone().polygons);
  22825. a.clipTo(b);
  22826. b.clipTo(a);
  22827. b.invert();
  22828. b.clipTo(a);
  22829. b.invert();
  22830. a.build(b.allPolygons());
  22831. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  22832. };
  22833. CSG.prototype.unionInPlace = function (csg) {
  22834. var a = new Node(this.polygons);
  22835. var b = new Node(csg.polygons);
  22836. a.clipTo(b);
  22837. b.clipTo(a);
  22838. b.invert();
  22839. b.clipTo(a);
  22840. b.invert();
  22841. a.build(b.allPolygons());
  22842. this.polygons = a.allPolygons();
  22843. };
  22844. CSG.prototype.subtract = function (csg) {
  22845. var a = new Node(this.clone().polygons);
  22846. var b = new Node(csg.clone().polygons);
  22847. a.invert();
  22848. a.clipTo(b);
  22849. b.clipTo(a);
  22850. b.invert();
  22851. b.clipTo(a);
  22852. b.invert();
  22853. a.build(b.allPolygons());
  22854. a.invert();
  22855. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  22856. };
  22857. CSG.prototype.subtractInPlace = function (csg) {
  22858. var a = new Node(this.polygons);
  22859. var b = new Node(csg.polygons);
  22860. a.invert();
  22861. a.clipTo(b);
  22862. b.clipTo(a);
  22863. b.invert();
  22864. b.clipTo(a);
  22865. b.invert();
  22866. a.build(b.allPolygons());
  22867. a.invert();
  22868. this.polygons = a.allPolygons();
  22869. };
  22870. CSG.prototype.intersect = function (csg) {
  22871. var a = new Node(this.clone().polygons);
  22872. var b = new Node(csg.clone().polygons);
  22873. a.invert();
  22874. b.clipTo(a);
  22875. b.invert();
  22876. a.clipTo(b);
  22877. b.clipTo(a);
  22878. a.build(b.allPolygons());
  22879. a.invert();
  22880. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  22881. };
  22882. CSG.prototype.intersectInPlace = function (csg) {
  22883. var a = new Node(this.polygons);
  22884. var b = new Node(csg.polygons);
  22885. a.invert();
  22886. b.clipTo(a);
  22887. b.invert();
  22888. a.clipTo(b);
  22889. b.clipTo(a);
  22890. a.build(b.allPolygons());
  22891. a.invert();
  22892. this.polygons = a.allPolygons();
  22893. };
  22894. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  22895. // not modified.
  22896. CSG.prototype.inverse = function () {
  22897. var csg = this.clone();
  22898. csg.inverseInPlace();
  22899. return csg;
  22900. };
  22901. CSG.prototype.inverseInPlace = function () {
  22902. this.polygons.map(function (p) {
  22903. p.flip();
  22904. });
  22905. };
  22906. // This is used to keep meshes transformations so they can be restored
  22907. // when we build back a Babylon Mesh
  22908. // NB : All CSG operations are performed in world coordinates
  22909. CSG.prototype.copyTransformAttributes = function (csg) {
  22910. this.matrix = csg.matrix;
  22911. this.position = csg.position;
  22912. this.rotation = csg.rotation;
  22913. this.scaling = csg.scaling;
  22914. return this;
  22915. };
  22916. // Build Raw mesh from CSG
  22917. // Coordinates here are in world space
  22918. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  22919. var matrix = this.matrix.clone();
  22920. matrix.invert();
  22921. 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;
  22922. if (keepSubMeshes) {
  22923. // Sort Polygons, since subMeshes are indices range
  22924. polygons.sort(function (a, b) {
  22925. if (a.shared.meshId === b.shared.meshId) {
  22926. return a.shared.subMeshId - b.shared.subMeshId;
  22927. }
  22928. else {
  22929. return a.shared.meshId - b.shared.meshId;
  22930. }
  22931. });
  22932. }
  22933. for (var i = 0, il = polygons.length; i < il; i++) {
  22934. polygon = polygons[i];
  22935. // Building SubMeshes
  22936. if (!subMesh_dict[polygon.shared.meshId]) {
  22937. subMesh_dict[polygon.shared.meshId] = {};
  22938. }
  22939. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  22940. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  22941. indexStart: +Infinity,
  22942. indexEnd: -Infinity,
  22943. materialIndex: polygon.shared.materialIndex
  22944. };
  22945. }
  22946. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  22947. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  22948. polygonIndices[0] = 0;
  22949. polygonIndices[1] = j - 1;
  22950. polygonIndices[2] = j;
  22951. for (var k = 0; k < 3; k++) {
  22952. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  22953. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  22954. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  22955. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  22956. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  22957. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  22958. // Check if 2 points can be merged
  22959. 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)) {
  22960. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  22961. uvs.push(uv.x, uv.y);
  22962. normals.push(normal.x, normal.y, normal.z);
  22963. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  22964. }
  22965. indices.push(vertex_idx);
  22966. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  22967. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  22968. currentIndex++;
  22969. }
  22970. }
  22971. }
  22972. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  22973. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22974. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  22975. mesh.setIndices(indices);
  22976. if (keepSubMeshes) {
  22977. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  22978. var materialIndexOffset = 0, materialMaxIndex;
  22979. mesh.subMeshes.length = 0;
  22980. for (var m in subMesh_dict) {
  22981. materialMaxIndex = -1;
  22982. for (var sm in subMesh_dict[m]) {
  22983. subMesh_obj = subMesh_dict[m][sm];
  22984. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  22985. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  22986. }
  22987. materialIndexOffset += ++materialMaxIndex;
  22988. }
  22989. }
  22990. return mesh;
  22991. };
  22992. // Build Mesh from CSG taking material and transforms into account
  22993. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  22994. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  22995. mesh.material = material;
  22996. mesh.position.copyFrom(this.position);
  22997. mesh.rotation.copyFrom(this.rotation);
  22998. mesh.scaling.copyFrom(this.scaling);
  22999. mesh.computeWorldMatrix(true);
  23000. return mesh;
  23001. };
  23002. return CSG;
  23003. })();
  23004. BABYLON.CSG = CSG;
  23005. })(BABYLON || (BABYLON = {}));
  23006. //# sourceMappingURL=babylon.csg.js.map
  23007. var __extends = this.__extends || function (d, b) {
  23008. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23009. function __() { this.constructor = d; }
  23010. __.prototype = b.prototype;
  23011. d.prototype = new __();
  23012. };
  23013. var BABYLON;
  23014. (function (BABYLON) {
  23015. var OculusDistortionCorrectionPostProcess = (function (_super) {
  23016. __extends(OculusDistortionCorrectionPostProcess, _super);
  23017. //ANY
  23018. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  23019. var _this = this;
  23020. _super.call(this, name, "oculusDistortionCorrection", [
  23021. 'LensCenter',
  23022. 'Scale',
  23023. 'ScaleIn',
  23024. 'HmdWarpParam'
  23025. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  23026. this._isRightEye = isRightEye;
  23027. this._distortionFactors = cameraSettings.DistortionK;
  23028. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  23029. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  23030. this.onSizeChanged = function () {
  23031. _this.aspectRatio = _this.width * .5 / _this.height;
  23032. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  23033. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  23034. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  23035. };
  23036. this.onApply = function (effect) {
  23037. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  23038. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  23039. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  23040. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  23041. };
  23042. }
  23043. return OculusDistortionCorrectionPostProcess;
  23044. })(BABYLON.PostProcess);
  23045. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  23046. })(BABYLON || (BABYLON = {}));
  23047. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map
  23048. // Mainly based on these 2 articles :
  23049. // 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
  23050. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  23051. var BABYLON;
  23052. (function (BABYLON) {
  23053. (function (JoystickAxis) {
  23054. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  23055. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  23056. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  23057. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  23058. var JoystickAxis = BABYLON.JoystickAxis;
  23059. var VirtualJoystick = (function () {
  23060. function VirtualJoystick(leftJoystick) {
  23061. var _this = this;
  23062. if (leftJoystick) {
  23063. this._leftJoystick = true;
  23064. }
  23065. else {
  23066. this._leftJoystick = false;
  23067. }
  23068. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  23069. VirtualJoystick._globalJoystickIndex++;
  23070. // By default left & right arrow keys are moving the X
  23071. // and up & down keys are moving the Y
  23072. this._axisTargetedByLeftAndRight = 0 /* X */;
  23073. this._axisTargetedByUpAndDown = 1 /* Y */;
  23074. this.reverseLeftRight = false;
  23075. this.reverseUpDown = false;
  23076. // collections of pointers
  23077. this._touches = new BABYLON.SmartCollection();
  23078. this.deltaPosition = BABYLON.Vector3.Zero();
  23079. this._joystickSensibility = 25;
  23080. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  23081. this._rotationSpeed = 25;
  23082. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  23083. this._rotateOnAxisRelativeToMesh = false;
  23084. // injecting a canvas element on top of the canvas 3D game
  23085. if (!VirtualJoystick.vjCanvas) {
  23086. window.addEventListener("resize", function () {
  23087. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  23088. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  23089. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  23090. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  23091. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  23092. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  23093. }, false);
  23094. VirtualJoystick.vjCanvas = document.createElement("canvas");
  23095. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  23096. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  23097. VirtualJoystick.vjCanvas.width = window.innerWidth;
  23098. VirtualJoystick.vjCanvas.height = window.innerHeight;
  23099. VirtualJoystick.vjCanvas.style.width = "100%";
  23100. VirtualJoystick.vjCanvas.style.height = "100%";
  23101. VirtualJoystick.vjCanvas.style.position = "absolute";
  23102. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  23103. VirtualJoystick.vjCanvas.style.top = "0px";
  23104. VirtualJoystick.vjCanvas.style.left = "0px";
  23105. VirtualJoystick.vjCanvas.style.zIndex = "5";
  23106. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  23107. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  23108. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  23109. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  23110. document.body.appendChild(VirtualJoystick.vjCanvas);
  23111. }
  23112. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  23113. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  23114. this.pressed = false;
  23115. // default joystick color
  23116. this._joystickColor = "cyan";
  23117. this._joystickPointerID = -1;
  23118. // current joystick position
  23119. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  23120. // origin joystick position
  23121. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  23122. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  23123. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  23124. _this._onPointerDown(evt);
  23125. }, false);
  23126. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  23127. _this._onPointerMove(evt);
  23128. }, false);
  23129. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  23130. _this._onPointerUp(evt);
  23131. }, false);
  23132. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  23133. _this._onPointerUp(evt);
  23134. }, false);
  23135. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  23136. evt.preventDefault(); // Disables system menu
  23137. }, false);
  23138. requestAnimationFrame(function () {
  23139. _this._drawVirtualJoystick();
  23140. });
  23141. }
  23142. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  23143. this._joystickSensibility = newJoystickSensibility;
  23144. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  23145. };
  23146. VirtualJoystick.prototype._onPointerDown = function (e) {
  23147. var positionOnScreenCondition;
  23148. e.preventDefault();
  23149. if (this._leftJoystick === true) {
  23150. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  23151. }
  23152. else {
  23153. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  23154. }
  23155. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  23156. // First contact will be dedicated to the virtual joystick
  23157. this._joystickPointerID = e.pointerId;
  23158. this._joystickPointerStartPos.x = e.clientX;
  23159. this._joystickPointerStartPos.y = e.clientY;
  23160. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  23161. this._deltaJoystickVector.x = 0;
  23162. this._deltaJoystickVector.y = 0;
  23163. this.pressed = true;
  23164. this._touches.add(e.pointerId.toString(), e);
  23165. }
  23166. else {
  23167. // You can only trigger the action buttons with a joystick declared
  23168. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  23169. this._action();
  23170. this._touches.add(e.pointerId.toString(), e);
  23171. }
  23172. }
  23173. };
  23174. VirtualJoystick.prototype._onPointerMove = function (e) {
  23175. // If the current pointer is the one associated to the joystick (first touch contact)
  23176. if (this._joystickPointerID == e.pointerId) {
  23177. this._joystickPointerPos.x = e.clientX;
  23178. this._joystickPointerPos.y = e.clientY;
  23179. this._deltaJoystickVector = this._joystickPointerPos.clone();
  23180. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  23181. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  23182. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  23183. switch (this._axisTargetedByLeftAndRight) {
  23184. case 0 /* X */:
  23185. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  23186. break;
  23187. case 1 /* Y */:
  23188. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  23189. break;
  23190. case 2 /* Z */:
  23191. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  23192. break;
  23193. }
  23194. var directionUpDown = this.reverseUpDown ? 1 : -1;
  23195. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  23196. switch (this._axisTargetedByUpAndDown) {
  23197. case 0 /* X */:
  23198. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  23199. break;
  23200. case 1 /* Y */:
  23201. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  23202. break;
  23203. case 2 /* Z */:
  23204. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  23205. break;
  23206. }
  23207. }
  23208. else {
  23209. if (this._touches.item(e.pointerId.toString())) {
  23210. this._touches.item(e.pointerId.toString()).x = e.clientX;
  23211. this._touches.item(e.pointerId.toString()).y = e.clientY;
  23212. }
  23213. }
  23214. };
  23215. VirtualJoystick.prototype._onPointerUp = function (e) {
  23216. this._clearCanvas();
  23217. if (this._joystickPointerID == e.pointerId) {
  23218. this._joystickPointerID = -1;
  23219. this.pressed = false;
  23220. }
  23221. this._deltaJoystickVector.x = 0;
  23222. this._deltaJoystickVector.y = 0;
  23223. this._touches.remove(e.pointerId.toString());
  23224. };
  23225. /**
  23226. * Change the color of the virtual joystick
  23227. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  23228. */
  23229. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  23230. this._joystickColor = newColor;
  23231. };
  23232. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  23233. this._action = action;
  23234. };
  23235. // Define which axis you'd like to control for left & right
  23236. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  23237. switch (axis) {
  23238. case 0 /* X */:
  23239. case 1 /* Y */:
  23240. case 2 /* Z */:
  23241. this._axisTargetedByLeftAndRight = axis;
  23242. break;
  23243. default:
  23244. this._axisTargetedByLeftAndRight = 0 /* X */;
  23245. break;
  23246. }
  23247. };
  23248. // Define which axis you'd like to control for up & down
  23249. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  23250. switch (axis) {
  23251. case 0 /* X */:
  23252. case 1 /* Y */:
  23253. case 2 /* Z */:
  23254. this._axisTargetedByUpAndDown = axis;
  23255. break;
  23256. default:
  23257. this._axisTargetedByUpAndDown = 1 /* Y */;
  23258. break;
  23259. }
  23260. };
  23261. VirtualJoystick.prototype._clearCanvas = function () {
  23262. if (this._leftJoystick) {
  23263. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  23264. }
  23265. else {
  23266. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  23267. }
  23268. };
  23269. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  23270. var _this = this;
  23271. if (this.pressed) {
  23272. this._clearCanvas();
  23273. this._touches.forEach(function (touch) {
  23274. if (touch.pointerId === _this._joystickPointerID) {
  23275. VirtualJoystick.vjCanvasContext.beginPath();
  23276. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  23277. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  23278. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  23279. VirtualJoystick.vjCanvasContext.stroke();
  23280. VirtualJoystick.vjCanvasContext.beginPath();
  23281. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  23282. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  23283. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  23284. VirtualJoystick.vjCanvasContext.stroke();
  23285. VirtualJoystick.vjCanvasContext.beginPath();
  23286. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  23287. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  23288. VirtualJoystick.vjCanvasContext.stroke();
  23289. }
  23290. else {
  23291. VirtualJoystick.vjCanvasContext.beginPath();
  23292. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  23293. VirtualJoystick.vjCanvasContext.beginPath();
  23294. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  23295. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  23296. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  23297. VirtualJoystick.vjCanvasContext.stroke();
  23298. }
  23299. ;
  23300. });
  23301. }
  23302. requestAnimationFrame(function () {
  23303. _this._drawVirtualJoystick();
  23304. });
  23305. };
  23306. VirtualJoystick.prototype.releaseCanvas = function () {
  23307. if (VirtualJoystick.vjCanvas) {
  23308. document.body.removeChild(VirtualJoystick.vjCanvas);
  23309. VirtualJoystick.vjCanvas = null;
  23310. }
  23311. };
  23312. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  23313. VirtualJoystick._globalJoystickIndex = 0;
  23314. return VirtualJoystick;
  23315. })();
  23316. BABYLON.VirtualJoystick = VirtualJoystick;
  23317. })(BABYLON || (BABYLON = {}));
  23318. //# sourceMappingURL=babylon.virtualJoystick.js.map
  23319. var __extends = this.__extends || function (d, b) {
  23320. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23321. function __() { this.constructor = d; }
  23322. __.prototype = b.prototype;
  23323. d.prototype = new __();
  23324. };
  23325. var BABYLON;
  23326. (function (BABYLON) {
  23327. var OculusRiftDevKit2013_Metric = {
  23328. HResolution: 1280,
  23329. VResolution: 800,
  23330. HScreenSize: 0.149759993,
  23331. VScreenSize: 0.0935999975,
  23332. VScreenCenter: 0.0467999987,
  23333. EyeToScreenDistance: 0.0410000011,
  23334. LensSeparationDistance: 0.0635000020,
  23335. InterpupillaryDistance: 0.0640000030,
  23336. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  23337. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  23338. PostProcessScaleFactor: 1.714605507808412,
  23339. LensCenterOffset: 0.151976421
  23340. };
  23341. var _OculusInnerCamera = (function (_super) {
  23342. __extends(_OculusInnerCamera, _super);
  23343. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  23344. _super.call(this, name, position, scene);
  23345. this._workMatrix = new BABYLON.Matrix();
  23346. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  23347. // Constants
  23348. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  23349. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  23350. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  23351. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  23352. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  23353. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  23354. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  23355. // Postprocess
  23356. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  23357. }
  23358. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  23359. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  23360. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  23361. return this._projectionMatrix;
  23362. };
  23363. _OculusInnerCamera.prototype._getViewMatrix = function () {
  23364. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  23365. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  23366. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  23367. // Computing target and final matrix
  23368. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  23369. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  23370. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  23371. return this._viewMatrix;
  23372. };
  23373. return _OculusInnerCamera;
  23374. })(BABYLON.FreeCamera);
  23375. var OculusCamera = (function (_super) {
  23376. __extends(OculusCamera, _super);
  23377. function OculusCamera(name, position, scene) {
  23378. _super.call(this, name, position, scene);
  23379. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  23380. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  23381. this.subCameras.push(this._leftCamera);
  23382. this.subCameras.push(this._rightCamera);
  23383. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  23384. }
  23385. OculusCamera.prototype._update = function () {
  23386. this._leftCamera.position.copyFrom(this.position);
  23387. this._rightCamera.position.copyFrom(this.position);
  23388. this._updateCamera(this._leftCamera);
  23389. this._updateCamera(this._rightCamera);
  23390. _super.prototype._update.call(this);
  23391. };
  23392. OculusCamera.prototype._updateCamera = function (camera) {
  23393. camera.minZ = this.minZ;
  23394. camera.maxZ = this.maxZ;
  23395. camera.rotation.x = this.rotation.x;
  23396. camera.rotation.y = this.rotation.y;
  23397. camera.rotation.z = this.rotation.z;
  23398. };
  23399. // Oculus events
  23400. OculusCamera.prototype._onOrientationEvent = function (evt) {
  23401. var yaw = evt.alpha / 180 * Math.PI;
  23402. var pitch = evt.beta / 180 * Math.PI;
  23403. var roll = evt.gamma / 180 * Math.PI;
  23404. if (!this._offsetOrientation) {
  23405. this._offsetOrientation = {
  23406. yaw: yaw,
  23407. pitch: pitch,
  23408. roll: roll
  23409. };
  23410. return;
  23411. }
  23412. else {
  23413. this.rotation.y += yaw - this._offsetOrientation.yaw;
  23414. this.rotation.x += pitch - this._offsetOrientation.pitch;
  23415. this.rotation.z += this._offsetOrientation.roll - roll;
  23416. this._offsetOrientation.yaw = yaw;
  23417. this._offsetOrientation.pitch = pitch;
  23418. this._offsetOrientation.roll = roll;
  23419. }
  23420. };
  23421. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  23422. _super.prototype.attachControl.call(this, element, noPreventDefault);
  23423. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  23424. };
  23425. OculusCamera.prototype.detachControl = function (element) {
  23426. _super.prototype.detachControl.call(this, element);
  23427. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  23428. };
  23429. return OculusCamera;
  23430. })(BABYLON.FreeCamera);
  23431. BABYLON.OculusCamera = OculusCamera;
  23432. })(BABYLON || (BABYLON = {}));
  23433. //# sourceMappingURL=babylon.oculusCamera.js.map
  23434. var __extends = this.__extends || function (d, b) {
  23435. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23436. function __() { this.constructor = d; }
  23437. __.prototype = b.prototype;
  23438. d.prototype = new __();
  23439. };
  23440. var BABYLON;
  23441. (function (BABYLON) {
  23442. var OculusRiftDevKit2013_Metric = {
  23443. HResolution: 1280,
  23444. VResolution: 800,
  23445. HScreenSize: 0.149759993,
  23446. VScreenSize: 0.0935999975,
  23447. VScreenCenter: 0.0467999987,
  23448. EyeToScreenDistance: 0.0410000011,
  23449. LensSeparationDistance: 0.0635000020,
  23450. InterpupillaryDistance: 0.0640000030,
  23451. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  23452. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  23453. PostProcessScaleFactor: 1.714605507808412,
  23454. LensCenterOffset: 0.151976421
  23455. };
  23456. var _OculusInnerGamepadCamera = (function (_super) {
  23457. __extends(_OculusInnerGamepadCamera, _super);
  23458. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  23459. _super.call(this, name, position, scene);
  23460. this._workMatrix = new BABYLON.Matrix();
  23461. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  23462. // Constants
  23463. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  23464. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  23465. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  23466. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  23467. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  23468. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  23469. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  23470. // Postprocess
  23471. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  23472. }
  23473. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  23474. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  23475. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  23476. return this._projectionMatrix;
  23477. };
  23478. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  23479. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  23480. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  23481. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  23482. // Computing target and final matrix
  23483. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  23484. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  23485. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  23486. return this._viewMatrix;
  23487. };
  23488. return _OculusInnerGamepadCamera;
  23489. })(BABYLON.FreeCamera);
  23490. var OculusGamepadCamera = (function (_super) {
  23491. __extends(OculusGamepadCamera, _super);
  23492. function OculusGamepadCamera(name, position, scene) {
  23493. var _this = this;
  23494. _super.call(this, name, position, scene);
  23495. this.angularSensibility = 200;
  23496. this.moveSensibility = 75;
  23497. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  23498. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  23499. this.subCameras.push(this._leftCamera);
  23500. this.subCameras.push(this._rightCamera);
  23501. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  23502. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  23503. _this._onNewGameConnected(gamepad);
  23504. });
  23505. }
  23506. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  23507. // Only the first gamepad can control the camera
  23508. if (gamepad.index === 0) {
  23509. this._gamepad = gamepad;
  23510. }
  23511. };
  23512. OculusGamepadCamera.prototype._update = function () {
  23513. this._leftCamera.position.copyFrom(this.position);
  23514. this._rightCamera.position.copyFrom(this.position);
  23515. this._updateCamera(this._leftCamera);
  23516. this._updateCamera(this._rightCamera);
  23517. _super.prototype._update.call(this);
  23518. };
  23519. OculusGamepadCamera.prototype._checkInputs = function () {
  23520. if (!this._gamepad) {
  23521. return;
  23522. }
  23523. var LSValues = this._gamepad.leftStick;
  23524. var normalizedLX = LSValues.x / this.moveSensibility;
  23525. var normalizedLY = LSValues.y / this.moveSensibility;
  23526. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  23527. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  23528. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23529. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  23530. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23531. };
  23532. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  23533. camera.minZ = this.minZ;
  23534. camera.maxZ = this.maxZ;
  23535. camera.rotation.x = this.rotation.x;
  23536. camera.rotation.y = this.rotation.y;
  23537. camera.rotation.z = this.rotation.z;
  23538. };
  23539. // Oculus events
  23540. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  23541. var yaw = evt.alpha / 180 * Math.PI;
  23542. var pitch = evt.beta / 180 * Math.PI;
  23543. var roll = evt.gamma / 180 * Math.PI;
  23544. if (!this._offsetOrientation) {
  23545. this._offsetOrientation = {
  23546. yaw: yaw,
  23547. pitch: pitch,
  23548. roll: roll
  23549. };
  23550. return;
  23551. }
  23552. else {
  23553. this.rotation.y += yaw - this._offsetOrientation.yaw;
  23554. this.rotation.x += pitch - this._offsetOrientation.pitch;
  23555. this.rotation.z += this._offsetOrientation.roll - roll;
  23556. this._offsetOrientation.yaw = yaw;
  23557. this._offsetOrientation.pitch = pitch;
  23558. this._offsetOrientation.roll = roll;
  23559. }
  23560. };
  23561. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  23562. _super.prototype.attachControl.call(this, element, noPreventDefault);
  23563. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  23564. };
  23565. OculusGamepadCamera.prototype.detachControl = function (element) {
  23566. _super.prototype.detachControl.call(this, element);
  23567. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  23568. };
  23569. OculusGamepadCamera.prototype.dispose = function () {
  23570. this._gamepads.dispose();
  23571. _super.prototype.dispose.call(this);
  23572. };
  23573. return OculusGamepadCamera;
  23574. })(BABYLON.FreeCamera);
  23575. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  23576. })(BABYLON || (BABYLON = {}));
  23577. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  23578. var __extends = this.__extends || function (d, b) {
  23579. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23580. function __() { this.constructor = d; }
  23581. __.prototype = b.prototype;
  23582. d.prototype = new __();
  23583. };
  23584. var BABYLON;
  23585. (function (BABYLON) {
  23586. // We're mainly based on the logic defined into the FreeCamera code
  23587. var VirtualJoysticksCamera = (function (_super) {
  23588. __extends(VirtualJoysticksCamera, _super);
  23589. function VirtualJoysticksCamera(name, position, scene) {
  23590. _super.call(this, name, position, scene);
  23591. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  23592. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  23593. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  23594. this._leftjoystick.setJoystickSensibility(0.15);
  23595. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  23596. this._rightjoystick.setAxisForUpDown(0 /* X */);
  23597. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  23598. this._rightjoystick.reverseUpDown = true;
  23599. this._rightjoystick.setJoystickSensibility(0.05);
  23600. this._rightjoystick.setJoystickColor("yellow");
  23601. }
  23602. VirtualJoysticksCamera.prototype._checkInputs = function () {
  23603. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23604. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  23605. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23606. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  23607. if (!this._leftjoystick.pressed) {
  23608. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  23609. }
  23610. if (!this._rightjoystick.pressed) {
  23611. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  23612. }
  23613. };
  23614. VirtualJoysticksCamera.prototype.dispose = function () {
  23615. this._leftjoystick.releaseCanvas();
  23616. _super.prototype.dispose.call(this);
  23617. };
  23618. return VirtualJoysticksCamera;
  23619. })(BABYLON.FreeCamera);
  23620. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  23621. })(BABYLON || (BABYLON = {}));
  23622. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  23623. var __extends = this.__extends || function (d, b) {
  23624. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23625. function __() { this.constructor = d; }
  23626. __.prototype = b.prototype;
  23627. d.prototype = new __();
  23628. };
  23629. var BABYLON;
  23630. (function (BABYLON) {
  23631. var ShaderMaterial = (function (_super) {
  23632. __extends(ShaderMaterial, _super);
  23633. function ShaderMaterial(name, scene, shaderPath, options) {
  23634. _super.call(this, name, scene);
  23635. this._textures = new Array();
  23636. this._floats = new Array();
  23637. this._floatsArrays = {};
  23638. this._colors3 = new Array();
  23639. this._colors4 = new Array();
  23640. this._vectors2 = new Array();
  23641. this._vectors3 = new Array();
  23642. this._matrices = new Array();
  23643. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  23644. this._shaderPath = shaderPath;
  23645. options.needAlphaBlending = options.needAlphaBlending || false;
  23646. options.needAlphaTesting = options.needAlphaTesting || false;
  23647. options.attributes = options.attributes || ["position", "normal", "uv"];
  23648. options.uniforms = options.uniforms || ["worldViewProjection"];
  23649. options.samplers = options.samplers || [];
  23650. this._options = options;
  23651. }
  23652. ShaderMaterial.prototype.needAlphaBlending = function () {
  23653. return this._options.needAlphaBlending;
  23654. };
  23655. ShaderMaterial.prototype.needAlphaTesting = function () {
  23656. return this._options.needAlphaTesting;
  23657. };
  23658. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  23659. if (this._options.uniforms.indexOf(uniformName) === -1) {
  23660. this._options.uniforms.push(uniformName);
  23661. }
  23662. };
  23663. ShaderMaterial.prototype.setTexture = function (name, texture) {
  23664. if (this._options.samplers.indexOf(name) === -1) {
  23665. this._options.samplers.push(name);
  23666. }
  23667. this._textures[name] = texture;
  23668. return this;
  23669. };
  23670. ShaderMaterial.prototype.setFloat = function (name, value) {
  23671. this._checkUniform(name);
  23672. this._floats[name] = value;
  23673. return this;
  23674. };
  23675. ShaderMaterial.prototype.setFloats = function (name, value) {
  23676. this._checkUniform(name);
  23677. this._floatsArrays[name] = value;
  23678. return this;
  23679. };
  23680. ShaderMaterial.prototype.setColor3 = function (name, value) {
  23681. this._checkUniform(name);
  23682. this._colors3[name] = value;
  23683. return this;
  23684. };
  23685. ShaderMaterial.prototype.setColor4 = function (name, value) {
  23686. this._checkUniform(name);
  23687. this._colors4[name] = value;
  23688. return this;
  23689. };
  23690. ShaderMaterial.prototype.setVector2 = function (name, value) {
  23691. this._checkUniform(name);
  23692. this._vectors2[name] = value;
  23693. return this;
  23694. };
  23695. ShaderMaterial.prototype.setVector3 = function (name, value) {
  23696. this._checkUniform(name);
  23697. this._vectors3[name] = value;
  23698. return this;
  23699. };
  23700. ShaderMaterial.prototype.setMatrix = function (name, value) {
  23701. this._checkUniform(name);
  23702. this._matrices[name] = value;
  23703. return this;
  23704. };
  23705. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  23706. var scene = this.getScene();
  23707. var engine = scene.getEngine();
  23708. if (!this.checkReadyOnEveryCall) {
  23709. if (this._renderId === scene.getRenderId()) {
  23710. return true;
  23711. }
  23712. }
  23713. // Instances
  23714. var defines = [];
  23715. var fallbacks = new BABYLON.EffectFallbacks();
  23716. if (useInstances) {
  23717. defines.push("#define INSTANCES");
  23718. }
  23719. // Bones
  23720. if (mesh && mesh.useBones) {
  23721. defines.push("#define BONES");
  23722. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  23723. defines.push("#define BONES4");
  23724. fallbacks.addFallback(0, "BONES4");
  23725. }
  23726. // Alpha test
  23727. if (engine.getAlphaTesting()) {
  23728. defines.push("#define ALPHATEST");
  23729. }
  23730. var previousEffect = this._effect;
  23731. var join = defines.join("\n");
  23732. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  23733. if (!this._effect.isReady()) {
  23734. return false;
  23735. }
  23736. if (previousEffect !== this._effect) {
  23737. scene.resetCachedMaterial();
  23738. }
  23739. this._renderId = scene.getRenderId();
  23740. return true;
  23741. };
  23742. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23743. var scene = this.getScene();
  23744. if (this._options.uniforms.indexOf("world") !== -1) {
  23745. this._effect.setMatrix("world", world);
  23746. }
  23747. if (this._options.uniforms.indexOf("worldView") !== -1) {
  23748. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  23749. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  23750. }
  23751. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  23752. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  23753. }
  23754. };
  23755. ShaderMaterial.prototype.bind = function (world, mesh) {
  23756. // Std values
  23757. this.bindOnlyWorldMatrix(world);
  23758. if (this.getScene().getCachedMaterial() !== this) {
  23759. if (this._options.uniforms.indexOf("view") !== -1) {
  23760. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  23761. }
  23762. if (this._options.uniforms.indexOf("projection") !== -1) {
  23763. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  23764. }
  23765. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  23766. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  23767. }
  23768. // Bones
  23769. if (mesh && mesh.useBones) {
  23770. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  23771. }
  23772. for (var name in this._textures) {
  23773. this._effect.setTexture(name, this._textures[name]);
  23774. }
  23775. for (name in this._floats) {
  23776. this._effect.setFloat(name, this._floats[name]);
  23777. }
  23778. for (name in this._floatsArrays) {
  23779. this._effect.setArray(name, this._floatsArrays[name]);
  23780. }
  23781. for (name in this._colors3) {
  23782. this._effect.setColor3(name, this._colors3[name]);
  23783. }
  23784. for (name in this._colors4) {
  23785. var color = this._colors4[name];
  23786. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23787. }
  23788. for (name in this._vectors2) {
  23789. this._effect.setVector2(name, this._vectors2[name]);
  23790. }
  23791. for (name in this._vectors3) {
  23792. this._effect.setVector3(name, this._vectors3[name]);
  23793. }
  23794. for (name in this._matrices) {
  23795. this._effect.setMatrix(name, this._matrices[name]);
  23796. }
  23797. }
  23798. _super.prototype.bind.call(this, world, mesh);
  23799. };
  23800. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  23801. for (var name in this._textures) {
  23802. this._textures[name].dispose();
  23803. }
  23804. this._textures = [];
  23805. _super.prototype.dispose.call(this, forceDisposeEffect);
  23806. };
  23807. return ShaderMaterial;
  23808. })(BABYLON.Material);
  23809. BABYLON.ShaderMaterial = ShaderMaterial;
  23810. })(BABYLON || (BABYLON = {}));
  23811. //# sourceMappingURL=babylon.shaderMaterial.js.map
  23812. var BABYLON;
  23813. (function (BABYLON) {
  23814. var VertexData = (function () {
  23815. function VertexData() {
  23816. }
  23817. VertexData.prototype.set = function (data, kind) {
  23818. switch (kind) {
  23819. case BABYLON.VertexBuffer.PositionKind:
  23820. this.positions = data;
  23821. break;
  23822. case BABYLON.VertexBuffer.NormalKind:
  23823. this.normals = data;
  23824. break;
  23825. case BABYLON.VertexBuffer.UVKind:
  23826. this.uvs = data;
  23827. break;
  23828. case BABYLON.VertexBuffer.UV2Kind:
  23829. this.uv2s = data;
  23830. break;
  23831. case BABYLON.VertexBuffer.ColorKind:
  23832. this.colors = data;
  23833. break;
  23834. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23835. this.matricesIndices = data;
  23836. break;
  23837. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23838. this.matricesWeights = data;
  23839. break;
  23840. }
  23841. };
  23842. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23843. this._applyTo(mesh, updatable);
  23844. };
  23845. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23846. this._applyTo(geometry, updatable);
  23847. };
  23848. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23849. this._update(mesh);
  23850. };
  23851. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23852. this._update(geometry);
  23853. };
  23854. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23855. if (this.positions) {
  23856. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23857. }
  23858. if (this.normals) {
  23859. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23860. }
  23861. if (this.uvs) {
  23862. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23863. }
  23864. if (this.uv2s) {
  23865. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  23866. }
  23867. if (this.colors) {
  23868. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23869. }
  23870. if (this.matricesIndices) {
  23871. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23872. }
  23873. if (this.matricesWeights) {
  23874. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23875. }
  23876. if (this.indices) {
  23877. meshOrGeometry.setIndices(this.indices);
  23878. }
  23879. };
  23880. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23881. if (this.positions) {
  23882. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23883. }
  23884. if (this.normals) {
  23885. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23886. }
  23887. if (this.uvs) {
  23888. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23889. }
  23890. if (this.uv2s) {
  23891. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  23892. }
  23893. if (this.colors) {
  23894. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23895. }
  23896. if (this.matricesIndices) {
  23897. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23898. }
  23899. if (this.matricesWeights) {
  23900. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23901. }
  23902. if (this.indices) {
  23903. meshOrGeometry.setIndices(this.indices);
  23904. }
  23905. };
  23906. VertexData.prototype.transform = function (matrix) {
  23907. var transformed = BABYLON.Vector3.Zero();
  23908. if (this.positions) {
  23909. var position = BABYLON.Vector3.Zero();
  23910. for (var index = 0; index < this.positions.length; index += 3) {
  23911. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23912. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23913. this.positions[index] = transformed.x;
  23914. this.positions[index + 1] = transformed.y;
  23915. this.positions[index + 2] = transformed.z;
  23916. }
  23917. }
  23918. if (this.normals) {
  23919. var normal = BABYLON.Vector3.Zero();
  23920. for (index = 0; index < this.normals.length; index += 3) {
  23921. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23922. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23923. this.normals[index] = transformed.x;
  23924. this.normals[index + 1] = transformed.y;
  23925. this.normals[index + 2] = transformed.z;
  23926. }
  23927. }
  23928. };
  23929. VertexData.prototype.merge = function (other) {
  23930. if (other.indices) {
  23931. if (!this.indices) {
  23932. this.indices = [];
  23933. }
  23934. var offset = this.positions ? this.positions.length / 3 : 0;
  23935. for (var index = 0; index < other.indices.length; index++) {
  23936. this.indices.push(other.indices[index] + offset);
  23937. }
  23938. }
  23939. if (other.positions) {
  23940. if (!this.positions) {
  23941. this.positions = [];
  23942. }
  23943. for (index = 0; index < other.positions.length; index++) {
  23944. this.positions.push(other.positions[index]);
  23945. }
  23946. }
  23947. if (other.normals) {
  23948. if (!this.normals) {
  23949. this.normals = [];
  23950. }
  23951. for (index = 0; index < other.normals.length; index++) {
  23952. this.normals.push(other.normals[index]);
  23953. }
  23954. }
  23955. if (other.uvs) {
  23956. if (!this.uvs) {
  23957. this.uvs = [];
  23958. }
  23959. for (index = 0; index < other.uvs.length; index++) {
  23960. this.uvs.push(other.uvs[index]);
  23961. }
  23962. }
  23963. if (other.uv2s) {
  23964. if (!this.uv2s) {
  23965. this.uv2s = [];
  23966. }
  23967. for (index = 0; index < other.uv2s.length; index++) {
  23968. this.uv2s.push(other.uv2s[index]);
  23969. }
  23970. }
  23971. if (other.matricesIndices) {
  23972. if (!this.matricesIndices) {
  23973. this.matricesIndices = [];
  23974. }
  23975. for (index = 0; index < other.matricesIndices.length; index++) {
  23976. this.matricesIndices.push(other.matricesIndices[index]);
  23977. }
  23978. }
  23979. if (other.matricesWeights) {
  23980. if (!this.matricesWeights) {
  23981. this.matricesWeights = [];
  23982. }
  23983. for (index = 0; index < other.matricesWeights.length; index++) {
  23984. this.matricesWeights.push(other.matricesWeights[index]);
  23985. }
  23986. }
  23987. if (other.colors) {
  23988. if (!this.colors) {
  23989. this.colors = [];
  23990. }
  23991. for (index = 0; index < other.colors.length; index++) {
  23992. this.colors.push(other.colors[index]);
  23993. }
  23994. }
  23995. };
  23996. // Statics
  23997. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23998. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23999. };
  24000. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24001. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24002. };
  24003. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24004. var result = new VertexData();
  24005. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24006. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24007. }
  24008. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24009. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24010. }
  24011. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24012. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24013. }
  24014. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24015. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24016. }
  24017. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24018. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24019. }
  24020. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24021. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24022. }
  24023. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24024. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24025. }
  24026. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24027. return result;
  24028. };
  24029. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  24030. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24031. closeArray = closeArray || false;
  24032. closePath = closePath || false;
  24033. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24034. offset = offset || defaultOffset;
  24035. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24036. var positions = [];
  24037. var indices = [];
  24038. var normals = [];
  24039. var uvs = [];
  24040. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24041. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24042. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24043. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24044. var minlg; // minimal length among all paths from pathArray
  24045. var lg = []; // array of path lengths : nb of vertex per path
  24046. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  24047. var p; // path iterator
  24048. var i; // point iterator
  24049. var j; // point iterator
  24050. // if single path in pathArray
  24051. if (pathArray.length < 2) {
  24052. var ar1 = [];
  24053. var ar2 = [];
  24054. for (i = 0; i < pathArray[0].length - offset; i++) {
  24055. ar1.push(pathArray[0][i]);
  24056. ar2.push(pathArray[0][i + offset]);
  24057. }
  24058. pathArray = [ar1, ar2];
  24059. }
  24060. // positions and horizontal distances (u)
  24061. var idc = 0;
  24062. minlg = pathArray[0].length;
  24063. for (p = 0; p < pathArray.length; p++) {
  24064. uTotalDistance[p] = 0;
  24065. us[p] = [0];
  24066. var path = pathArray[p];
  24067. var l = path.length;
  24068. minlg = (minlg < l) ? minlg : l;
  24069. lg[p] = l;
  24070. idx[p] = idc;
  24071. j = 0;
  24072. while (j < l) {
  24073. positions.push(path[j].x, path[j].y, path[j].z);
  24074. if (j > 0) {
  24075. var vectlg = path[j].subtract(path[j - 1]).length();
  24076. var dist = vectlg + uTotalDistance[p];
  24077. us[p].push(dist);
  24078. uTotalDistance[p] = dist;
  24079. }
  24080. j++;
  24081. }
  24082. if (closePath) {
  24083. vectlg = path[0].subtract(path[j - 1]).length();
  24084. dist = vectlg + uTotalDistance[p];
  24085. uTotalDistance[p] = dist;
  24086. }
  24087. idc += l;
  24088. }
  24089. for (i = 0; i < minlg; i++) {
  24090. vTotalDistance[i] = 0;
  24091. vs[i] = [0];
  24092. var path1;
  24093. var path2;
  24094. for (p = 0; p < pathArray.length - 1; p++) {
  24095. path1 = pathArray[p];
  24096. path2 = pathArray[p + 1];
  24097. vectlg = path2[i].subtract(path1[i]).length();
  24098. dist = vectlg + vTotalDistance[i];
  24099. vs[i].push(dist);
  24100. vTotalDistance[i] = dist;
  24101. }
  24102. if (closeArray) {
  24103. path1 = pathArray[p];
  24104. path2 = pathArray[0];
  24105. vectlg = path2[i].subtract(path1[i]).length();
  24106. dist = vectlg + vTotalDistance[i];
  24107. vTotalDistance[i] = dist;
  24108. }
  24109. }
  24110. // uvs
  24111. var u;
  24112. var v;
  24113. for (p = 0; p < pathArray.length; p++) {
  24114. for (i = 0; i < minlg; i++) {
  24115. u = us[p][i] / uTotalDistance[p];
  24116. v = vs[i][p] / vTotalDistance[i];
  24117. uvs.push(u, v);
  24118. }
  24119. }
  24120. // indices
  24121. p = 0; // path index
  24122. var pi = 0; // positions array index
  24123. var l1 = lg[p] - 1; // path1 length
  24124. var l2 = lg[p + 1] - 1; // path2 length
  24125. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24126. var shft = idx[1] - idx[0]; // shift
  24127. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  24128. var t1; // two consecutive triangles, so 4 points : point1
  24129. var t2; // point2
  24130. var t3; // point3
  24131. var t4; // point4
  24132. while (pi <= min && p < path1nb) {
  24133. // 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
  24134. t1 = pi;
  24135. t2 = pi + shft;
  24136. t3 = pi + 1;
  24137. t4 = pi + shft + 1;
  24138. indices.push(pi, pi + shft, pi + 1);
  24139. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24140. pi += 1;
  24141. if (pi === min) {
  24142. if (closePath) {
  24143. indices.push(pi, pi + shft, idx[p]);
  24144. indices.push(idx[p] + shft, idx[p], pi + shft);
  24145. t3 = idx[p];
  24146. t4 = idx[p] + shft;
  24147. }
  24148. p++;
  24149. if (p === lg.length - 1) {
  24150. shft = idx[0] - idx[p];
  24151. l1 = lg[p] - 1;
  24152. l2 = lg[0] - 1;
  24153. }
  24154. else {
  24155. shft = idx[p + 1] - idx[p];
  24156. l1 = lg[p] - 1;
  24157. l2 = lg[p + 1] - 1;
  24158. }
  24159. pi = idx[p];
  24160. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24161. }
  24162. }
  24163. // normals
  24164. VertexData.ComputeNormals(positions, indices, normals);
  24165. // sides
  24166. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24167. // Result
  24168. var vertexData = new VertexData();
  24169. vertexData.indices = indices;
  24170. vertexData.positions = positions;
  24171. vertexData.normals = normals;
  24172. vertexData.uvs = uvs;
  24173. return vertexData;
  24174. };
  24175. VertexData.CreateBox = function (size, sideOrientation) {
  24176. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24177. var normalsSource = [
  24178. new BABYLON.Vector3(0, 0, 1),
  24179. new BABYLON.Vector3(0, 0, -1),
  24180. new BABYLON.Vector3(1, 0, 0),
  24181. new BABYLON.Vector3(-1, 0, 0),
  24182. new BABYLON.Vector3(0, 1, 0),
  24183. new BABYLON.Vector3(0, -1, 0)
  24184. ];
  24185. var indices = [];
  24186. var positions = [];
  24187. var normals = [];
  24188. var uvs = [];
  24189. size = size || 1;
  24190. for (var index = 0; index < normalsSource.length; index++) {
  24191. var normal = normalsSource[index];
  24192. // Get two vectors perpendicular to the face normal and to each other.
  24193. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24194. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24195. // Six indices (two triangles) per face.
  24196. var verticesLength = positions.length / 3;
  24197. indices.push(verticesLength);
  24198. indices.push(verticesLength + 1);
  24199. indices.push(verticesLength + 2);
  24200. indices.push(verticesLength);
  24201. indices.push(verticesLength + 2);
  24202. indices.push(verticesLength + 3);
  24203. // Four vertices per face.
  24204. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  24205. positions.push(vertex.x, vertex.y, vertex.z);
  24206. normals.push(normal.x, normal.y, normal.z);
  24207. uvs.push(1.0, 1.0);
  24208. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  24209. positions.push(vertex.x, vertex.y, vertex.z);
  24210. normals.push(normal.x, normal.y, normal.z);
  24211. uvs.push(0.0, 1.0);
  24212. vertex = normal.add(side1).add(side2).scale(size / 2);
  24213. positions.push(vertex.x, vertex.y, vertex.z);
  24214. normals.push(normal.x, normal.y, normal.z);
  24215. uvs.push(0.0, 0.0);
  24216. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  24217. positions.push(vertex.x, vertex.y, vertex.z);
  24218. normals.push(normal.x, normal.y, normal.z);
  24219. uvs.push(1.0, 0.0);
  24220. }
  24221. // sides
  24222. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24223. // Result
  24224. var vertexData = new VertexData();
  24225. vertexData.indices = indices;
  24226. vertexData.positions = positions;
  24227. vertexData.normals = normals;
  24228. vertexData.uvs = uvs;
  24229. return vertexData;
  24230. };
  24231. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  24232. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24233. segments = segments || 32;
  24234. diameter = diameter || 1;
  24235. var radius = diameter / 2;
  24236. var totalZRotationSteps = 2 + segments;
  24237. var totalYRotationSteps = 2 * totalZRotationSteps;
  24238. var indices = [];
  24239. var positions = [];
  24240. var normals = [];
  24241. var uvs = [];
  24242. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24243. var normalizedZ = zRotationStep / totalZRotationSteps;
  24244. var angleZ = (normalizedZ * Math.PI);
  24245. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24246. var normalizedY = yRotationStep / totalYRotationSteps;
  24247. var angleY = normalizedY * Math.PI * 2;
  24248. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24249. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24250. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24251. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24252. var vertex = complete.scale(radius);
  24253. var normal = BABYLON.Vector3.Normalize(vertex);
  24254. positions.push(vertex.x, vertex.y, vertex.z);
  24255. normals.push(normal.x, normal.y, normal.z);
  24256. uvs.push(normalizedZ, normalizedY);
  24257. }
  24258. if (zRotationStep > 0) {
  24259. var verticesCount = positions.length / 3;
  24260. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24261. indices.push((firstIndex));
  24262. indices.push((firstIndex + 1));
  24263. indices.push(firstIndex + totalYRotationSteps + 1);
  24264. indices.push((firstIndex + totalYRotationSteps + 1));
  24265. indices.push((firstIndex + 1));
  24266. indices.push((firstIndex + totalYRotationSteps + 2));
  24267. }
  24268. }
  24269. }
  24270. // Sides
  24271. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24272. // Result
  24273. var vertexData = new VertexData();
  24274. vertexData.indices = indices;
  24275. vertexData.positions = positions;
  24276. vertexData.normals = normals;
  24277. vertexData.uvs = uvs;
  24278. return vertexData;
  24279. };
  24280. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  24281. if (subdivisions === void 0) { subdivisions = 1; }
  24282. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24283. var radiusTop = diameterTop / 2;
  24284. var radiusBottom = diameterBottom / 2;
  24285. var indices = [];
  24286. var positions = [];
  24287. var normals = [];
  24288. var uvs = [];
  24289. height = height || 1;
  24290. diameterTop = diameterTop || 0.5;
  24291. diameterBottom = diameterBottom || 1;
  24292. tessellation = tessellation || 16;
  24293. subdivisions = subdivisions || 1;
  24294. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  24295. var getCircleVector = function (i) {
  24296. var angle = (i * 2.0 * Math.PI / tessellation);
  24297. var dx = Math.cos(angle);
  24298. var dz = Math.sin(angle);
  24299. return new BABYLON.Vector3(dx, 0, dz);
  24300. };
  24301. var createCylinderCap = function (isTop) {
  24302. var radius = isTop ? radiusTop : radiusBottom;
  24303. if (radius === 0) {
  24304. return;
  24305. }
  24306. var vbase = positions.length / 3;
  24307. var offset = new BABYLON.Vector3(0, height / 2, 0);
  24308. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  24309. if (!isTop) {
  24310. offset.scaleInPlace(-1);
  24311. textureScale.x = -textureScale.x;
  24312. }
  24313. for (var i = 0; i < tessellation; i++) {
  24314. var circleVector = getCircleVector(i);
  24315. var position = circleVector.scale(radius).add(offset);
  24316. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  24317. positions.push(position.x, position.y, position.z);
  24318. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24319. }
  24320. for (i = 0; i < tessellation - 2; i++) {
  24321. if (!isTop) {
  24322. indices.push(vbase);
  24323. indices.push(vbase + (i + 2) % tessellation);
  24324. indices.push(vbase + (i + 1) % tessellation);
  24325. }
  24326. else {
  24327. indices.push(vbase);
  24328. indices.push(vbase + (i + 1) % tessellation);
  24329. indices.push(vbase + (i + 2) % tessellation);
  24330. }
  24331. }
  24332. };
  24333. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  24334. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  24335. var stride = tessellation + 1;
  24336. for (var i = 0; i <= tessellation; i++) {
  24337. var circleVector = getCircleVector(i);
  24338. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  24339. var position, radius = radiusBottom;
  24340. for (var s = 0; s <= subdivisions; s++) {
  24341. // Update variables
  24342. position = circleVector.scale(radius);
  24343. position.addInPlace(base.add(offset.scale(s)));
  24344. textureCoordinate.y += 1 / subdivisions;
  24345. radius += (radiusTop - radiusBottom) / subdivisions;
  24346. // Push in arrays
  24347. positions.push(position.x, position.y, position.z);
  24348. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24349. }
  24350. }
  24351. subdivisions += 1;
  24352. for (s = 0; s < subdivisions - 1; s++) {
  24353. for (i = 0; i <= tessellation; i++) {
  24354. indices.push(i * subdivisions + s);
  24355. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  24356. indices.push(i * subdivisions + (s + 1));
  24357. indices.push(i * subdivisions + (s + 1));
  24358. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  24359. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  24360. }
  24361. }
  24362. // Create flat triangle fan caps to seal the top and bottom.
  24363. createCylinderCap(true);
  24364. createCylinderCap(false);
  24365. // Normals
  24366. VertexData.ComputeNormals(positions, indices, normals);
  24367. // Sides
  24368. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24369. // Result
  24370. var vertexData = new VertexData();
  24371. vertexData.indices = indices;
  24372. vertexData.positions = positions;
  24373. vertexData.normals = normals;
  24374. vertexData.uvs = uvs;
  24375. return vertexData;
  24376. };
  24377. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  24378. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24379. var indices = [];
  24380. var positions = [];
  24381. var normals = [];
  24382. var uvs = [];
  24383. diameter = diameter || 1;
  24384. thickness = thickness || 0.5;
  24385. tessellation = tessellation || 16;
  24386. var stride = tessellation + 1;
  24387. for (var i = 0; i <= tessellation; i++) {
  24388. var u = i / tessellation;
  24389. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24390. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24391. for (var j = 0; j <= tessellation; j++) {
  24392. var v = 1 - j / tessellation;
  24393. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24394. var dx = Math.cos(innerAngle);
  24395. var dy = Math.sin(innerAngle);
  24396. // Create a vertex.
  24397. var normal = new BABYLON.Vector3(dx, dy, 0);
  24398. var position = normal.scale(thickness / 2);
  24399. var textureCoordinate = new BABYLON.Vector2(u, v);
  24400. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24401. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24402. positions.push(position.x, position.y, position.z);
  24403. normals.push(normal.x, normal.y, normal.z);
  24404. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24405. // And create indices for two triangles.
  24406. var nextI = (i + 1) % stride;
  24407. var nextJ = (j + 1) % stride;
  24408. indices.push(i * stride + j);
  24409. indices.push(i * stride + nextJ);
  24410. indices.push(nextI * stride + j);
  24411. indices.push(i * stride + nextJ);
  24412. indices.push(nextI * stride + nextJ);
  24413. indices.push(nextI * stride + j);
  24414. }
  24415. }
  24416. // Sides
  24417. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24418. // Result
  24419. var vertexData = new VertexData();
  24420. vertexData.indices = indices;
  24421. vertexData.positions = positions;
  24422. vertexData.normals = normals;
  24423. vertexData.uvs = uvs;
  24424. return vertexData;
  24425. };
  24426. VertexData.CreateLines = function (points) {
  24427. var indices = [];
  24428. var positions = [];
  24429. for (var index = 0; index < points.length; index++) {
  24430. positions.push(points[index].x, points[index].y, points[index].z);
  24431. if (index > 0) {
  24432. indices.push(index - 1);
  24433. indices.push(index);
  24434. }
  24435. }
  24436. // Result
  24437. var vertexData = new VertexData();
  24438. vertexData.indices = indices;
  24439. vertexData.positions = positions;
  24440. return vertexData;
  24441. };
  24442. VertexData.CreateGround = function (width, height, subdivisions) {
  24443. var indices = [];
  24444. var positions = [];
  24445. var normals = [];
  24446. var uvs = [];
  24447. var row, col;
  24448. width = width || 1;
  24449. height = height || 1;
  24450. subdivisions = subdivisions || 1;
  24451. for (row = 0; row <= subdivisions; row++) {
  24452. for (col = 0; col <= subdivisions; col++) {
  24453. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24454. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24455. positions.push(position.x, position.y, position.z);
  24456. normals.push(normal.x, normal.y, normal.z);
  24457. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24458. }
  24459. }
  24460. for (row = 0; row < subdivisions; row++) {
  24461. for (col = 0; col < subdivisions; col++) {
  24462. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24463. indices.push(col + 1 + row * (subdivisions + 1));
  24464. indices.push(col + row * (subdivisions + 1));
  24465. indices.push(col + (row + 1) * (subdivisions + 1));
  24466. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24467. indices.push(col + row * (subdivisions + 1));
  24468. }
  24469. }
  24470. // Result
  24471. var vertexData = new VertexData();
  24472. vertexData.indices = indices;
  24473. vertexData.positions = positions;
  24474. vertexData.normals = normals;
  24475. vertexData.uvs = uvs;
  24476. return vertexData;
  24477. };
  24478. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  24479. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  24480. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  24481. var indices = [];
  24482. var positions = [];
  24483. var normals = [];
  24484. var uvs = [];
  24485. var row, col, tileRow, tileCol;
  24486. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  24487. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24488. precision.w = (precision.w < 1) ? 1 : precision.w;
  24489. precision.h = (precision.h < 1) ? 1 : precision.h;
  24490. var tileSize = {
  24491. 'w': (xmax - xmin) / subdivisions.w,
  24492. 'h': (zmax - zmin) / subdivisions.h
  24493. };
  24494. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24495. // Indices
  24496. var base = positions.length / 3;
  24497. var rowLength = precision.w + 1;
  24498. for (row = 0; row < precision.h; row++) {
  24499. for (col = 0; col < precision.w; col++) {
  24500. var square = [
  24501. base + col + row * rowLength,
  24502. base + (col + 1) + row * rowLength,
  24503. base + (col + 1) + (row + 1) * rowLength,
  24504. base + col + (row + 1) * rowLength
  24505. ];
  24506. indices.push(square[1]);
  24507. indices.push(square[2]);
  24508. indices.push(square[3]);
  24509. indices.push(square[0]);
  24510. indices.push(square[1]);
  24511. indices.push(square[3]);
  24512. }
  24513. }
  24514. // Position, normals and uvs
  24515. var position = BABYLON.Vector3.Zero();
  24516. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24517. for (row = 0; row <= precision.h; row++) {
  24518. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24519. for (col = 0; col <= precision.w; col++) {
  24520. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24521. position.y = 0;
  24522. positions.push(position.x, position.y, position.z);
  24523. normals.push(normal.x, normal.y, normal.z);
  24524. uvs.push(col / precision.w, row / precision.h);
  24525. }
  24526. }
  24527. }
  24528. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24529. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24530. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24531. }
  24532. }
  24533. // Result
  24534. var vertexData = new VertexData();
  24535. vertexData.indices = indices;
  24536. vertexData.positions = positions;
  24537. vertexData.normals = normals;
  24538. vertexData.uvs = uvs;
  24539. return vertexData;
  24540. };
  24541. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  24542. var indices = [];
  24543. var positions = [];
  24544. var normals = [];
  24545. var uvs = [];
  24546. var row, col;
  24547. for (row = 0; row <= subdivisions; row++) {
  24548. for (col = 0; col <= subdivisions; col++) {
  24549. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24550. // Compute height
  24551. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  24552. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  24553. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  24554. var r = buffer[pos] / 255.0;
  24555. var g = buffer[pos + 1] / 255.0;
  24556. var b = buffer[pos + 2] / 255.0;
  24557. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24558. position.y = minHeight + (maxHeight - minHeight) * gradient;
  24559. // Add vertex
  24560. positions.push(position.x, position.y, position.z);
  24561. normals.push(0, 0, 0);
  24562. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24563. }
  24564. }
  24565. for (row = 0; row < subdivisions; row++) {
  24566. for (col = 0; col < subdivisions; col++) {
  24567. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24568. indices.push(col + 1 + row * (subdivisions + 1));
  24569. indices.push(col + row * (subdivisions + 1));
  24570. indices.push(col + (row + 1) * (subdivisions + 1));
  24571. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24572. indices.push(col + row * (subdivisions + 1));
  24573. }
  24574. }
  24575. // Normals
  24576. VertexData.ComputeNormals(positions, indices, normals);
  24577. // Result
  24578. var vertexData = new VertexData();
  24579. vertexData.indices = indices;
  24580. vertexData.positions = positions;
  24581. vertexData.normals = normals;
  24582. vertexData.uvs = uvs;
  24583. return vertexData;
  24584. };
  24585. VertexData.CreatePlane = function (size, sideOrientation) {
  24586. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24587. var indices = [];
  24588. var positions = [];
  24589. var normals = [];
  24590. var uvs = [];
  24591. size = size || 1;
  24592. // Vertices
  24593. var halfSize = size / 2.0;
  24594. positions.push(-halfSize, -halfSize, 0);
  24595. normals.push(0, 0, -1.0);
  24596. uvs.push(0.0, 0.0);
  24597. positions.push(halfSize, -halfSize, 0);
  24598. normals.push(0, 0, -1.0);
  24599. uvs.push(1.0, 0.0);
  24600. positions.push(halfSize, halfSize, 0);
  24601. normals.push(0, 0, -1.0);
  24602. uvs.push(1.0, 1.0);
  24603. positions.push(-halfSize, halfSize, 0);
  24604. normals.push(0, 0, -1.0);
  24605. uvs.push(0.0, 1.0);
  24606. // Indices
  24607. indices.push(0);
  24608. indices.push(1);
  24609. indices.push(2);
  24610. indices.push(0);
  24611. indices.push(2);
  24612. indices.push(3);
  24613. // Sides
  24614. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24615. // Result
  24616. var vertexData = new VertexData();
  24617. vertexData.indices = indices;
  24618. vertexData.positions = positions;
  24619. vertexData.normals = normals;
  24620. vertexData.uvs = uvs;
  24621. return vertexData;
  24622. };
  24623. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  24624. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24625. var positions = [];
  24626. var indices = [];
  24627. var normals = [];
  24628. var uvs = [];
  24629. // positions and uvs
  24630. positions.push(0, 0, 0); // disc center first
  24631. uvs.push(0.5, 0.5);
  24632. var step = Math.PI * 2 / tessellation;
  24633. for (var a = 0; a < Math.PI * 2; a += step) {
  24634. var x = Math.cos(a);
  24635. var y = Math.sin(a);
  24636. var u = (x + 1) / 2;
  24637. var v = (1 - y) / 2;
  24638. positions.push(radius * x, radius * y, 0);
  24639. uvs.push(u, v);
  24640. }
  24641. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24642. uvs.push(uvs[2], uvs[3]);
  24643. //indices
  24644. var vertexNb = positions.length / 3;
  24645. for (var i = 1; i < vertexNb - 1; i++) {
  24646. indices.push(i + 1, 0, i);
  24647. }
  24648. // result
  24649. VertexData.ComputeNormals(positions, indices, normals);
  24650. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24651. var vertexData = new VertexData();
  24652. vertexData.indices = indices;
  24653. vertexData.positions = positions;
  24654. vertexData.normals = normals;
  24655. vertexData.uvs = uvs;
  24656. return vertexData;
  24657. };
  24658. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24659. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  24660. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24661. var indices = [];
  24662. var positions = [];
  24663. var normals = [];
  24664. var uvs = [];
  24665. radius = radius || 2;
  24666. tube = tube || 0.5;
  24667. radialSegments = radialSegments || 32;
  24668. tubularSegments = tubularSegments || 32;
  24669. p = p || 2;
  24670. q = q || 3;
  24671. // Helper
  24672. var getPos = function (angle) {
  24673. var cu = Math.cos(angle);
  24674. var su = Math.sin(angle);
  24675. var quOverP = q / p * angle;
  24676. var cs = Math.cos(quOverP);
  24677. var tx = radius * (2 + cs) * 0.5 * cu;
  24678. var ty = radius * (2 + cs) * su * 0.5;
  24679. var tz = radius * Math.sin(quOverP) * 0.5;
  24680. return new BABYLON.Vector3(tx, ty, tz);
  24681. };
  24682. for (var i = 0; i <= radialSegments; i++) {
  24683. var modI = i % radialSegments;
  24684. var u = modI / radialSegments * 2 * p * Math.PI;
  24685. var p1 = getPos(u);
  24686. var p2 = getPos(u + 0.01);
  24687. var tang = p2.subtract(p1);
  24688. var n = p2.add(p1);
  24689. var bitan = BABYLON.Vector3.Cross(tang, n);
  24690. n = BABYLON.Vector3.Cross(bitan, tang);
  24691. bitan.normalize();
  24692. n.normalize();
  24693. for (var j = 0; j < tubularSegments; j++) {
  24694. var modJ = j % tubularSegments;
  24695. var v = modJ / tubularSegments * 2 * Math.PI;
  24696. var cx = -tube * Math.cos(v);
  24697. var cy = tube * Math.sin(v);
  24698. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24699. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24700. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24701. uvs.push(i / radialSegments);
  24702. uvs.push(j / tubularSegments);
  24703. }
  24704. }
  24705. for (i = 0; i < radialSegments; i++) {
  24706. for (j = 0; j < tubularSegments; j++) {
  24707. var jNext = (j + 1) % tubularSegments;
  24708. var a = i * tubularSegments + j;
  24709. var b = (i + 1) * tubularSegments + j;
  24710. var c = (i + 1) * tubularSegments + jNext;
  24711. var d = i * tubularSegments + jNext;
  24712. indices.push(d);
  24713. indices.push(b);
  24714. indices.push(a);
  24715. indices.push(d);
  24716. indices.push(c);
  24717. indices.push(b);
  24718. }
  24719. }
  24720. // Normals
  24721. VertexData.ComputeNormals(positions, indices, normals);
  24722. // Sides
  24723. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24724. // Result
  24725. var vertexData = new VertexData();
  24726. vertexData.indices = indices;
  24727. vertexData.positions = positions;
  24728. vertexData.normals = normals;
  24729. vertexData.uvs = uvs;
  24730. return vertexData;
  24731. };
  24732. // Tools
  24733. /**
  24734. * @param {any} - positions (number[] or Float32Array)
  24735. * @param {any} - indices (number[] or Uint16Array)
  24736. * @param {any} - normals (number[] or Float32Array)
  24737. */
  24738. VertexData.ComputeNormals = function (positions, indices, normals) {
  24739. var index = 0;
  24740. // temp Vector3
  24741. var p1 = BABYLON.Vector3.Zero();
  24742. var p2 = BABYLON.Vector3.Zero();
  24743. var p3 = BABYLON.Vector3.Zero();
  24744. var p1p2 = BABYLON.Vector3.Zero();
  24745. var p3p2 = BABYLON.Vector3.Zero();
  24746. var faceNormal = BABYLON.Vector3.Zero();
  24747. var vertexNormali1 = BABYLON.Vector3.Zero();
  24748. var vertexNormali2 = BABYLON.Vector3.Zero();
  24749. var vertexNormali3 = BABYLON.Vector3.Zero();
  24750. // indice triplet = 1 face
  24751. var nbFaces = indices.length / 3;
  24752. for (index = 0; index < nbFaces; index++) {
  24753. var i1 = indices[index * 3];
  24754. var i2 = indices[index * 3 + 1];
  24755. var i3 = indices[index * 3 + 2];
  24756. // setting the temp V3
  24757. BABYLON.Vector3.FromFloatsToRef(positions[i1 * 3], positions[i1 * 3 + 1], positions[i1 * 3 + 2], p1);
  24758. BABYLON.Vector3.FromFloatsToRef(positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2], p2);
  24759. BABYLON.Vector3.FromFloatsToRef(positions[i3 * 3], positions[i3 * 3 + 1], positions[i3 * 3 + 2], p3);
  24760. p1.subtractToRef(p2, p1p2);
  24761. p3.subtractToRef(p2, p3p2);
  24762. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  24763. faceNormal.normalize();
  24764. // All intermediate results are stored in the normals array :
  24765. // get the normals at i1, i2 and i3 indexes
  24766. normals[i1 * 3] = normals[i1 * 3] || 0.0;
  24767. normals[i1 * 3 + 1] = normals[i1 * 3 + 1] || 0.0;
  24768. normals[i1 * 3 + 2] = normals[i1 * 3 + 2] || 0.0;
  24769. normals[i2 * 3] = normals[i2 * 3] || 0.0;
  24770. normals[i2 * 3 + 1] = normals[i2 * 3 + 1] || 0.0;
  24771. normals[i2 * 3 + 2] = normals[i2 * 3 + 2] || 0.0;
  24772. normals[i3 * 3] = normals[i3 * 3] || 0.0;
  24773. normals[i3 * 3 + 1] = normals[i3 * 3 + 1] || 0.0;
  24774. normals[i3 * 3 + 2] = normals[i3 * 3 + 2] || 0.0;
  24775. // make intermediate vectors3 from normals values
  24776. BABYLON.Vector3.FromFloatsToRef(normals[i1 * 3], normals[i1 * 3 + 1], normals[i1 * 3 + 2], vertexNormali1);
  24777. BABYLON.Vector3.FromFloatsToRef(normals[i2 * 3], normals[i2 * 3 + 1], normals[i2 * 3 + 2], vertexNormali2);
  24778. BABYLON.Vector3.FromFloatsToRef(normals[i3 * 3], normals[i3 * 3 + 1], normals[i3 * 3 + 2], vertexNormali3);
  24779. // add the current face normals to these intermediate vectors3
  24780. vertexNormali1 = vertexNormali1.addInPlace(faceNormal);
  24781. vertexNormali2 = vertexNormali2.addInPlace(faceNormal);
  24782. vertexNormali3 = vertexNormali3.addInPlace(faceNormal);
  24783. // store back intermediate vectors3 into the normals array
  24784. normals[i1 * 3] = vertexNormali1.x;
  24785. normals[i1 * 3 + 1] = vertexNormali1.y;
  24786. normals[i1 * 3 + 2] = vertexNormali1.z;
  24787. normals[i2 * 3] = vertexNormali2.x;
  24788. normals[i2 * 3 + 1] = vertexNormali2.y;
  24789. normals[i2 * 3 + 2] = vertexNormali2.z;
  24790. normals[i3 * 3] = vertexNormali3.x;
  24791. normals[i3 * 3 + 1] = vertexNormali3.y;
  24792. normals[i3 * 3 + 2] = vertexNormali3.z;
  24793. }
  24794. for (index = 0; index < normals.length / 3; index++) {
  24795. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  24796. vertexNormali1.normalize();
  24797. normals[index * 3] = vertexNormali1.x;
  24798. normals[index * 3 + 1] = vertexNormali1.y;
  24799. normals[index * 3 + 2] = vertexNormali1.z;
  24800. }
  24801. };
  24802. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24803. var li = indices.length;
  24804. var ln = normals.length;
  24805. var i;
  24806. var n;
  24807. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24808. switch (sideOrientation) {
  24809. case BABYLON.Mesh.FRONTSIDE:
  24810. break;
  24811. case BABYLON.Mesh.BACKSIDE:
  24812. var tmp;
  24813. for (i = 0; i < li; i += 3) {
  24814. tmp = indices[i];
  24815. indices[i] = indices[i + 2];
  24816. indices[i + 2] = tmp;
  24817. }
  24818. for (n = 0; n < ln; n++) {
  24819. normals[n] = -normals[n];
  24820. }
  24821. break;
  24822. case BABYLON.Mesh.DOUBLESIDE:
  24823. // positions
  24824. var lp = positions.length;
  24825. var l = lp / 3;
  24826. for (var p = 0; p < lp; p++) {
  24827. positions[lp + p] = positions[p];
  24828. }
  24829. for (i = 0; i < li; i += 3) {
  24830. indices[i + li] = indices[i + 2] + l;
  24831. indices[i + 1 + li] = indices[i + 1] + l;
  24832. indices[i + 2 + li] = indices[i] + l;
  24833. }
  24834. for (n = 0; n < ln; n++) {
  24835. normals[ln + n] = -normals[n];
  24836. }
  24837. // uvs
  24838. var lu = uvs.length;
  24839. for (var u = 0; u < lu; u++) {
  24840. uvs[u + lu] = uvs[u];
  24841. }
  24842. break;
  24843. }
  24844. };
  24845. return VertexData;
  24846. })();
  24847. BABYLON.VertexData = VertexData;
  24848. })(BABYLON || (BABYLON = {}));
  24849. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  24850. var __extends = this.__extends || function (d, b) {
  24851. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24852. function __() { this.constructor = d; }
  24853. __.prototype = b.prototype;
  24854. d.prototype = new __();
  24855. };
  24856. var BABYLON;
  24857. (function (BABYLON) {
  24858. var buildCamera = function (that, name) {
  24859. that._leftCamera.isIntermediate = true;
  24860. that.subCameras.push(that._leftCamera);
  24861. that.subCameras.push(that._rightCamera);
  24862. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  24863. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  24864. that._anaglyphPostProcess.onApply = function (effect) {
  24865. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  24866. };
  24867. that._update();
  24868. };
  24869. var AnaglyphArcRotateCamera = (function (_super) {
  24870. __extends(AnaglyphArcRotateCamera, _super);
  24871. // ANY
  24872. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  24873. _super.call(this, name, alpha, beta, radius, target, scene);
  24874. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  24875. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  24876. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  24877. buildCamera(this, name);
  24878. }
  24879. AnaglyphArcRotateCamera.prototype._update = function () {
  24880. this._updateCamera(this._leftCamera);
  24881. this._updateCamera(this._rightCamera);
  24882. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  24883. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  24884. _super.prototype._update.call(this);
  24885. };
  24886. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  24887. camera.beta = this.beta;
  24888. camera.radius = this.radius;
  24889. camera.minZ = this.minZ;
  24890. camera.maxZ = this.maxZ;
  24891. camera.fov = this.fov;
  24892. camera.target = this.target;
  24893. };
  24894. return AnaglyphArcRotateCamera;
  24895. })(BABYLON.ArcRotateCamera);
  24896. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  24897. var AnaglyphFreeCamera = (function (_super) {
  24898. __extends(AnaglyphFreeCamera, _super);
  24899. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  24900. _super.call(this, name, position, scene);
  24901. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  24902. this._transformMatrix = new BABYLON.Matrix();
  24903. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  24904. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  24905. buildCamera(this, name);
  24906. }
  24907. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  24908. var target = this.getTarget();
  24909. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  24910. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  24911. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  24912. };
  24913. AnaglyphFreeCamera.prototype._update = function () {
  24914. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  24915. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  24916. this._updateCamera(this._leftCamera);
  24917. this._updateCamera(this._rightCamera);
  24918. _super.prototype._update.call(this);
  24919. };
  24920. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  24921. camera.minZ = this.minZ;
  24922. camera.maxZ = this.maxZ;
  24923. camera.fov = this.fov;
  24924. camera.viewport = this.viewport;
  24925. camera.setTarget(this.getTarget());
  24926. };
  24927. return AnaglyphFreeCamera;
  24928. })(BABYLON.FreeCamera);
  24929. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  24930. })(BABYLON || (BABYLON = {}));
  24931. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  24932. var __extends = this.__extends || function (d, b) {
  24933. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24934. function __() { this.constructor = d; }
  24935. __.prototype = b.prototype;
  24936. d.prototype = new __();
  24937. };
  24938. var BABYLON;
  24939. (function (BABYLON) {
  24940. var AnaglyphPostProcess = (function (_super) {
  24941. __extends(AnaglyphPostProcess, _super);
  24942. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  24943. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  24944. }
  24945. return AnaglyphPostProcess;
  24946. })(BABYLON.PostProcess);
  24947. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  24948. })(BABYLON || (BABYLON = {}));
  24949. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  24950. var BABYLON;
  24951. (function (BABYLON) {
  24952. var Tags = (function () {
  24953. function Tags() {
  24954. }
  24955. Tags.EnableFor = function (obj) {
  24956. obj._tags = obj._tags || {};
  24957. obj.hasTags = function () {
  24958. return Tags.HasTags(obj);
  24959. };
  24960. obj.addTags = function (tagsString) {
  24961. return Tags.AddTagsTo(obj, tagsString);
  24962. };
  24963. obj.removeTags = function (tagsString) {
  24964. return Tags.RemoveTagsFrom(obj, tagsString);
  24965. };
  24966. obj.matchesTagsQuery = function (tagsQuery) {
  24967. return Tags.MatchesQuery(obj, tagsQuery);
  24968. };
  24969. };
  24970. Tags.DisableFor = function (obj) {
  24971. delete obj._tags;
  24972. delete obj.hasTags;
  24973. delete obj.addTags;
  24974. delete obj.removeTags;
  24975. delete obj.matchesTagsQuery;
  24976. };
  24977. Tags.HasTags = function (obj) {
  24978. if (!obj._tags) {
  24979. return false;
  24980. }
  24981. return !BABYLON.Tools.IsEmpty(obj._tags);
  24982. };
  24983. Tags.GetTags = function (obj) {
  24984. if (!obj._tags) {
  24985. return null;
  24986. }
  24987. return obj._tags;
  24988. };
  24989. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24990. // a tag cannot start with '||', '&&', and '!'
  24991. // it cannot contain whitespaces
  24992. Tags.AddTagsTo = function (obj, tagsString) {
  24993. if (!tagsString) {
  24994. return;
  24995. }
  24996. var tags = tagsString.split(" ");
  24997. for (var t in tags) {
  24998. Tags._AddTagTo(obj, tags[t]);
  24999. }
  25000. };
  25001. Tags._AddTagTo = function (obj, tag) {
  25002. tag = tag.trim();
  25003. if (tag === "" || tag === "true" || tag === "false") {
  25004. return;
  25005. }
  25006. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25007. return;
  25008. }
  25009. Tags.EnableFor(obj);
  25010. obj._tags[tag] = true;
  25011. };
  25012. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25013. if (!Tags.HasTags(obj)) {
  25014. return;
  25015. }
  25016. var tags = tagsString.split(" ");
  25017. for (var t in tags) {
  25018. Tags._RemoveTagFrom(obj, tags[t]);
  25019. }
  25020. };
  25021. Tags._RemoveTagFrom = function (obj, tag) {
  25022. delete obj._tags[tag];
  25023. };
  25024. Tags.MatchesQuery = function (obj, tagsQuery) {
  25025. if (tagsQuery === undefined) {
  25026. return true;
  25027. }
  25028. if (tagsQuery === "") {
  25029. return Tags.HasTags(obj);
  25030. }
  25031. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25032. };
  25033. return Tags;
  25034. })();
  25035. BABYLON.Tags = Tags;
  25036. })(BABYLON || (BABYLON = {}));
  25037. //# sourceMappingURL=babylon.tags.js.map
  25038. var BABYLON;
  25039. (function (BABYLON) {
  25040. var Internals;
  25041. (function (Internals) {
  25042. var AndOrNotEvaluator = (function () {
  25043. function AndOrNotEvaluator() {
  25044. }
  25045. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25046. if (!query.match(/\([^\(\)]*\)/g)) {
  25047. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25048. }
  25049. else {
  25050. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25051. // remove parenthesis
  25052. r = r.slice(1, r.length - 1);
  25053. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25054. });
  25055. }
  25056. if (query === "true") {
  25057. return true;
  25058. }
  25059. if (query === "false") {
  25060. return false;
  25061. }
  25062. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  25063. };
  25064. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  25065. evaluateCallback = evaluateCallback || (function (r) {
  25066. return r === "true" ? true : false;
  25067. });
  25068. var result;
  25069. var or = parenthesisContent.split("||");
  25070. for (var i in or) {
  25071. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  25072. var and = ori.split("&&");
  25073. if (and.length > 1) {
  25074. for (var j = 0; j < and.length; ++j) {
  25075. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  25076. if (andj !== "true" && andj !== "false") {
  25077. if (andj[0] === "!") {
  25078. result = !evaluateCallback(andj.substring(1));
  25079. }
  25080. else {
  25081. result = evaluateCallback(andj);
  25082. }
  25083. }
  25084. else {
  25085. result = andj === "true" ? true : false;
  25086. }
  25087. if (!result) {
  25088. ori = "false";
  25089. break;
  25090. }
  25091. }
  25092. }
  25093. if (result || ori === "true") {
  25094. result = true;
  25095. break;
  25096. }
  25097. // result equals false (or undefined)
  25098. if (ori !== "true" && ori !== "false") {
  25099. if (ori[0] === "!") {
  25100. result = !evaluateCallback(ori.substring(1));
  25101. }
  25102. else {
  25103. result = evaluateCallback(ori);
  25104. }
  25105. }
  25106. else {
  25107. result = ori === "true" ? true : false;
  25108. }
  25109. }
  25110. // the whole parenthesis scope is replaced by 'true' or 'false'
  25111. return result ? "true" : "false";
  25112. };
  25113. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  25114. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  25115. // remove whitespaces
  25116. r = r.replace(/[\s]/g, function () { return ""; });
  25117. return r.length % 2 ? "!" : "";
  25118. });
  25119. booleanString = booleanString.trim();
  25120. if (booleanString === "!true") {
  25121. booleanString = "false";
  25122. }
  25123. else if (booleanString === "!false") {
  25124. booleanString = "true";
  25125. }
  25126. return booleanString;
  25127. };
  25128. return AndOrNotEvaluator;
  25129. })();
  25130. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  25131. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25132. })(BABYLON || (BABYLON = {}));
  25133. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  25134. var BABYLON;
  25135. (function (BABYLON) {
  25136. var PostProcessRenderPass = (function () {
  25137. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  25138. this._enabled = true;
  25139. this._refCount = 0;
  25140. this._name = name;
  25141. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  25142. this.setRenderList(renderList);
  25143. this._renderTexture.onBeforeRender = beforeRender;
  25144. this._renderTexture.onAfterRender = afterRender;
  25145. this._scene = scene;
  25146. this._renderList = renderList;
  25147. }
  25148. // private
  25149. PostProcessRenderPass.prototype._incRefCount = function () {
  25150. if (this._refCount === 0) {
  25151. this._scene.customRenderTargets.push(this._renderTexture);
  25152. }
  25153. return ++this._refCount;
  25154. };
  25155. PostProcessRenderPass.prototype._decRefCount = function () {
  25156. this._refCount--;
  25157. if (this._refCount <= 0) {
  25158. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  25159. }
  25160. return this._refCount;
  25161. };
  25162. PostProcessRenderPass.prototype._update = function () {
  25163. this.setRenderList(this._renderList);
  25164. };
  25165. // public
  25166. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  25167. this._renderTexture.renderList = renderList;
  25168. };
  25169. PostProcessRenderPass.prototype.getRenderTexture = function () {
  25170. return this._renderTexture;
  25171. };
  25172. return PostProcessRenderPass;
  25173. })();
  25174. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  25175. })(BABYLON || (BABYLON = {}));
  25176. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  25177. var BABYLON;
  25178. (function (BABYLON) {
  25179. var PostProcessRenderEffect = (function () {
  25180. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  25181. this._engine = engine;
  25182. this._name = name;
  25183. this._singleInstance = singleInstance || true;
  25184. this._getPostProcess = getPostProcess;
  25185. this._cameras = [];
  25186. this._indicesForCamera = [];
  25187. this._postProcesses = {};
  25188. this._renderPasses = {};
  25189. this._renderEffectAsPasses = {};
  25190. }
  25191. PostProcessRenderEffect.prototype._update = function () {
  25192. for (var renderPassName in this._renderPasses) {
  25193. this._renderPasses[renderPassName]._update();
  25194. }
  25195. };
  25196. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  25197. this._renderPasses[renderPass._name] = renderPass;
  25198. this._linkParameters();
  25199. };
  25200. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  25201. delete this._renderPasses[renderPass._name];
  25202. this._linkParameters();
  25203. };
  25204. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  25205. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  25206. this._linkParameters();
  25207. };
  25208. PostProcessRenderEffect.prototype.getPass = function (passName) {
  25209. for (var renderPassName in this._renderPasses) {
  25210. if (renderPassName === passName) {
  25211. return this._renderPasses[passName];
  25212. }
  25213. }
  25214. };
  25215. PostProcessRenderEffect.prototype.emptyPasses = function () {
  25216. this._renderPasses = {};
  25217. this._linkParameters();
  25218. };
  25219. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  25220. var cameraKey;
  25221. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25222. for (var i = 0; i < _cam.length; i++) {
  25223. var camera = _cam[i];
  25224. var cameraName = camera.name;
  25225. if (this._singleInstance) {
  25226. cameraKey = 0;
  25227. }
  25228. else {
  25229. cameraKey = cameraName;
  25230. }
  25231. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  25232. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  25233. if (!this._indicesForCamera[cameraName]) {
  25234. this._indicesForCamera[cameraName] = [];
  25235. }
  25236. this._indicesForCamera[cameraName].push(index);
  25237. if (this._cameras.indexOf(camera) === -1) {
  25238. this._cameras[cameraName] = camera;
  25239. }
  25240. for (var passName in this._renderPasses) {
  25241. this._renderPasses[passName]._incRefCount();
  25242. }
  25243. }
  25244. this._linkParameters();
  25245. };
  25246. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  25247. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25248. for (var i = 0; i < _cam.length; i++) {
  25249. var camera = _cam[i];
  25250. var cameraName = camera.name;
  25251. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25252. var index = this._cameras.indexOf(cameraName);
  25253. this._indicesForCamera.splice(index, 1);
  25254. this._cameras.splice(index, 1);
  25255. for (var passName in this._renderPasses) {
  25256. this._renderPasses[passName]._decRefCount();
  25257. }
  25258. }
  25259. };
  25260. PostProcessRenderEffect.prototype._enable = function (cameras) {
  25261. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25262. for (var i = 0; i < _cam.length; i++) {
  25263. var camera = _cam[i];
  25264. var cameraName = camera.name;
  25265. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  25266. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  25267. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  25268. }
  25269. }
  25270. for (var passName in this._renderPasses) {
  25271. this._renderPasses[passName]._incRefCount();
  25272. }
  25273. }
  25274. };
  25275. PostProcessRenderEffect.prototype._disable = function (cameras) {
  25276. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25277. for (var i = 0; i < _cam.length; i++) {
  25278. var camera = _cam[i];
  25279. var cameraName = camera.Name;
  25280. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25281. for (var passName in this._renderPasses) {
  25282. this._renderPasses[passName]._decRefCount();
  25283. }
  25284. }
  25285. };
  25286. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  25287. if (this._singleInstance) {
  25288. return this._postProcesses[0];
  25289. }
  25290. else {
  25291. return this._postProcesses[camera.name];
  25292. }
  25293. };
  25294. PostProcessRenderEffect.prototype._linkParameters = function () {
  25295. var _this = this;
  25296. for (var index in this._postProcesses) {
  25297. if (this.applyParameters) {
  25298. this.applyParameters(this._postProcesses[index]);
  25299. }
  25300. this._postProcesses[index].onBeforeRender = function (effect) {
  25301. _this._linkTextures(effect);
  25302. };
  25303. }
  25304. };
  25305. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  25306. for (var renderPassName in this._renderPasses) {
  25307. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  25308. }
  25309. for (var renderEffectName in this._renderEffectAsPasses) {
  25310. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  25311. }
  25312. };
  25313. return PostProcessRenderEffect;
  25314. })();
  25315. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  25316. })(BABYLON || (BABYLON = {}));
  25317. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  25318. var BABYLON;
  25319. (function (BABYLON) {
  25320. var PostProcessRenderPipeline = (function () {
  25321. function PostProcessRenderPipeline(engine, name) {
  25322. this._engine = engine;
  25323. this._name = name;
  25324. this._renderEffects = {};
  25325. this._renderEffectsForIsolatedPass = {};
  25326. this._cameras = [];
  25327. }
  25328. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  25329. this._renderEffects[renderEffect._name] = renderEffect;
  25330. };
  25331. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  25332. var renderEffects = this._renderEffects[renderEffectName];
  25333. if (!renderEffects) {
  25334. return;
  25335. }
  25336. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25337. };
  25338. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  25339. var renderEffects = this._renderEffects[renderEffectName];
  25340. if (!renderEffects) {
  25341. return;
  25342. }
  25343. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25344. };
  25345. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  25346. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25347. var indicesToDelete = [];
  25348. for (var i = 0; i < _cam.length; i++) {
  25349. var camera = _cam[i];
  25350. var cameraName = camera.name;
  25351. if (this._cameras.indexOf(camera) === -1) {
  25352. this._cameras[cameraName] = camera;
  25353. }
  25354. else if (unique) {
  25355. indicesToDelete.push(i);
  25356. }
  25357. }
  25358. for (var i = 0; i < indicesToDelete.length; i++) {
  25359. cameras.splice(indicesToDelete[i], 1);
  25360. }
  25361. for (var renderEffectName in this._renderEffects) {
  25362. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25363. }
  25364. };
  25365. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25366. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25367. for (var renderEffectName in this._renderEffects) {
  25368. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25369. }
  25370. for (var i = 0; i < _cam.length; i++) {
  25371. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25372. }
  25373. };
  25374. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25375. var _this = this;
  25376. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25377. var pass = null;
  25378. for (var renderEffectName in this._renderEffects) {
  25379. pass = this._renderEffects[renderEffectName].getPass(passName);
  25380. if (pass != null) {
  25381. break;
  25382. }
  25383. }
  25384. if (pass === null) {
  25385. return;
  25386. }
  25387. for (var renderEffectName in this._renderEffects) {
  25388. this._renderEffects[renderEffectName]._disable(_cam);
  25389. }
  25390. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25391. for (var i = 0; i < _cam.length; i++) {
  25392. var camera = _cam[i];
  25393. var cameraName = camera.name;
  25394. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  25395. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  25396. });
  25397. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25398. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25399. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25400. }
  25401. };
  25402. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25403. var _this = this;
  25404. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25405. for (var i = 0; i < _cam.length; i++) {
  25406. var camera = _cam[i];
  25407. var cameraName = camera.name;
  25408. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  25409. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  25410. });
  25411. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25412. }
  25413. for (var renderEffectName in this._renderEffects) {
  25414. this._renderEffects[renderEffectName]._enable(_cam);
  25415. }
  25416. };
  25417. PostProcessRenderPipeline.prototype._update = function () {
  25418. for (var renderEffectName in this._renderEffects) {
  25419. this._renderEffects[renderEffectName]._update();
  25420. }
  25421. for (var i = 0; i < this._cameras.length; i++) {
  25422. var cameraName = this._cameras[i].name;
  25423. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25424. this._renderEffectsForIsolatedPass[cameraName]._update();
  25425. }
  25426. }
  25427. };
  25428. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25429. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25430. return PostProcessRenderPipeline;
  25431. })();
  25432. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25433. })(BABYLON || (BABYLON = {}));
  25434. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  25435. var BABYLON;
  25436. (function (BABYLON) {
  25437. var PostProcessRenderPipelineManager = (function () {
  25438. function PostProcessRenderPipelineManager() {
  25439. this._renderPipelines = {};
  25440. }
  25441. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25442. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25443. };
  25444. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25445. var renderPipeline = this._renderPipelines[renderPipelineName];
  25446. if (!renderPipeline) {
  25447. return;
  25448. }
  25449. renderPipeline._attachCameras(cameras, unique);
  25450. };
  25451. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  25452. var renderPipeline = this._renderPipelines[renderPipelineName];
  25453. if (!renderPipeline) {
  25454. return;
  25455. }
  25456. renderPipeline._detachCameras(cameras);
  25457. };
  25458. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25459. var renderPipeline = this._renderPipelines[renderPipelineName];
  25460. if (!renderPipeline) {
  25461. return;
  25462. }
  25463. renderPipeline._enableEffect(renderEffectName, cameras);
  25464. };
  25465. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25466. var renderPipeline = this._renderPipelines[renderPipelineName];
  25467. if (!renderPipeline) {
  25468. return;
  25469. }
  25470. renderPipeline._disableEffect(renderEffectName, cameras);
  25471. };
  25472. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  25473. var renderPipeline = this._renderPipelines[renderPipelineName];
  25474. if (!renderPipeline) {
  25475. return;
  25476. }
  25477. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  25478. };
  25479. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  25480. var renderPipeline = this._renderPipelines[renderPipelineName];
  25481. if (!renderPipeline) {
  25482. return;
  25483. }
  25484. renderPipeline._disableDisplayOnlyPass(cameras);
  25485. };
  25486. PostProcessRenderPipelineManager.prototype.update = function () {
  25487. for (var renderPipelineName in this._renderPipelines) {
  25488. this._renderPipelines[renderPipelineName]._update();
  25489. }
  25490. };
  25491. return PostProcessRenderPipelineManager;
  25492. })();
  25493. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25494. })(BABYLON || (BABYLON = {}));
  25495. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  25496. var __extends = this.__extends || function (d, b) {
  25497. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25498. function __() { this.constructor = d; }
  25499. __.prototype = b.prototype;
  25500. d.prototype = new __();
  25501. };
  25502. var BABYLON;
  25503. (function (BABYLON) {
  25504. var DisplayPassPostProcess = (function (_super) {
  25505. __extends(DisplayPassPostProcess, _super);
  25506. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  25507. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  25508. }
  25509. return DisplayPassPostProcess;
  25510. })(BABYLON.PostProcess);
  25511. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  25512. })(BABYLON || (BABYLON = {}));
  25513. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  25514. var BABYLON;
  25515. (function (BABYLON) {
  25516. var BoundingBoxRenderer = (function () {
  25517. function BoundingBoxRenderer(scene) {
  25518. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25519. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25520. this.showBackLines = true;
  25521. this.renderList = new BABYLON.SmartArray(32);
  25522. this._scene = scene;
  25523. }
  25524. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25525. if (this._colorShader) {
  25526. return;
  25527. }
  25528. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25529. attributes: ["position"],
  25530. uniforms: ["worldViewProjection", "color"]
  25531. });
  25532. var engine = this._scene.getEngine();
  25533. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25534. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25535. 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]);
  25536. };
  25537. BoundingBoxRenderer.prototype.reset = function () {
  25538. this.renderList.reset();
  25539. };
  25540. BoundingBoxRenderer.prototype.render = function () {
  25541. if (this.renderList.length === 0) {
  25542. return;
  25543. }
  25544. this._prepareRessources();
  25545. if (!this._colorShader.isReady()) {
  25546. return;
  25547. }
  25548. var engine = this._scene.getEngine();
  25549. engine.setDepthWrite(false);
  25550. this._colorShader._preBind();
  25551. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25552. var boundingBox = this.renderList.data[boundingBoxIndex];
  25553. var min = boundingBox.minimum;
  25554. var max = boundingBox.maximum;
  25555. var diff = max.subtract(min);
  25556. var median = min.add(diff.scale(0.5));
  25557. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  25558. // VBOs
  25559. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25560. if (this.showBackLines) {
  25561. // Back
  25562. engine.setDepthFunctionToGreaterOrEqual();
  25563. this._scene.resetCachedMaterial();
  25564. this._colorShader.setColor4("color", this.backColor.toColor4());
  25565. this._colorShader.bind(worldMatrix);
  25566. // Draw order
  25567. engine.draw(false, 0, 24);
  25568. }
  25569. // Front
  25570. engine.setDepthFunctionToLess();
  25571. this._scene.resetCachedMaterial();
  25572. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25573. this._colorShader.bind(worldMatrix);
  25574. // Draw order
  25575. engine.draw(false, 0, 24);
  25576. }
  25577. this._colorShader.unbind();
  25578. engine.setDepthFunctionToLessOrEqual();
  25579. engine.setDepthWrite(true);
  25580. };
  25581. BoundingBoxRenderer.prototype.dispose = function () {
  25582. if (!this._colorShader) {
  25583. return;
  25584. }
  25585. this._colorShader.dispose();
  25586. this._vb.dispose();
  25587. this._scene.getEngine()._releaseBuffer(this._ib);
  25588. };
  25589. return BoundingBoxRenderer;
  25590. })();
  25591. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25592. })(BABYLON || (BABYLON = {}));
  25593. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  25594. var __extends = this.__extends || function (d, b) {
  25595. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25596. function __() { this.constructor = d; }
  25597. __.prototype = b.prototype;
  25598. d.prototype = new __();
  25599. };
  25600. var BABYLON;
  25601. (function (BABYLON) {
  25602. var Condition = (function () {
  25603. function Condition(actionManager) {
  25604. this._actionManager = actionManager;
  25605. }
  25606. Condition.prototype.isValid = function () {
  25607. return true;
  25608. };
  25609. Condition.prototype._getProperty = function (propertyPath) {
  25610. return this._actionManager._getProperty(propertyPath);
  25611. };
  25612. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25613. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25614. };
  25615. return Condition;
  25616. })();
  25617. BABYLON.Condition = Condition;
  25618. var ValueCondition = (function (_super) {
  25619. __extends(ValueCondition, _super);
  25620. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25621. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25622. _super.call(this, actionManager);
  25623. this.propertyPath = propertyPath;
  25624. this.value = value;
  25625. this.operator = operator;
  25626. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25627. this._property = this._getProperty(this.propertyPath);
  25628. }
  25629. Object.defineProperty(ValueCondition, "IsEqual", {
  25630. get: function () {
  25631. return ValueCondition._IsEqual;
  25632. },
  25633. enumerable: true,
  25634. configurable: true
  25635. });
  25636. Object.defineProperty(ValueCondition, "IsDifferent", {
  25637. get: function () {
  25638. return ValueCondition._IsDifferent;
  25639. },
  25640. enumerable: true,
  25641. configurable: true
  25642. });
  25643. Object.defineProperty(ValueCondition, "IsGreater", {
  25644. get: function () {
  25645. return ValueCondition._IsGreater;
  25646. },
  25647. enumerable: true,
  25648. configurable: true
  25649. });
  25650. Object.defineProperty(ValueCondition, "IsLesser", {
  25651. get: function () {
  25652. return ValueCondition._IsLesser;
  25653. },
  25654. enumerable: true,
  25655. configurable: true
  25656. });
  25657. // Methods
  25658. ValueCondition.prototype.isValid = function () {
  25659. switch (this.operator) {
  25660. case ValueCondition.IsGreater:
  25661. return this._target[this._property] > this.value;
  25662. case ValueCondition.IsLesser:
  25663. return this._target[this._property] < this.value;
  25664. case ValueCondition.IsEqual:
  25665. case ValueCondition.IsDifferent:
  25666. var check;
  25667. if (this.value.equals) {
  25668. check = this.value.equals(this._target[this._property]);
  25669. }
  25670. else {
  25671. check = this.value === this._target[this._property];
  25672. }
  25673. return this.operator === ValueCondition.IsEqual ? check : !check;
  25674. }
  25675. return false;
  25676. };
  25677. // Statics
  25678. ValueCondition._IsEqual = 0;
  25679. ValueCondition._IsDifferent = 1;
  25680. ValueCondition._IsGreater = 2;
  25681. ValueCondition._IsLesser = 3;
  25682. return ValueCondition;
  25683. })(Condition);
  25684. BABYLON.ValueCondition = ValueCondition;
  25685. var PredicateCondition = (function (_super) {
  25686. __extends(PredicateCondition, _super);
  25687. function PredicateCondition(actionManager, predicate) {
  25688. _super.call(this, actionManager);
  25689. this.predicate = predicate;
  25690. }
  25691. PredicateCondition.prototype.isValid = function () {
  25692. return this.predicate();
  25693. };
  25694. return PredicateCondition;
  25695. })(Condition);
  25696. BABYLON.PredicateCondition = PredicateCondition;
  25697. var StateCondition = (function (_super) {
  25698. __extends(StateCondition, _super);
  25699. function StateCondition(actionManager, target, value) {
  25700. _super.call(this, actionManager);
  25701. this.value = value;
  25702. this._target = target;
  25703. }
  25704. // Methods
  25705. StateCondition.prototype.isValid = function () {
  25706. return this._target.state === this.value;
  25707. };
  25708. return StateCondition;
  25709. })(Condition);
  25710. BABYLON.StateCondition = StateCondition;
  25711. })(BABYLON || (BABYLON = {}));
  25712. //# sourceMappingURL=babylon.condition.js.map
  25713. var BABYLON;
  25714. (function (BABYLON) {
  25715. var Action = (function () {
  25716. function Action(triggerOptions, condition) {
  25717. this.triggerOptions = triggerOptions;
  25718. if (triggerOptions.parameter) {
  25719. this.trigger = triggerOptions.trigger;
  25720. this._triggerParameter = triggerOptions.parameter;
  25721. }
  25722. else {
  25723. this.trigger = triggerOptions;
  25724. }
  25725. this._nextActiveAction = this;
  25726. this._condition = condition;
  25727. }
  25728. // Methods
  25729. Action.prototype._prepare = function () {
  25730. };
  25731. Action.prototype.getTriggerParameter = function () {
  25732. return this._triggerParameter;
  25733. };
  25734. Action.prototype._executeCurrent = function (evt) {
  25735. if (this._nextActiveAction._condition) {
  25736. var condition = this._nextActiveAction._condition;
  25737. var currentRenderId = this._actionManager.getScene().getRenderId();
  25738. // We cache the current evaluation for the current frame
  25739. if (condition._evaluationId === currentRenderId) {
  25740. if (!condition._currentResult) {
  25741. return;
  25742. }
  25743. }
  25744. else {
  25745. condition._evaluationId = currentRenderId;
  25746. if (!condition.isValid()) {
  25747. condition._currentResult = false;
  25748. return;
  25749. }
  25750. condition._currentResult = true;
  25751. }
  25752. }
  25753. this._nextActiveAction.execute(evt);
  25754. if (this._nextActiveAction._child) {
  25755. if (!this._nextActiveAction._child._actionManager) {
  25756. this._nextActiveAction._child._actionManager = this._actionManager;
  25757. }
  25758. this._nextActiveAction = this._nextActiveAction._child;
  25759. }
  25760. else {
  25761. this._nextActiveAction = this;
  25762. }
  25763. };
  25764. Action.prototype.execute = function (evt) {
  25765. };
  25766. Action.prototype.then = function (action) {
  25767. this._child = action;
  25768. action._actionManager = this._actionManager;
  25769. action._prepare();
  25770. return action;
  25771. };
  25772. Action.prototype._getProperty = function (propertyPath) {
  25773. return this._actionManager._getProperty(propertyPath);
  25774. };
  25775. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25776. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25777. };
  25778. return Action;
  25779. })();
  25780. BABYLON.Action = Action;
  25781. })(BABYLON || (BABYLON = {}));
  25782. //# sourceMappingURL=babylon.action.js.map
  25783. var BABYLON;
  25784. (function (BABYLON) {
  25785. /**
  25786. * ActionEvent is the event beint sent when an action is triggered.
  25787. */
  25788. var ActionEvent = (function () {
  25789. /**
  25790. * @constructor
  25791. * @param source The mesh that triggered the action.
  25792. * @param pointerX the X mouse cursor position at the time of the event
  25793. * @param pointerY the Y mouse cursor position at the time of the event
  25794. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25795. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25796. */
  25797. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  25798. this.source = source;
  25799. this.pointerX = pointerX;
  25800. this.pointerY = pointerY;
  25801. this.meshUnderPointer = meshUnderPointer;
  25802. this.sourceEvent = sourceEvent;
  25803. }
  25804. /**
  25805. * Helper function to auto-create an ActionEvent from a source mesh.
  25806. * @param source the source mesh that triggered the event
  25807. * @param evt {Event} The original (browser) event
  25808. */
  25809. ActionEvent.CreateNew = function (source, evt) {
  25810. var scene = source.getScene();
  25811. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25812. };
  25813. /**
  25814. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25815. * @param scene the scene where the event occurred
  25816. * @param evt {Event} The original (browser) event
  25817. */
  25818. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25819. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25820. };
  25821. return ActionEvent;
  25822. })();
  25823. BABYLON.ActionEvent = ActionEvent;
  25824. /**
  25825. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25826. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25827. */
  25828. var ActionManager = (function () {
  25829. function ActionManager(scene) {
  25830. // Members
  25831. this.actions = new Array();
  25832. this._scene = scene;
  25833. scene._actionManagers.push(this);
  25834. }
  25835. Object.defineProperty(ActionManager, "NothingTrigger", {
  25836. get: function () {
  25837. return ActionManager._NothingTrigger;
  25838. },
  25839. enumerable: true,
  25840. configurable: true
  25841. });
  25842. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25843. get: function () {
  25844. return ActionManager._OnPickTrigger;
  25845. },
  25846. enumerable: true,
  25847. configurable: true
  25848. });
  25849. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25850. get: function () {
  25851. return ActionManager._OnLeftPickTrigger;
  25852. },
  25853. enumerable: true,
  25854. configurable: true
  25855. });
  25856. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25857. get: function () {
  25858. return ActionManager._OnRightPickTrigger;
  25859. },
  25860. enumerable: true,
  25861. configurable: true
  25862. });
  25863. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25864. get: function () {
  25865. return ActionManager._OnCenterPickTrigger;
  25866. },
  25867. enumerable: true,
  25868. configurable: true
  25869. });
  25870. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25871. get: function () {
  25872. return ActionManager._OnPointerOverTrigger;
  25873. },
  25874. enumerable: true,
  25875. configurable: true
  25876. });
  25877. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25878. get: function () {
  25879. return ActionManager._OnPointerOutTrigger;
  25880. },
  25881. enumerable: true,
  25882. configurable: true
  25883. });
  25884. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25885. get: function () {
  25886. return ActionManager._OnEveryFrameTrigger;
  25887. },
  25888. enumerable: true,
  25889. configurable: true
  25890. });
  25891. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25892. get: function () {
  25893. return ActionManager._OnIntersectionEnterTrigger;
  25894. },
  25895. enumerable: true,
  25896. configurable: true
  25897. });
  25898. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25899. get: function () {
  25900. return ActionManager._OnIntersectionExitTrigger;
  25901. },
  25902. enumerable: true,
  25903. configurable: true
  25904. });
  25905. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25906. get: function () {
  25907. return ActionManager._OnKeyDownTrigger;
  25908. },
  25909. enumerable: true,
  25910. configurable: true
  25911. });
  25912. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25913. get: function () {
  25914. return ActionManager._OnKeyUpTrigger;
  25915. },
  25916. enumerable: true,
  25917. configurable: true
  25918. });
  25919. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25920. get: function () {
  25921. return ActionManager._OnPickUpTrigger;
  25922. },
  25923. enumerable: true,
  25924. configurable: true
  25925. });
  25926. // Methods
  25927. ActionManager.prototype.dispose = function () {
  25928. var index = this._scene._actionManagers.indexOf(this);
  25929. if (index > -1) {
  25930. this._scene._actionManagers.splice(index, 1);
  25931. }
  25932. };
  25933. ActionManager.prototype.getScene = function () {
  25934. return this._scene;
  25935. };
  25936. /**
  25937. * Does this action manager handles actions of any of the given triggers
  25938. * @param {number[]} triggers - the triggers to be tested
  25939. * @return {boolean} whether one (or more) of the triggers is handeled
  25940. */
  25941. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25942. for (var index = 0; index < this.actions.length; index++) {
  25943. var action = this.actions[index];
  25944. if (triggers.indexOf(action.trigger) > -1) {
  25945. return true;
  25946. }
  25947. }
  25948. return false;
  25949. };
  25950. /**
  25951. * Does this action manager handles actions of a given trigger
  25952. * @param {number} trigger - the trigger to be tested
  25953. * @return {boolean} whether the trigger is handeled
  25954. */
  25955. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25956. for (var index = 0; index < this.actions.length; index++) {
  25957. var action = this.actions[index];
  25958. if (action.trigger === trigger) {
  25959. return true;
  25960. }
  25961. }
  25962. return false;
  25963. };
  25964. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25965. /**
  25966. * Does this action manager has pointer triggers
  25967. * @return {boolean} whether or not it has pointer triggers
  25968. */
  25969. get: function () {
  25970. for (var index = 0; index < this.actions.length; index++) {
  25971. var action = this.actions[index];
  25972. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25973. return true;
  25974. }
  25975. if (action.trigger == ActionManager._OnPickUpTrigger) {
  25976. return true;
  25977. }
  25978. }
  25979. return false;
  25980. },
  25981. enumerable: true,
  25982. configurable: true
  25983. });
  25984. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25985. /**
  25986. * Does this action manager has pick triggers
  25987. * @return {boolean} whether or not it has pick triggers
  25988. */
  25989. get: function () {
  25990. for (var index = 0; index < this.actions.length; index++) {
  25991. var action = this.actions[index];
  25992. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25993. return true;
  25994. }
  25995. }
  25996. return false;
  25997. },
  25998. enumerable: true,
  25999. configurable: true
  26000. });
  26001. /**
  26002. * Registers an action to this action manager
  26003. * @param {BABYLON.Action} action - the action to be registered
  26004. * @return {BABYLON.Action} the action amended (prepared) after registration
  26005. */
  26006. ActionManager.prototype.registerAction = function (action) {
  26007. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26008. if (this.getScene().actionManager !== this) {
  26009. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26010. return null;
  26011. }
  26012. }
  26013. this.actions.push(action);
  26014. action._actionManager = this;
  26015. action._prepare();
  26016. return action;
  26017. };
  26018. /**
  26019. * Process a specific trigger
  26020. * @param {number} trigger - the trigger to process
  26021. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26022. */
  26023. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26024. for (var index = 0; index < this.actions.length; index++) {
  26025. var action = this.actions[index];
  26026. if (action.trigger === trigger) {
  26027. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  26028. var parameter = action.getTriggerParameter();
  26029. if (parameter) {
  26030. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26031. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26032. if (actualkey !== parameter.toLowerCase()) {
  26033. continue;
  26034. }
  26035. }
  26036. }
  26037. action._executeCurrent(evt);
  26038. }
  26039. }
  26040. };
  26041. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26042. var properties = propertyPath.split(".");
  26043. for (var index = 0; index < properties.length - 1; index++) {
  26044. target = target[properties[index]];
  26045. }
  26046. return target;
  26047. };
  26048. ActionManager.prototype._getProperty = function (propertyPath) {
  26049. var properties = propertyPath.split(".");
  26050. return properties[properties.length - 1];
  26051. };
  26052. // Statics
  26053. ActionManager._NothingTrigger = 0;
  26054. ActionManager._OnPickTrigger = 1;
  26055. ActionManager._OnLeftPickTrigger = 2;
  26056. ActionManager._OnRightPickTrigger = 3;
  26057. ActionManager._OnCenterPickTrigger = 4;
  26058. ActionManager._OnPointerOverTrigger = 5;
  26059. ActionManager._OnPointerOutTrigger = 6;
  26060. ActionManager._OnEveryFrameTrigger = 7;
  26061. ActionManager._OnIntersectionEnterTrigger = 8;
  26062. ActionManager._OnIntersectionExitTrigger = 9;
  26063. ActionManager._OnKeyDownTrigger = 10;
  26064. ActionManager._OnKeyUpTrigger = 11;
  26065. ActionManager._OnPickUpTrigger = 12;
  26066. return ActionManager;
  26067. })();
  26068. BABYLON.ActionManager = ActionManager;
  26069. })(BABYLON || (BABYLON = {}));
  26070. //# sourceMappingURL=babylon.actionManager.js.map
  26071. var __extends = this.__extends || function (d, b) {
  26072. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26073. function __() { this.constructor = d; }
  26074. __.prototype = b.prototype;
  26075. d.prototype = new __();
  26076. };
  26077. var BABYLON;
  26078. (function (BABYLON) {
  26079. var InterpolateValueAction = (function (_super) {
  26080. __extends(InterpolateValueAction, _super);
  26081. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  26082. if (duration === void 0) { duration = 1000; }
  26083. _super.call(this, triggerOptions, condition);
  26084. this.propertyPath = propertyPath;
  26085. this.value = value;
  26086. this.duration = duration;
  26087. this.stopOtherAnimations = stopOtherAnimations;
  26088. this._target = target;
  26089. }
  26090. InterpolateValueAction.prototype._prepare = function () {
  26091. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26092. this._property = this._getProperty(this.propertyPath);
  26093. };
  26094. InterpolateValueAction.prototype.execute = function () {
  26095. var scene = this._actionManager.getScene();
  26096. var keys = [
  26097. {
  26098. frame: 0,
  26099. value: this._target[this._property]
  26100. },
  26101. {
  26102. frame: 100,
  26103. value: this.value
  26104. }
  26105. ];
  26106. var dataType;
  26107. if (typeof this.value === "number") {
  26108. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  26109. }
  26110. else if (this.value instanceof BABYLON.Color3) {
  26111. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  26112. }
  26113. else if (this.value instanceof BABYLON.Vector3) {
  26114. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  26115. }
  26116. else if (this.value instanceof BABYLON.Matrix) {
  26117. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  26118. }
  26119. else if (this.value instanceof BABYLON.Quaternion) {
  26120. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  26121. }
  26122. else {
  26123. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  26124. return;
  26125. }
  26126. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  26127. animation.setKeys(keys);
  26128. if (this.stopOtherAnimations) {
  26129. scene.stopAnimation(this._target);
  26130. }
  26131. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  26132. };
  26133. return InterpolateValueAction;
  26134. })(BABYLON.Action);
  26135. BABYLON.InterpolateValueAction = InterpolateValueAction;
  26136. })(BABYLON || (BABYLON = {}));
  26137. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  26138. var __extends = this.__extends || function (d, b) {
  26139. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26140. function __() { this.constructor = d; }
  26141. __.prototype = b.prototype;
  26142. d.prototype = new __();
  26143. };
  26144. var BABYLON;
  26145. (function (BABYLON) {
  26146. var SwitchBooleanAction = (function (_super) {
  26147. __extends(SwitchBooleanAction, _super);
  26148. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  26149. _super.call(this, triggerOptions, condition);
  26150. this.propertyPath = propertyPath;
  26151. this._target = target;
  26152. }
  26153. SwitchBooleanAction.prototype._prepare = function () {
  26154. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26155. this._property = this._getProperty(this.propertyPath);
  26156. };
  26157. SwitchBooleanAction.prototype.execute = function () {
  26158. this._target[this._property] = !this._target[this._property];
  26159. };
  26160. return SwitchBooleanAction;
  26161. })(BABYLON.Action);
  26162. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  26163. var SetStateAction = (function (_super) {
  26164. __extends(SetStateAction, _super);
  26165. function SetStateAction(triggerOptions, target, value, condition) {
  26166. _super.call(this, triggerOptions, condition);
  26167. this.value = value;
  26168. this._target = target;
  26169. }
  26170. SetStateAction.prototype.execute = function () {
  26171. this._target.state = this.value;
  26172. };
  26173. return SetStateAction;
  26174. })(BABYLON.Action);
  26175. BABYLON.SetStateAction = SetStateAction;
  26176. var SetValueAction = (function (_super) {
  26177. __extends(SetValueAction, _super);
  26178. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  26179. _super.call(this, triggerOptions, condition);
  26180. this.propertyPath = propertyPath;
  26181. this.value = value;
  26182. this._target = target;
  26183. }
  26184. SetValueAction.prototype._prepare = function () {
  26185. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26186. this._property = this._getProperty(this.propertyPath);
  26187. };
  26188. SetValueAction.prototype.execute = function () {
  26189. this._target[this._property] = this.value;
  26190. };
  26191. return SetValueAction;
  26192. })(BABYLON.Action);
  26193. BABYLON.SetValueAction = SetValueAction;
  26194. var IncrementValueAction = (function (_super) {
  26195. __extends(IncrementValueAction, _super);
  26196. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  26197. _super.call(this, triggerOptions, condition);
  26198. this.propertyPath = propertyPath;
  26199. this.value = value;
  26200. this._target = target;
  26201. }
  26202. IncrementValueAction.prototype._prepare = function () {
  26203. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26204. this._property = this._getProperty(this.propertyPath);
  26205. if (typeof this._target[this._property] !== "number") {
  26206. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  26207. }
  26208. };
  26209. IncrementValueAction.prototype.execute = function () {
  26210. this._target[this._property] += this.value;
  26211. };
  26212. return IncrementValueAction;
  26213. })(BABYLON.Action);
  26214. BABYLON.IncrementValueAction = IncrementValueAction;
  26215. var PlayAnimationAction = (function (_super) {
  26216. __extends(PlayAnimationAction, _super);
  26217. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  26218. _super.call(this, triggerOptions, condition);
  26219. this.from = from;
  26220. this.to = to;
  26221. this.loop = loop;
  26222. this._target = target;
  26223. }
  26224. PlayAnimationAction.prototype._prepare = function () {
  26225. };
  26226. PlayAnimationAction.prototype.execute = function () {
  26227. var scene = this._actionManager.getScene();
  26228. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  26229. };
  26230. return PlayAnimationAction;
  26231. })(BABYLON.Action);
  26232. BABYLON.PlayAnimationAction = PlayAnimationAction;
  26233. var StopAnimationAction = (function (_super) {
  26234. __extends(StopAnimationAction, _super);
  26235. function StopAnimationAction(triggerOptions, target, condition) {
  26236. _super.call(this, triggerOptions, condition);
  26237. this._target = target;
  26238. }
  26239. StopAnimationAction.prototype._prepare = function () {
  26240. };
  26241. StopAnimationAction.prototype.execute = function () {
  26242. var scene = this._actionManager.getScene();
  26243. scene.stopAnimation(this._target);
  26244. };
  26245. return StopAnimationAction;
  26246. })(BABYLON.Action);
  26247. BABYLON.StopAnimationAction = StopAnimationAction;
  26248. var DoNothingAction = (function (_super) {
  26249. __extends(DoNothingAction, _super);
  26250. function DoNothingAction(triggerOptions, condition) {
  26251. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  26252. _super.call(this, triggerOptions, condition);
  26253. }
  26254. DoNothingAction.prototype.execute = function () {
  26255. };
  26256. return DoNothingAction;
  26257. })(BABYLON.Action);
  26258. BABYLON.DoNothingAction = DoNothingAction;
  26259. var CombineAction = (function (_super) {
  26260. __extends(CombineAction, _super);
  26261. function CombineAction(triggerOptions, children, condition) {
  26262. _super.call(this, triggerOptions, condition);
  26263. this.children = children;
  26264. }
  26265. CombineAction.prototype._prepare = function () {
  26266. for (var index = 0; index < this.children.length; index++) {
  26267. this.children[index]._actionManager = this._actionManager;
  26268. this.children[index]._prepare();
  26269. }
  26270. };
  26271. CombineAction.prototype.execute = function (evt) {
  26272. for (var index = 0; index < this.children.length; index++) {
  26273. this.children[index].execute(evt);
  26274. }
  26275. };
  26276. return CombineAction;
  26277. })(BABYLON.Action);
  26278. BABYLON.CombineAction = CombineAction;
  26279. var ExecuteCodeAction = (function (_super) {
  26280. __extends(ExecuteCodeAction, _super);
  26281. function ExecuteCodeAction(triggerOptions, func, condition) {
  26282. _super.call(this, triggerOptions, condition);
  26283. this.func = func;
  26284. }
  26285. ExecuteCodeAction.prototype.execute = function (evt) {
  26286. this.func(evt);
  26287. };
  26288. return ExecuteCodeAction;
  26289. })(BABYLON.Action);
  26290. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  26291. var SetParentAction = (function (_super) {
  26292. __extends(SetParentAction, _super);
  26293. function SetParentAction(triggerOptions, target, parent, condition) {
  26294. _super.call(this, triggerOptions, condition);
  26295. this._target = target;
  26296. this._parent = parent;
  26297. }
  26298. SetParentAction.prototype._prepare = function () {
  26299. };
  26300. SetParentAction.prototype.execute = function () {
  26301. if (this._target.parent === this._parent) {
  26302. return;
  26303. }
  26304. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  26305. invertParentWorldMatrix.invert();
  26306. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  26307. this._target.parent = this._parent;
  26308. };
  26309. return SetParentAction;
  26310. })(BABYLON.Action);
  26311. BABYLON.SetParentAction = SetParentAction;
  26312. var PlaySoundAction = (function (_super) {
  26313. __extends(PlaySoundAction, _super);
  26314. function PlaySoundAction(triggerOptions, sound, condition) {
  26315. _super.call(this, triggerOptions, condition);
  26316. this._sound = sound;
  26317. }
  26318. PlaySoundAction.prototype._prepare = function () {
  26319. };
  26320. PlaySoundAction.prototype.execute = function () {
  26321. if (this._sound !== undefined)
  26322. this._sound.play();
  26323. };
  26324. return PlaySoundAction;
  26325. })(BABYLON.Action);
  26326. BABYLON.PlaySoundAction = PlaySoundAction;
  26327. var StopSoundAction = (function (_super) {
  26328. __extends(StopSoundAction, _super);
  26329. function StopSoundAction(triggerOptions, sound, condition) {
  26330. _super.call(this, triggerOptions, condition);
  26331. this._sound = sound;
  26332. }
  26333. StopSoundAction.prototype._prepare = function () {
  26334. };
  26335. StopSoundAction.prototype.execute = function () {
  26336. if (this._sound !== undefined)
  26337. this._sound.stop();
  26338. };
  26339. return StopSoundAction;
  26340. })(BABYLON.Action);
  26341. BABYLON.StopSoundAction = StopSoundAction;
  26342. })(BABYLON || (BABYLON = {}));
  26343. //# sourceMappingURL=babylon.directActions.js.map
  26344. var __extends = this.__extends || function (d, b) {
  26345. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26346. function __() { this.constructor = d; }
  26347. __.prototype = b.prototype;
  26348. d.prototype = new __();
  26349. };
  26350. var BABYLON;
  26351. (function (BABYLON) {
  26352. var Geometry = (function () {
  26353. function Geometry(id, scene, vertexData, updatable, mesh) {
  26354. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26355. this._totalVertices = 0;
  26356. this._indices = [];
  26357. this._isDisposed = false;
  26358. this.id = id;
  26359. this._engine = scene.getEngine();
  26360. this._meshes = [];
  26361. this._scene = scene;
  26362. // vertexData
  26363. if (vertexData) {
  26364. this.setAllVerticesData(vertexData, updatable);
  26365. }
  26366. else {
  26367. this._totalVertices = 0;
  26368. this._indices = [];
  26369. }
  26370. // applyToMesh
  26371. if (mesh) {
  26372. this.applyToMesh(mesh);
  26373. mesh.computeWorldMatrix(true);
  26374. }
  26375. }
  26376. Geometry.prototype.getScene = function () {
  26377. return this._scene;
  26378. };
  26379. Geometry.prototype.getEngine = function () {
  26380. return this._engine;
  26381. };
  26382. Geometry.prototype.isReady = function () {
  26383. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26384. };
  26385. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26386. vertexData.applyToGeometry(this, updatable);
  26387. this.notifyUpdate();
  26388. };
  26389. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26390. this._vertexBuffers = this._vertexBuffers || {};
  26391. if (this._vertexBuffers[kind]) {
  26392. this._vertexBuffers[kind].dispose();
  26393. }
  26394. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26395. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26396. stride = this._vertexBuffers[kind].getStrideSize();
  26397. this._totalVertices = data.length / stride;
  26398. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26399. var meshes = this._meshes;
  26400. var numOfMeshes = meshes.length;
  26401. for (var index = 0; index < numOfMeshes; index++) {
  26402. var mesh = meshes[index];
  26403. mesh._resetPointsArrayCache();
  26404. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26405. mesh._createGlobalSubMesh();
  26406. mesh.computeWorldMatrix(true);
  26407. }
  26408. }
  26409. this.notifyUpdate(kind);
  26410. };
  26411. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26412. var vertexBuffer = this.getVertexBuffer(kind);
  26413. if (!vertexBuffer) {
  26414. return;
  26415. }
  26416. vertexBuffer.updateDirectly(data, offset);
  26417. this.notifyUpdate(kind);
  26418. };
  26419. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26420. var vertexBuffer = this.getVertexBuffer(kind);
  26421. if (!vertexBuffer) {
  26422. return;
  26423. }
  26424. vertexBuffer.update(data);
  26425. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26426. var extend;
  26427. var stride = vertexBuffer.getStrideSize();
  26428. this._totalVertices = data.length / stride;
  26429. if (updateExtends) {
  26430. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26431. }
  26432. var meshes = this._meshes;
  26433. var numOfMeshes = meshes.length;
  26434. for (var index = 0; index < numOfMeshes; index++) {
  26435. var mesh = meshes[index];
  26436. mesh._resetPointsArrayCache();
  26437. if (updateExtends) {
  26438. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26439. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26440. var subMesh = mesh.subMeshes[subIndex];
  26441. subMesh.refreshBoundingInfo();
  26442. }
  26443. }
  26444. }
  26445. }
  26446. this.notifyUpdate(kind);
  26447. };
  26448. Geometry.prototype.getTotalVertices = function () {
  26449. if (!this.isReady()) {
  26450. return 0;
  26451. }
  26452. return this._totalVertices;
  26453. };
  26454. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26455. var vertexBuffer = this.getVertexBuffer(kind);
  26456. if (!vertexBuffer) {
  26457. return null;
  26458. }
  26459. var orig = vertexBuffer.getData();
  26460. if (!copyWhenShared || this._meshes.length === 1) {
  26461. return orig;
  26462. }
  26463. else {
  26464. var len = orig.length;
  26465. var copy = [];
  26466. for (var i = 0; i < len; i++) {
  26467. copy.push(orig[i]);
  26468. }
  26469. return copy;
  26470. }
  26471. };
  26472. Geometry.prototype.getVertexBuffer = function (kind) {
  26473. if (!this.isReady()) {
  26474. return null;
  26475. }
  26476. return this._vertexBuffers[kind];
  26477. };
  26478. Geometry.prototype.getVertexBuffers = function () {
  26479. if (!this.isReady()) {
  26480. return null;
  26481. }
  26482. return this._vertexBuffers;
  26483. };
  26484. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26485. if (!this._vertexBuffers) {
  26486. if (this._delayInfo) {
  26487. return this._delayInfo.indexOf(kind) !== -1;
  26488. }
  26489. return false;
  26490. }
  26491. return this._vertexBuffers[kind] !== undefined;
  26492. };
  26493. Geometry.prototype.getVerticesDataKinds = function () {
  26494. var result = [];
  26495. if (!this._vertexBuffers && this._delayInfo) {
  26496. for (var kind in this._delayInfo) {
  26497. result.push(kind);
  26498. }
  26499. }
  26500. else {
  26501. for (kind in this._vertexBuffers) {
  26502. result.push(kind);
  26503. }
  26504. }
  26505. return result;
  26506. };
  26507. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26508. if (this._indexBuffer) {
  26509. this._engine._releaseBuffer(this._indexBuffer);
  26510. }
  26511. this._indices = indices;
  26512. if (this._meshes.length !== 0 && this._indices) {
  26513. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26514. }
  26515. if (totalVertices !== undefined) {
  26516. this._totalVertices = totalVertices;
  26517. }
  26518. var meshes = this._meshes;
  26519. var numOfMeshes = meshes.length;
  26520. for (var index = 0; index < numOfMeshes; index++) {
  26521. meshes[index]._createGlobalSubMesh();
  26522. }
  26523. this.notifyUpdate();
  26524. };
  26525. Geometry.prototype.getTotalIndices = function () {
  26526. if (!this.isReady()) {
  26527. return 0;
  26528. }
  26529. return this._indices.length;
  26530. };
  26531. Geometry.prototype.getIndices = function (copyWhenShared) {
  26532. if (!this.isReady()) {
  26533. return null;
  26534. }
  26535. var orig = this._indices;
  26536. if (!copyWhenShared || this._meshes.length === 1) {
  26537. return orig;
  26538. }
  26539. else {
  26540. var len = orig.length;
  26541. var copy = [];
  26542. for (var i = 0; i < len; i++) {
  26543. copy.push(orig[i]);
  26544. }
  26545. return copy;
  26546. }
  26547. };
  26548. Geometry.prototype.getIndexBuffer = function () {
  26549. if (!this.isReady()) {
  26550. return null;
  26551. }
  26552. return this._indexBuffer;
  26553. };
  26554. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26555. var meshes = this._meshes;
  26556. var index = meshes.indexOf(mesh);
  26557. if (index === -1) {
  26558. return;
  26559. }
  26560. for (var kind in this._vertexBuffers) {
  26561. this._vertexBuffers[kind].dispose();
  26562. }
  26563. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26564. this._indexBuffer = null;
  26565. }
  26566. meshes.splice(index, 1);
  26567. mesh._geometry = null;
  26568. if (meshes.length === 0 && shouldDispose) {
  26569. this.dispose();
  26570. }
  26571. };
  26572. Geometry.prototype.applyToMesh = function (mesh) {
  26573. if (mesh._geometry === this) {
  26574. return;
  26575. }
  26576. var previousGeometry = mesh._geometry;
  26577. if (previousGeometry) {
  26578. previousGeometry.releaseForMesh(mesh);
  26579. }
  26580. var meshes = this._meshes;
  26581. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26582. mesh._geometry = this;
  26583. this._scene.pushGeometry(this);
  26584. meshes.push(mesh);
  26585. if (this.isReady()) {
  26586. this._applyToMesh(mesh);
  26587. }
  26588. else {
  26589. mesh._boundingInfo = this._boundingInfo;
  26590. }
  26591. };
  26592. Geometry.prototype._applyToMesh = function (mesh) {
  26593. var numOfMeshes = this._meshes.length;
  26594. for (var kind in this._vertexBuffers) {
  26595. if (numOfMeshes === 1) {
  26596. this._vertexBuffers[kind].create();
  26597. }
  26598. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26599. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26600. mesh._resetPointsArrayCache();
  26601. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26602. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26603. mesh._createGlobalSubMesh();
  26604. //bounding info was just created again, world matrix should be applied again.
  26605. mesh._updateBoundingInfo();
  26606. }
  26607. }
  26608. // indexBuffer
  26609. if (numOfMeshes === 1 && this._indices) {
  26610. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26611. }
  26612. if (this._indexBuffer) {
  26613. this._indexBuffer.references = numOfMeshes;
  26614. }
  26615. };
  26616. Geometry.prototype.notifyUpdate = function (kind) {
  26617. if (this.onGeometryUpdated) {
  26618. this.onGeometryUpdated(this, kind);
  26619. }
  26620. };
  26621. Geometry.prototype.load = function (scene, onLoaded) {
  26622. var _this = this;
  26623. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26624. return;
  26625. }
  26626. if (this.isReady()) {
  26627. if (onLoaded) {
  26628. onLoaded();
  26629. }
  26630. return;
  26631. }
  26632. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26633. scene._addPendingData(this);
  26634. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26635. _this._delayLoadingFunction(JSON.parse(data), _this);
  26636. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26637. _this._delayInfo = [];
  26638. scene._removePendingData(_this);
  26639. var meshes = _this._meshes;
  26640. var numOfMeshes = meshes.length;
  26641. for (var index = 0; index < numOfMeshes; index++) {
  26642. _this._applyToMesh(meshes[index]);
  26643. }
  26644. if (onLoaded) {
  26645. onLoaded();
  26646. }
  26647. }, function () {
  26648. }, scene.database);
  26649. };
  26650. Geometry.prototype.isDisposed = function () {
  26651. return this._isDisposed;
  26652. };
  26653. Geometry.prototype.dispose = function () {
  26654. var meshes = this._meshes;
  26655. var numOfMeshes = meshes.length;
  26656. var index;
  26657. for (index = 0; index < numOfMeshes; index++) {
  26658. this.releaseForMesh(meshes[index]);
  26659. }
  26660. this._meshes = [];
  26661. for (var kind in this._vertexBuffers) {
  26662. this._vertexBuffers[kind].dispose();
  26663. }
  26664. this._vertexBuffers = [];
  26665. this._totalVertices = 0;
  26666. if (this._indexBuffer) {
  26667. this._engine._releaseBuffer(this._indexBuffer);
  26668. }
  26669. this._indexBuffer = null;
  26670. this._indices = [];
  26671. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26672. this.delayLoadingFile = null;
  26673. this._delayLoadingFunction = null;
  26674. this._delayInfo = [];
  26675. this._boundingInfo = null; // todo: .dispose()
  26676. this._scene.removeGeometry(this);
  26677. this._isDisposed = true;
  26678. };
  26679. Geometry.prototype.copy = function (id) {
  26680. var vertexData = new BABYLON.VertexData();
  26681. vertexData.indices = [];
  26682. var indices = this.getIndices();
  26683. for (var index = 0; index < indices.length; index++) {
  26684. vertexData.indices.push(indices[index]);
  26685. }
  26686. var updatable = false;
  26687. var stopChecking = false;
  26688. for (var kind in this._vertexBuffers) {
  26689. // using slice() to make a copy of the array and not just reference it
  26690. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  26691. if (!stopChecking) {
  26692. updatable = this.getVertexBuffer(kind).isUpdatable();
  26693. stopChecking = !updatable;
  26694. }
  26695. }
  26696. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26697. geometry.delayLoadState = this.delayLoadState;
  26698. geometry.delayLoadingFile = this.delayLoadingFile;
  26699. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26700. for (kind in this._delayInfo) {
  26701. geometry._delayInfo = geometry._delayInfo || [];
  26702. geometry._delayInfo.push(kind);
  26703. }
  26704. // Bounding info
  26705. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  26706. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26707. return geometry;
  26708. };
  26709. // Statics
  26710. Geometry.ExtractFromMesh = function (mesh, id) {
  26711. var geometry = mesh._geometry;
  26712. if (!geometry) {
  26713. return null;
  26714. }
  26715. return geometry.copy(id);
  26716. };
  26717. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26718. // be aware Math.random() could cause collisions
  26719. Geometry.RandomId = function () {
  26720. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26721. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26722. return v.toString(16);
  26723. });
  26724. };
  26725. return Geometry;
  26726. })();
  26727. BABYLON.Geometry = Geometry;
  26728. /////// Primitives //////////////////////////////////////////////
  26729. var Geometry;
  26730. (function (Geometry) {
  26731. var Primitives;
  26732. (function (Primitives) {
  26733. /// Abstract class
  26734. var _Primitive = (function (_super) {
  26735. __extends(_Primitive, _super);
  26736. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26737. this._beingRegenerated = true;
  26738. this._canBeRegenerated = canBeRegenerated;
  26739. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26740. this._beingRegenerated = false;
  26741. }
  26742. _Primitive.prototype.canBeRegenerated = function () {
  26743. return this._canBeRegenerated;
  26744. };
  26745. _Primitive.prototype.regenerate = function () {
  26746. if (!this._canBeRegenerated) {
  26747. return;
  26748. }
  26749. this._beingRegenerated = true;
  26750. this.setAllVerticesData(this._regenerateVertexData(), false);
  26751. this._beingRegenerated = false;
  26752. };
  26753. _Primitive.prototype.asNewGeometry = function (id) {
  26754. return _super.prototype.copy.call(this, id);
  26755. };
  26756. // overrides
  26757. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26758. if (!this._beingRegenerated) {
  26759. return;
  26760. }
  26761. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26762. };
  26763. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26764. if (!this._beingRegenerated) {
  26765. return;
  26766. }
  26767. _super.prototype.setVerticesData.call(this, kind, data, false);
  26768. };
  26769. // to override
  26770. // protected
  26771. _Primitive.prototype._regenerateVertexData = function () {
  26772. throw new Error("Abstract method");
  26773. };
  26774. _Primitive.prototype.copy = function (id) {
  26775. throw new Error("Must be overriden in sub-classes.");
  26776. };
  26777. return _Primitive;
  26778. })(Geometry);
  26779. Primitives._Primitive = _Primitive;
  26780. var Ribbon = (function (_super) {
  26781. __extends(Ribbon, _super);
  26782. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26783. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26784. this.pathArray = pathArray;
  26785. this.closeArray = closeArray;
  26786. this.closePath = closePath;
  26787. this.offset = offset;
  26788. this.side = side;
  26789. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26790. }
  26791. Ribbon.prototype._regenerateVertexData = function () {
  26792. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  26793. };
  26794. Ribbon.prototype.copy = function (id) {
  26795. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26796. };
  26797. return Ribbon;
  26798. })(_Primitive);
  26799. Primitives.Ribbon = Ribbon;
  26800. var Box = (function (_super) {
  26801. __extends(Box, _super);
  26802. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26803. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26804. this.size = size;
  26805. this.side = side;
  26806. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26807. }
  26808. Box.prototype._regenerateVertexData = function () {
  26809. return BABYLON.VertexData.CreateBox(this.size, this.side);
  26810. };
  26811. Box.prototype.copy = function (id) {
  26812. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26813. };
  26814. return Box;
  26815. })(_Primitive);
  26816. Primitives.Box = Box;
  26817. var Sphere = (function (_super) {
  26818. __extends(Sphere, _super);
  26819. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26820. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26821. this.segments = segments;
  26822. this.diameter = diameter;
  26823. this.side = side;
  26824. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26825. }
  26826. Sphere.prototype._regenerateVertexData = function () {
  26827. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  26828. };
  26829. Sphere.prototype.copy = function (id) {
  26830. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26831. };
  26832. return Sphere;
  26833. })(_Primitive);
  26834. Primitives.Sphere = Sphere;
  26835. var Cylinder = (function (_super) {
  26836. __extends(Cylinder, _super);
  26837. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26838. if (subdivisions === void 0) { subdivisions = 1; }
  26839. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26840. this.height = height;
  26841. this.diameterTop = diameterTop;
  26842. this.diameterBottom = diameterBottom;
  26843. this.tessellation = tessellation;
  26844. this.subdivisions = subdivisions;
  26845. this.side = side;
  26846. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26847. }
  26848. Cylinder.prototype._regenerateVertexData = function () {
  26849. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  26850. };
  26851. Cylinder.prototype.copy = function (id) {
  26852. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26853. };
  26854. return Cylinder;
  26855. })(_Primitive);
  26856. Primitives.Cylinder = Cylinder;
  26857. var Torus = (function (_super) {
  26858. __extends(Torus, _super);
  26859. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26860. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26861. this.diameter = diameter;
  26862. this.thickness = thickness;
  26863. this.tessellation = tessellation;
  26864. this.side = side;
  26865. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26866. }
  26867. Torus.prototype._regenerateVertexData = function () {
  26868. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  26869. };
  26870. Torus.prototype.copy = function (id) {
  26871. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26872. };
  26873. return Torus;
  26874. })(_Primitive);
  26875. Primitives.Torus = Torus;
  26876. var Ground = (function (_super) {
  26877. __extends(Ground, _super);
  26878. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26879. this.width = width;
  26880. this.height = height;
  26881. this.subdivisions = subdivisions;
  26882. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26883. }
  26884. Ground.prototype._regenerateVertexData = function () {
  26885. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  26886. };
  26887. Ground.prototype.copy = function (id) {
  26888. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26889. };
  26890. return Ground;
  26891. })(_Primitive);
  26892. Primitives.Ground = Ground;
  26893. var TiledGround = (function (_super) {
  26894. __extends(TiledGround, _super);
  26895. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26896. this.xmin = xmin;
  26897. this.zmin = zmin;
  26898. this.xmax = xmax;
  26899. this.zmax = zmax;
  26900. this.subdivisions = subdivisions;
  26901. this.precision = precision;
  26902. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26903. }
  26904. TiledGround.prototype._regenerateVertexData = function () {
  26905. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  26906. };
  26907. TiledGround.prototype.copy = function (id) {
  26908. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26909. };
  26910. return TiledGround;
  26911. })(_Primitive);
  26912. Primitives.TiledGround = TiledGround;
  26913. var Plane = (function (_super) {
  26914. __extends(Plane, _super);
  26915. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26916. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26917. this.size = size;
  26918. this.side = side;
  26919. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26920. }
  26921. Plane.prototype._regenerateVertexData = function () {
  26922. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  26923. };
  26924. Plane.prototype.copy = function (id) {
  26925. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26926. };
  26927. return Plane;
  26928. })(_Primitive);
  26929. Primitives.Plane = Plane;
  26930. var TorusKnot = (function (_super) {
  26931. __extends(TorusKnot, _super);
  26932. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26933. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26934. this.radius = radius;
  26935. this.tube = tube;
  26936. this.radialSegments = radialSegments;
  26937. this.tubularSegments = tubularSegments;
  26938. this.p = p;
  26939. this.q = q;
  26940. this.side = side;
  26941. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26942. }
  26943. TorusKnot.prototype._regenerateVertexData = function () {
  26944. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  26945. };
  26946. TorusKnot.prototype.copy = function (id) {
  26947. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26948. };
  26949. return TorusKnot;
  26950. })(_Primitive);
  26951. Primitives.TorusKnot = TorusKnot;
  26952. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26953. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26954. })(BABYLON || (BABYLON = {}));
  26955. //# sourceMappingURL=babylon.geometry.js.map
  26956. var __extends = this.__extends || function (d, b) {
  26957. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26958. function __() { this.constructor = d; }
  26959. __.prototype = b.prototype;
  26960. d.prototype = new __();
  26961. };
  26962. var BABYLON;
  26963. (function (BABYLON) {
  26964. var GroundMesh = (function (_super) {
  26965. __extends(GroundMesh, _super);
  26966. function GroundMesh(name, scene) {
  26967. _super.call(this, name, scene);
  26968. this.generateOctree = false;
  26969. this._worldInverse = new BABYLON.Matrix();
  26970. }
  26971. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  26972. get: function () {
  26973. return this._subdivisions;
  26974. },
  26975. enumerable: true,
  26976. configurable: true
  26977. });
  26978. GroundMesh.prototype.optimize = function (chunksCount) {
  26979. this.subdivide(this._subdivisions);
  26980. this.createOrUpdateSubmeshesOctree(32);
  26981. };
  26982. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  26983. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  26984. this.getWorldMatrix().invertToRef(this._worldInverse);
  26985. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  26986. var pickInfo = this.intersects(ray);
  26987. if (pickInfo.hit) {
  26988. return pickInfo.pickedPoint.y;
  26989. }
  26990. return 0;
  26991. };
  26992. return GroundMesh;
  26993. })(BABYLON.Mesh);
  26994. BABYLON.GroundMesh = GroundMesh;
  26995. })(BABYLON || (BABYLON = {}));
  26996. //# sourceMappingURL=babylon.groundMesh.js.map
  26997. var __extends = this.__extends || function (d, b) {
  26998. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26999. function __() { this.constructor = d; }
  27000. __.prototype = b.prototype;
  27001. d.prototype = new __();
  27002. };
  27003. var BABYLON;
  27004. (function (BABYLON) {
  27005. var Gamepads = (function () {
  27006. function Gamepads(ongamedpadconnected) {
  27007. var _this = this;
  27008. this.babylonGamepads = [];
  27009. this.oneGamepadConnected = false;
  27010. this.isMonitoring = false;
  27011. this.gamepadEventSupported = 'GamepadEvent' in window;
  27012. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  27013. 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=";
  27014. this._callbackGamepadConnected = ongamedpadconnected;
  27015. if (this.gamepadSupportAvailable) {
  27016. // Checking if the gamepad connected event is supported (like in Firefox)
  27017. if (this.gamepadEventSupported) {
  27018. window.addEventListener('gamepadconnected', function (evt) {
  27019. _this._onGamepadConnected(evt);
  27020. }, false);
  27021. window.addEventListener('gamepaddisconnected', function (evt) {
  27022. _this._onGamepadDisconnected(evt);
  27023. }, false);
  27024. }
  27025. else {
  27026. this._startMonitoringGamepads();
  27027. }
  27028. if (!this.oneGamepadConnected) {
  27029. this._insertGamepadDOMInstructions();
  27030. }
  27031. }
  27032. else {
  27033. this._insertGamepadDOMNotSupported();
  27034. }
  27035. }
  27036. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  27037. Gamepads.gamepadDOMInfo = document.createElement("div");
  27038. var buttonAImage = document.createElement("img");
  27039. buttonAImage.src = this.buttonADataURL;
  27040. var spanMessage = document.createElement("span");
  27041. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  27042. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  27043. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  27044. Gamepads.gamepadDOMInfo.style.position = "absolute";
  27045. Gamepads.gamepadDOMInfo.style.width = "100%";
  27046. Gamepads.gamepadDOMInfo.style.height = "48px";
  27047. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  27048. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  27049. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  27050. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  27051. buttonAImage.style.position = "relative";
  27052. buttonAImage.style.bottom = "8px";
  27053. spanMessage.style.position = "relative";
  27054. spanMessage.style.fontSize = "32px";
  27055. spanMessage.style.bottom = "32px";
  27056. spanMessage.style.color = "green";
  27057. document.body.appendChild(Gamepads.gamepadDOMInfo);
  27058. };
  27059. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  27060. Gamepads.gamepadDOMInfo = document.createElement("div");
  27061. var spanMessage = document.createElement("span");
  27062. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  27063. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  27064. Gamepads.gamepadDOMInfo.style.position = "absolute";
  27065. Gamepads.gamepadDOMInfo.style.width = "100%";
  27066. Gamepads.gamepadDOMInfo.style.height = "40px";
  27067. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  27068. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  27069. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  27070. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  27071. spanMessage.style.position = "relative";
  27072. spanMessage.style.fontSize = "32px";
  27073. spanMessage.style.color = "red";
  27074. document.body.appendChild(Gamepads.gamepadDOMInfo);
  27075. };
  27076. Gamepads.prototype.dispose = function () {
  27077. if (Gamepads.gamepadDOMInfo) {
  27078. document.body.removeChild(Gamepads.gamepadDOMInfo);
  27079. }
  27080. };
  27081. Gamepads.prototype._onGamepadConnected = function (evt) {
  27082. var newGamepad = this._addNewGamepad(evt.gamepad);
  27083. if (this._callbackGamepadConnected)
  27084. this._callbackGamepadConnected(newGamepad);
  27085. this._startMonitoringGamepads();
  27086. };
  27087. Gamepads.prototype._addNewGamepad = function (gamepad) {
  27088. if (!this.oneGamepadConnected) {
  27089. this.oneGamepadConnected = true;
  27090. if (Gamepads.gamepadDOMInfo) {
  27091. document.body.removeChild(Gamepads.gamepadDOMInfo);
  27092. Gamepads.gamepadDOMInfo = null;
  27093. }
  27094. }
  27095. var newGamepad;
  27096. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  27097. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  27098. }
  27099. else {
  27100. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  27101. }
  27102. this.babylonGamepads.push(newGamepad);
  27103. return newGamepad;
  27104. };
  27105. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  27106. for (var i in this.babylonGamepads) {
  27107. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  27108. this.babylonGamepads.splice(i, 1);
  27109. break;
  27110. }
  27111. }
  27112. // If no gamepads are left, stop the polling loop.
  27113. if (this.babylonGamepads.length == 0) {
  27114. this._stopMonitoringGamepads();
  27115. }
  27116. };
  27117. Gamepads.prototype._startMonitoringGamepads = function () {
  27118. if (!this.isMonitoring) {
  27119. this.isMonitoring = true;
  27120. this._checkGamepadsStatus();
  27121. }
  27122. };
  27123. Gamepads.prototype._stopMonitoringGamepads = function () {
  27124. this.isMonitoring = false;
  27125. };
  27126. Gamepads.prototype._checkGamepadsStatus = function () {
  27127. var _this = this;
  27128. // updating gamepad objects
  27129. this._updateGamepadObjects();
  27130. for (var i in this.babylonGamepads) {
  27131. this.babylonGamepads[i].update();
  27132. }
  27133. if (this.isMonitoring) {
  27134. if (window.requestAnimationFrame) {
  27135. window.requestAnimationFrame(function () {
  27136. _this._checkGamepadsStatus();
  27137. });
  27138. }
  27139. else if (window.mozRequestAnimationFrame) {
  27140. window.mozRequestAnimationFrame(function () {
  27141. _this._checkGamepadsStatus();
  27142. });
  27143. }
  27144. else if (window.webkitRequestAnimationFrame) {
  27145. window.webkitRequestAnimationFrame(function () {
  27146. _this._checkGamepadsStatus();
  27147. });
  27148. }
  27149. }
  27150. };
  27151. // This function is called only on Chrome, which does not yet support
  27152. // connection/disconnection events, but requires you to monitor
  27153. // an array for changes.
  27154. Gamepads.prototype._updateGamepadObjects = function () {
  27155. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  27156. for (var i = 0; i < gamepads.length; i++) {
  27157. if (gamepads[i]) {
  27158. if (!(gamepads[i].index in this.babylonGamepads)) {
  27159. var newGamepad = this._addNewGamepad(gamepads[i]);
  27160. if (this._callbackGamepadConnected) {
  27161. this._callbackGamepadConnected(newGamepad);
  27162. }
  27163. }
  27164. else {
  27165. this.babylonGamepads[i].browserGamepad = gamepads[i];
  27166. }
  27167. }
  27168. }
  27169. };
  27170. return Gamepads;
  27171. })();
  27172. BABYLON.Gamepads = Gamepads;
  27173. var StickValues = (function () {
  27174. function StickValues(x, y) {
  27175. this.x = x;
  27176. this.y = y;
  27177. }
  27178. return StickValues;
  27179. })();
  27180. BABYLON.StickValues = StickValues;
  27181. var Gamepad = (function () {
  27182. function Gamepad(id, index, browserGamepad) {
  27183. this.id = id;
  27184. this.index = index;
  27185. this.browserGamepad = browserGamepad;
  27186. if (this.browserGamepad.axes.length >= 2) {
  27187. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  27188. }
  27189. if (this.browserGamepad.axes.length >= 4) {
  27190. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  27191. }
  27192. }
  27193. Gamepad.prototype.onleftstickchanged = function (callback) {
  27194. this._onleftstickchanged = callback;
  27195. };
  27196. Gamepad.prototype.onrightstickchanged = function (callback) {
  27197. this._onrightstickchanged = callback;
  27198. };
  27199. Object.defineProperty(Gamepad.prototype, "leftStick", {
  27200. get: function () {
  27201. return this._leftStick;
  27202. },
  27203. set: function (newValues) {
  27204. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  27205. this._onleftstickchanged(newValues);
  27206. }
  27207. this._leftStick = newValues;
  27208. },
  27209. enumerable: true,
  27210. configurable: true
  27211. });
  27212. Object.defineProperty(Gamepad.prototype, "rightStick", {
  27213. get: function () {
  27214. return this._rightStick;
  27215. },
  27216. set: function (newValues) {
  27217. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  27218. this._onrightstickchanged(newValues);
  27219. }
  27220. this._rightStick = newValues;
  27221. },
  27222. enumerable: true,
  27223. configurable: true
  27224. });
  27225. Gamepad.prototype.update = function () {
  27226. if (this._leftStick) {
  27227. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  27228. }
  27229. if (this._rightStick) {
  27230. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  27231. }
  27232. };
  27233. return Gamepad;
  27234. })();
  27235. BABYLON.Gamepad = Gamepad;
  27236. var GenericPad = (function (_super) {
  27237. __extends(GenericPad, _super);
  27238. function GenericPad(id, index, gamepad) {
  27239. _super.call(this, id, index, gamepad);
  27240. this.id = id;
  27241. this.index = index;
  27242. this.gamepad = gamepad;
  27243. this._buttons = new Array(gamepad.buttons.length);
  27244. }
  27245. GenericPad.prototype.onbuttondown = function (callback) {
  27246. this._onbuttondown = callback;
  27247. };
  27248. GenericPad.prototype.onbuttonup = function (callback) {
  27249. this._onbuttonup = callback;
  27250. };
  27251. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  27252. if (newValue !== currentValue) {
  27253. if (this._onbuttondown && newValue === 1) {
  27254. this._onbuttondown(buttonIndex);
  27255. }
  27256. if (this._onbuttonup && newValue === 0) {
  27257. this._onbuttonup(buttonIndex);
  27258. }
  27259. }
  27260. return newValue;
  27261. };
  27262. GenericPad.prototype.update = function () {
  27263. _super.prototype.update.call(this);
  27264. for (var index = 0; index < this._buttons.length; index++) {
  27265. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  27266. }
  27267. };
  27268. return GenericPad;
  27269. })(Gamepad);
  27270. BABYLON.GenericPad = GenericPad;
  27271. (function (Xbox360Button) {
  27272. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  27273. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  27274. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  27275. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  27276. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  27277. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  27278. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  27279. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  27280. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  27281. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  27282. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  27283. var Xbox360Button = BABYLON.Xbox360Button;
  27284. (function (Xbox360Dpad) {
  27285. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  27286. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  27287. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  27288. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  27289. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  27290. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  27291. var Xbox360Pad = (function (_super) {
  27292. __extends(Xbox360Pad, _super);
  27293. function Xbox360Pad() {
  27294. _super.apply(this, arguments);
  27295. this._leftTrigger = 0;
  27296. this._rightTrigger = 0;
  27297. this._buttonA = 0;
  27298. this._buttonB = 0;
  27299. this._buttonX = 0;
  27300. this._buttonY = 0;
  27301. this._buttonBack = 0;
  27302. this._buttonStart = 0;
  27303. this._buttonLB = 0;
  27304. this._buttonRB = 0;
  27305. this._buttonLeftStick = 0;
  27306. this._buttonRightStick = 0;
  27307. this._dPadUp = 0;
  27308. this._dPadDown = 0;
  27309. this._dPadLeft = 0;
  27310. this._dPadRight = 0;
  27311. }
  27312. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  27313. this._onlefttriggerchanged = callback;
  27314. };
  27315. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  27316. this._onrighttriggerchanged = callback;
  27317. };
  27318. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  27319. get: function () {
  27320. return this._leftTrigger;
  27321. },
  27322. set: function (newValue) {
  27323. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  27324. this._onlefttriggerchanged(newValue);
  27325. }
  27326. this._leftTrigger = newValue;
  27327. },
  27328. enumerable: true,
  27329. configurable: true
  27330. });
  27331. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  27332. get: function () {
  27333. return this._rightTrigger;
  27334. },
  27335. set: function (newValue) {
  27336. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  27337. this._onrighttriggerchanged(newValue);
  27338. }
  27339. this._rightTrigger = newValue;
  27340. },
  27341. enumerable: true,
  27342. configurable: true
  27343. });
  27344. Xbox360Pad.prototype.onbuttondown = function (callback) {
  27345. this._onbuttondown = callback;
  27346. };
  27347. Xbox360Pad.prototype.onbuttonup = function (callback) {
  27348. this._onbuttonup = callback;
  27349. };
  27350. Xbox360Pad.prototype.ondpaddown = function (callback) {
  27351. this._ondpaddown = callback;
  27352. };
  27353. Xbox360Pad.prototype.ondpadup = function (callback) {
  27354. this._ondpadup = callback;
  27355. };
  27356. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  27357. if (newValue !== currentValue) {
  27358. if (this._onbuttondown && newValue === 1) {
  27359. this._onbuttondown(buttonType);
  27360. }
  27361. if (this._onbuttonup && newValue === 0) {
  27362. this._onbuttonup(buttonType);
  27363. }
  27364. }
  27365. return newValue;
  27366. };
  27367. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  27368. if (newValue !== currentValue) {
  27369. if (this._ondpaddown && newValue === 1) {
  27370. this._ondpaddown(buttonType);
  27371. }
  27372. if (this._ondpadup && newValue === 0) {
  27373. this._ondpadup(buttonType);
  27374. }
  27375. }
  27376. return newValue;
  27377. };
  27378. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  27379. get: function () {
  27380. return this._buttonA;
  27381. },
  27382. set: function (value) {
  27383. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  27384. },
  27385. enumerable: true,
  27386. configurable: true
  27387. });
  27388. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  27389. get: function () {
  27390. return this._buttonB;
  27391. },
  27392. set: function (value) {
  27393. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  27394. },
  27395. enumerable: true,
  27396. configurable: true
  27397. });
  27398. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  27399. get: function () {
  27400. return this._buttonX;
  27401. },
  27402. set: function (value) {
  27403. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  27404. },
  27405. enumerable: true,
  27406. configurable: true
  27407. });
  27408. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  27409. get: function () {
  27410. return this._buttonY;
  27411. },
  27412. set: function (value) {
  27413. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  27414. },
  27415. enumerable: true,
  27416. configurable: true
  27417. });
  27418. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  27419. get: function () {
  27420. return this._buttonStart;
  27421. },
  27422. set: function (value) {
  27423. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  27424. },
  27425. enumerable: true,
  27426. configurable: true
  27427. });
  27428. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  27429. get: function () {
  27430. return this._buttonBack;
  27431. },
  27432. set: function (value) {
  27433. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  27434. },
  27435. enumerable: true,
  27436. configurable: true
  27437. });
  27438. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  27439. get: function () {
  27440. return this._buttonLB;
  27441. },
  27442. set: function (value) {
  27443. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  27444. },
  27445. enumerable: true,
  27446. configurable: true
  27447. });
  27448. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  27449. get: function () {
  27450. return this._buttonRB;
  27451. },
  27452. set: function (value) {
  27453. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  27454. },
  27455. enumerable: true,
  27456. configurable: true
  27457. });
  27458. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  27459. get: function () {
  27460. return this._buttonLeftStick;
  27461. },
  27462. set: function (value) {
  27463. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  27464. },
  27465. enumerable: true,
  27466. configurable: true
  27467. });
  27468. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  27469. get: function () {
  27470. return this._buttonRightStick;
  27471. },
  27472. set: function (value) {
  27473. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  27474. },
  27475. enumerable: true,
  27476. configurable: true
  27477. });
  27478. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  27479. get: function () {
  27480. return this._dPadUp;
  27481. },
  27482. set: function (value) {
  27483. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  27484. },
  27485. enumerable: true,
  27486. configurable: true
  27487. });
  27488. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  27489. get: function () {
  27490. return this._dPadDown;
  27491. },
  27492. set: function (value) {
  27493. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  27494. },
  27495. enumerable: true,
  27496. configurable: true
  27497. });
  27498. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  27499. get: function () {
  27500. return this._dPadLeft;
  27501. },
  27502. set: function (value) {
  27503. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  27504. },
  27505. enumerable: true,
  27506. configurable: true
  27507. });
  27508. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  27509. get: function () {
  27510. return this._dPadRight;
  27511. },
  27512. set: function (value) {
  27513. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  27514. },
  27515. enumerable: true,
  27516. configurable: true
  27517. });
  27518. Xbox360Pad.prototype.update = function () {
  27519. _super.prototype.update.call(this);
  27520. this.buttonA = this.browserGamepad.buttons[0].value;
  27521. this.buttonB = this.browserGamepad.buttons[1].value;
  27522. this.buttonX = this.browserGamepad.buttons[2].value;
  27523. this.buttonY = this.browserGamepad.buttons[3].value;
  27524. this.buttonLB = this.browserGamepad.buttons[4].value;
  27525. this.buttonRB = this.browserGamepad.buttons[5].value;
  27526. this.leftTrigger = this.browserGamepad.buttons[6].value;
  27527. this.rightTrigger = this.browserGamepad.buttons[7].value;
  27528. this.buttonBack = this.browserGamepad.buttons[8].value;
  27529. this.buttonStart = this.browserGamepad.buttons[9].value;
  27530. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  27531. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  27532. this.dPadUp = this.browserGamepad.buttons[12].value;
  27533. this.dPadDown = this.browserGamepad.buttons[13].value;
  27534. this.dPadLeft = this.browserGamepad.buttons[14].value;
  27535. this.dPadRight = this.browserGamepad.buttons[15].value;
  27536. };
  27537. return Xbox360Pad;
  27538. })(Gamepad);
  27539. BABYLON.Xbox360Pad = Xbox360Pad;
  27540. })(BABYLON || (BABYLON = {}));
  27541. //# sourceMappingURL=babylon.gamepads.js.map
  27542. var __extends = this.__extends || function (d, b) {
  27543. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27544. function __() { this.constructor = d; }
  27545. __.prototype = b.prototype;
  27546. d.prototype = new __();
  27547. };
  27548. var BABYLON;
  27549. (function (BABYLON) {
  27550. // We're mainly based on the logic defined into the FreeCamera code
  27551. var GamepadCamera = (function (_super) {
  27552. __extends(GamepadCamera, _super);
  27553. function GamepadCamera(name, position, scene) {
  27554. var _this = this;
  27555. _super.call(this, name, position, scene);
  27556. this.angularSensibility = 200;
  27557. this.moveSensibility = 75;
  27558. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  27559. _this._onNewGameConnected(gamepad);
  27560. });
  27561. }
  27562. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  27563. // Only the first gamepad can control the camera
  27564. if (gamepad.index === 0) {
  27565. this._gamepad = gamepad;
  27566. }
  27567. };
  27568. GamepadCamera.prototype._checkInputs = function () {
  27569. if (!this._gamepad) {
  27570. return;
  27571. }
  27572. var LSValues = this._gamepad.leftStick;
  27573. var normalizedLX = LSValues.x / this.moveSensibility;
  27574. var normalizedLY = LSValues.y / this.moveSensibility;
  27575. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  27576. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  27577. var RSValues = this._gamepad.rightStick;
  27578. var normalizedRX = RSValues.x / this.angularSensibility;
  27579. var normalizedRY = RSValues.y / this.angularSensibility;
  27580. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  27581. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  27582. ;
  27583. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  27584. var speed = this._computeLocalCameraSpeed() * 50.0;
  27585. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  27586. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  27587. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  27588. };
  27589. GamepadCamera.prototype.dispose = function () {
  27590. this._gamepads.dispose();
  27591. _super.prototype.dispose.call(this);
  27592. };
  27593. return GamepadCamera;
  27594. })(BABYLON.FreeCamera);
  27595. BABYLON.GamepadCamera = GamepadCamera;
  27596. })(BABYLON || (BABYLON = {}));
  27597. //# sourceMappingURL=babylon.gamepadCamera.js.map
  27598. var __extends = this.__extends || function (d, b) {
  27599. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27600. function __() { this.constructor = d; }
  27601. __.prototype = b.prototype;
  27602. d.prototype = new __();
  27603. };
  27604. var BABYLON;
  27605. (function (BABYLON) {
  27606. var LinesMesh = (function (_super) {
  27607. __extends(LinesMesh, _super);
  27608. function LinesMesh(name, scene, updatable) {
  27609. if (updatable === void 0) { updatable = false; }
  27610. _super.call(this, name, scene);
  27611. this.color = new BABYLON.Color3(1, 1, 1);
  27612. this.alpha = 1;
  27613. this._indices = new Array();
  27614. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27615. attributes: ["position"],
  27616. uniforms: ["worldViewProjection", "color"],
  27617. needAlphaBlending: true
  27618. });
  27619. }
  27620. Object.defineProperty(LinesMesh.prototype, "material", {
  27621. get: function () {
  27622. return this._colorShader;
  27623. },
  27624. enumerable: true,
  27625. configurable: true
  27626. });
  27627. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27628. get: function () {
  27629. return false;
  27630. },
  27631. enumerable: true,
  27632. configurable: true
  27633. });
  27634. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27635. get: function () {
  27636. return false;
  27637. },
  27638. enumerable: true,
  27639. configurable: true
  27640. });
  27641. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27642. var engine = this.getScene().getEngine();
  27643. var indexToBind = this._geometry.getIndexBuffer();
  27644. // VBOs
  27645. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27646. // Color
  27647. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27648. };
  27649. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27650. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27651. return;
  27652. }
  27653. var engine = this.getScene().getEngine();
  27654. // Draw order
  27655. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27656. };
  27657. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27658. return null;
  27659. };
  27660. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27661. this._colorShader.dispose();
  27662. _super.prototype.dispose.call(this, doNotRecurse);
  27663. };
  27664. return LinesMesh;
  27665. })(BABYLON.Mesh);
  27666. BABYLON.LinesMesh = LinesMesh;
  27667. })(BABYLON || (BABYLON = {}));
  27668. //# sourceMappingURL=babylon.linesMesh.js.map
  27669. var BABYLON;
  27670. (function (BABYLON) {
  27671. var OutlineRenderer = (function () {
  27672. function OutlineRenderer(scene) {
  27673. this._scene = scene;
  27674. }
  27675. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  27676. var _this = this;
  27677. if (useOverlay === void 0) { useOverlay = false; }
  27678. var scene = this._scene;
  27679. var engine = this._scene.getEngine();
  27680. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27681. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  27682. return;
  27683. }
  27684. var mesh = subMesh.getRenderingMesh();
  27685. var material = subMesh.getMaterial();
  27686. engine.enableEffect(this._effect);
  27687. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  27688. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  27689. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27690. // Bones
  27691. if (mesh.useBones) {
  27692. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27693. }
  27694. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  27695. // Alpha test
  27696. if (material && material.needAlphaTesting()) {
  27697. var alphaTexture = material.getAlphaTestTexture();
  27698. this._effect.setTexture("diffuseSampler", alphaTexture);
  27699. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27700. }
  27701. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  27702. _this._effect.setMatrix("world", world);
  27703. });
  27704. };
  27705. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  27706. var defines = [];
  27707. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  27708. var mesh = subMesh.getMesh();
  27709. var material = subMesh.getMaterial();
  27710. // Alpha test
  27711. if (material && material.needAlphaTesting()) {
  27712. defines.push("#define ALPHATEST");
  27713. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27714. attribs.push(BABYLON.VertexBuffer.UVKind);
  27715. defines.push("#define UV1");
  27716. }
  27717. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27718. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27719. defines.push("#define UV2");
  27720. }
  27721. }
  27722. // Bones
  27723. if (mesh.useBones) {
  27724. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27725. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27726. defines.push("#define BONES");
  27727. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27728. }
  27729. // Instances
  27730. if (useInstances) {
  27731. defines.push("#define INSTANCES");
  27732. attribs.push("world0");
  27733. attribs.push("world1");
  27734. attribs.push("world2");
  27735. attribs.push("world3");
  27736. }
  27737. // Get correct effect
  27738. var join = defines.join("\n");
  27739. if (this._cachedDefines !== join) {
  27740. this._cachedDefines = join;
  27741. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  27742. }
  27743. return this._effect.isReady();
  27744. };
  27745. return OutlineRenderer;
  27746. })();
  27747. BABYLON.OutlineRenderer = OutlineRenderer;
  27748. })(BABYLON || (BABYLON = {}));
  27749. //# sourceMappingURL=babylon.outlineRenderer.js.map
  27750. var BABYLON;
  27751. (function (BABYLON) {
  27752. var MeshAssetTask = (function () {
  27753. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  27754. this.name = name;
  27755. this.meshesNames = meshesNames;
  27756. this.rootUrl = rootUrl;
  27757. this.sceneFilename = sceneFilename;
  27758. this.isCompleted = false;
  27759. }
  27760. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27761. var _this = this;
  27762. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  27763. _this.loadedMeshes = meshes;
  27764. _this.loadedParticleSystems = particleSystems;
  27765. _this.loadedSkeletons = skeletons;
  27766. _this.isCompleted = true;
  27767. if (_this.onSuccess) {
  27768. _this.onSuccess(_this);
  27769. }
  27770. onSuccess();
  27771. }, null, function () {
  27772. if (_this.onError) {
  27773. _this.onError(_this);
  27774. }
  27775. onError();
  27776. });
  27777. };
  27778. return MeshAssetTask;
  27779. })();
  27780. BABYLON.MeshAssetTask = MeshAssetTask;
  27781. var TextFileAssetTask = (function () {
  27782. function TextFileAssetTask(name, url) {
  27783. this.name = name;
  27784. this.url = url;
  27785. this.isCompleted = false;
  27786. }
  27787. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27788. var _this = this;
  27789. BABYLON.Tools.LoadFile(this.url, function (data) {
  27790. _this.text = data;
  27791. _this.isCompleted = true;
  27792. if (_this.onSuccess) {
  27793. _this.onSuccess(_this);
  27794. }
  27795. onSuccess();
  27796. }, null, scene.database, false, function () {
  27797. if (_this.onError) {
  27798. _this.onError(_this);
  27799. }
  27800. onError();
  27801. });
  27802. };
  27803. return TextFileAssetTask;
  27804. })();
  27805. BABYLON.TextFileAssetTask = TextFileAssetTask;
  27806. var BinaryFileAssetTask = (function () {
  27807. function BinaryFileAssetTask(name, url) {
  27808. this.name = name;
  27809. this.url = url;
  27810. this.isCompleted = false;
  27811. }
  27812. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27813. var _this = this;
  27814. BABYLON.Tools.LoadFile(this.url, function (data) {
  27815. _this.data = data;
  27816. _this.isCompleted = true;
  27817. if (_this.onSuccess) {
  27818. _this.onSuccess(_this);
  27819. }
  27820. onSuccess();
  27821. }, null, scene.database, true, function () {
  27822. if (_this.onError) {
  27823. _this.onError(_this);
  27824. }
  27825. onError();
  27826. });
  27827. };
  27828. return BinaryFileAssetTask;
  27829. })();
  27830. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  27831. var ImageAssetTask = (function () {
  27832. function ImageAssetTask(name, url) {
  27833. this.name = name;
  27834. this.url = url;
  27835. this.isCompleted = false;
  27836. }
  27837. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27838. var _this = this;
  27839. var img = new Image();
  27840. img.onload = function () {
  27841. _this.image = img;
  27842. _this.isCompleted = true;
  27843. if (_this.onSuccess) {
  27844. _this.onSuccess(_this);
  27845. }
  27846. onSuccess();
  27847. };
  27848. img.onerror = function () {
  27849. if (_this.onError) {
  27850. _this.onError(_this);
  27851. }
  27852. onError();
  27853. };
  27854. img.src = this.url;
  27855. };
  27856. return ImageAssetTask;
  27857. })();
  27858. BABYLON.ImageAssetTask = ImageAssetTask;
  27859. var TextureAssetTask = (function () {
  27860. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  27861. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27862. this.name = name;
  27863. this.url = url;
  27864. this.noMipmap = noMipmap;
  27865. this.invertY = invertY;
  27866. this.samplingMode = samplingMode;
  27867. this.isCompleted = false;
  27868. }
  27869. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27870. var _this = this;
  27871. var onload = function () {
  27872. _this.isCompleted = true;
  27873. if (_this.onSuccess) {
  27874. _this.onSuccess(_this);
  27875. }
  27876. onSuccess();
  27877. };
  27878. var onerror = function () {
  27879. if (_this.onError) {
  27880. _this.onError(_this);
  27881. }
  27882. onError();
  27883. };
  27884. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  27885. };
  27886. return TextureAssetTask;
  27887. })();
  27888. BABYLON.TextureAssetTask = TextureAssetTask;
  27889. var AssetsManager = (function () {
  27890. function AssetsManager(scene) {
  27891. this._tasks = new Array();
  27892. this._waitingTasksCount = 0;
  27893. this.useDefaultLoadingScreen = true;
  27894. this._scene = scene;
  27895. }
  27896. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  27897. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  27898. this._tasks.push(task);
  27899. return task;
  27900. };
  27901. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  27902. var task = new TextFileAssetTask(taskName, url);
  27903. this._tasks.push(task);
  27904. return task;
  27905. };
  27906. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  27907. var task = new BinaryFileAssetTask(taskName, url);
  27908. this._tasks.push(task);
  27909. return task;
  27910. };
  27911. AssetsManager.prototype.addImageTask = function (taskName, url) {
  27912. var task = new ImageAssetTask(taskName, url);
  27913. this._tasks.push(task);
  27914. return task;
  27915. };
  27916. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  27917. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27918. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  27919. this._tasks.push(task);
  27920. return task;
  27921. };
  27922. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  27923. this._waitingTasksCount--;
  27924. if (this._waitingTasksCount === 0) {
  27925. if (this.onFinish) {
  27926. this.onFinish(this._tasks);
  27927. }
  27928. this._scene.getEngine().hideLoadingUI();
  27929. }
  27930. };
  27931. AssetsManager.prototype._runTask = function (task) {
  27932. var _this = this;
  27933. task.run(this._scene, function () {
  27934. if (_this.onTaskSuccess) {
  27935. _this.onTaskSuccess(task);
  27936. }
  27937. _this._decreaseWaitingTasksCount();
  27938. }, function () {
  27939. if (_this.onTaskError) {
  27940. _this.onTaskError(task);
  27941. }
  27942. _this._decreaseWaitingTasksCount();
  27943. });
  27944. };
  27945. AssetsManager.prototype.reset = function () {
  27946. this._tasks = new Array();
  27947. return this;
  27948. };
  27949. AssetsManager.prototype.load = function () {
  27950. this._waitingTasksCount = this._tasks.length;
  27951. if (this._waitingTasksCount === 0) {
  27952. if (this.onFinish) {
  27953. this.onFinish(this._tasks);
  27954. }
  27955. return this;
  27956. }
  27957. if (this.useDefaultLoadingScreen) {
  27958. this._scene.getEngine().displayLoadingUI();
  27959. }
  27960. for (var index = 0; index < this._tasks.length; index++) {
  27961. var task = this._tasks[index];
  27962. this._runTask(task);
  27963. }
  27964. return this;
  27965. };
  27966. return AssetsManager;
  27967. })();
  27968. BABYLON.AssetsManager = AssetsManager;
  27969. })(BABYLON || (BABYLON = {}));
  27970. //# sourceMappingURL=babylon.assetsManager.js.map
  27971. var __extends = this.__extends || function (d, b) {
  27972. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27973. function __() { this.constructor = d; }
  27974. __.prototype = b.prototype;
  27975. d.prototype = new __();
  27976. };
  27977. var BABYLON;
  27978. (function (BABYLON) {
  27979. var VRDeviceOrientationCamera = (function (_super) {
  27980. __extends(VRDeviceOrientationCamera, _super);
  27981. function VRDeviceOrientationCamera(name, position, scene) {
  27982. _super.call(this, name, position, scene);
  27983. this._alpha = 0;
  27984. this._beta = 0;
  27985. this._gamma = 0;
  27986. }
  27987. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  27988. this._alpha = +evt.alpha | 0;
  27989. this._beta = +evt.beta | 0;
  27990. this._gamma = +evt.gamma | 0;
  27991. if (this._gamma < 0) {
  27992. this._gamma = 90 + this._gamma;
  27993. }
  27994. else {
  27995. // Incline it in the correct angle.
  27996. this._gamma = 270 - this._gamma;
  27997. }
  27998. this.rotation.x = this._gamma / 180.0 * Math.PI;
  27999. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  28000. this.rotation.z = this._beta / 180.0 * Math.PI;
  28001. };
  28002. return VRDeviceOrientationCamera;
  28003. })(BABYLON.OculusCamera);
  28004. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  28005. })(BABYLON || (BABYLON = {}));
  28006. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  28007. var __extends = this.__extends || function (d, b) {
  28008. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28009. function __() { this.constructor = d; }
  28010. __.prototype = b.prototype;
  28011. d.prototype = new __();
  28012. };
  28013. var BABYLON;
  28014. (function (BABYLON) {
  28015. var WebVRCamera = (function (_super) {
  28016. __extends(WebVRCamera, _super);
  28017. function WebVRCamera(name, position, scene) {
  28018. _super.call(this, name, position, scene);
  28019. this._hmdDevice = null;
  28020. this._sensorDevice = null;
  28021. this._cacheState = null;
  28022. this._cacheQuaternion = new BABYLON.Quaternion();
  28023. this._cacheRotation = BABYLON.Vector3.Zero();
  28024. this._vrEnabled = false;
  28025. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  28026. }
  28027. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  28028. var size = devices.length;
  28029. var i = 0;
  28030. // Reset devices.
  28031. this._sensorDevice = null;
  28032. this._hmdDevice = null;
  28033. while (i < size && this._hmdDevice === null) {
  28034. if (devices[i] instanceof HMDVRDevice) {
  28035. this._hmdDevice = devices[i];
  28036. }
  28037. i++;
  28038. }
  28039. i = 0;
  28040. while (i < size && this._sensorDevice === null) {
  28041. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  28042. this._sensorDevice = devices[i];
  28043. }
  28044. i++;
  28045. }
  28046. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  28047. };
  28048. WebVRCamera.prototype._update = function () {
  28049. if (this._vrEnabled) {
  28050. this._cacheState = this._sensorDevice.getState();
  28051. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  28052. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  28053. this.rotation.x = -this._cacheRotation.z;
  28054. this.rotation.y = -this._cacheRotation.y;
  28055. this.rotation.z = this._cacheRotation.x;
  28056. }
  28057. _super.prototype._update.call(this);
  28058. };
  28059. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  28060. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28061. if (navigator.getVRDevices) {
  28062. navigator.getVRDevices().then(this._getWebVRDevices);
  28063. }
  28064. else if (navigator.mozGetVRDevices) {
  28065. navigator.mozGetVRDevices(this._getWebVRDevices);
  28066. }
  28067. };
  28068. WebVRCamera.prototype.detachControl = function (element) {
  28069. _super.prototype.detachControl.call(this, element);
  28070. this._vrEnabled = false;
  28071. };
  28072. return WebVRCamera;
  28073. })(BABYLON.OculusCamera);
  28074. BABYLON.WebVRCamera = WebVRCamera;
  28075. })(BABYLON || (BABYLON = {}));
  28076. //# sourceMappingURL=babylon.webVRCamera.js.map
  28077. var __extends = this.__extends || function (d, b) {
  28078. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28079. function __() { this.constructor = d; }
  28080. __.prototype = b.prototype;
  28081. d.prototype = new __();
  28082. };
  28083. var BABYLON;
  28084. (function (BABYLON) {
  28085. // Standard optimizations
  28086. var SceneOptimization = (function () {
  28087. function SceneOptimization(priority) {
  28088. if (priority === void 0) { priority = 0; }
  28089. this.priority = priority;
  28090. this.apply = function (scene) {
  28091. return true; // Return true if everything that can be done was applied
  28092. };
  28093. }
  28094. return SceneOptimization;
  28095. })();
  28096. BABYLON.SceneOptimization = SceneOptimization;
  28097. var TextureOptimization = (function (_super) {
  28098. __extends(TextureOptimization, _super);
  28099. function TextureOptimization(priority, maximumSize) {
  28100. var _this = this;
  28101. if (priority === void 0) { priority = 0; }
  28102. if (maximumSize === void 0) { maximumSize = 1024; }
  28103. _super.call(this, priority);
  28104. this.priority = priority;
  28105. this.maximumSize = maximumSize;
  28106. this.apply = function (scene) {
  28107. var allDone = true;
  28108. for (var index = 0; index < scene.textures.length; index++) {
  28109. var texture = scene.textures[index];
  28110. if (!texture.canRescale) {
  28111. continue;
  28112. }
  28113. var currentSize = texture.getSize();
  28114. var maxDimension = Math.max(currentSize.width, currentSize.height);
  28115. if (maxDimension > _this.maximumSize) {
  28116. texture.scale(0.5);
  28117. allDone = false;
  28118. }
  28119. }
  28120. return allDone;
  28121. };
  28122. }
  28123. return TextureOptimization;
  28124. })(SceneOptimization);
  28125. BABYLON.TextureOptimization = TextureOptimization;
  28126. var HardwareScalingOptimization = (function (_super) {
  28127. __extends(HardwareScalingOptimization, _super);
  28128. function HardwareScalingOptimization(priority, maximumScale) {
  28129. var _this = this;
  28130. if (priority === void 0) { priority = 0; }
  28131. if (maximumScale === void 0) { maximumScale = 2; }
  28132. _super.call(this, priority);
  28133. this.priority = priority;
  28134. this.maximumScale = maximumScale;
  28135. this._currentScale = 1;
  28136. this.apply = function (scene) {
  28137. _this._currentScale++;
  28138. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  28139. return _this._currentScale >= _this.maximumScale;
  28140. };
  28141. }
  28142. return HardwareScalingOptimization;
  28143. })(SceneOptimization);
  28144. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  28145. var ShadowsOptimization = (function (_super) {
  28146. __extends(ShadowsOptimization, _super);
  28147. function ShadowsOptimization() {
  28148. _super.apply(this, arguments);
  28149. this.apply = function (scene) {
  28150. scene.shadowsEnabled = false;
  28151. return true;
  28152. };
  28153. }
  28154. return ShadowsOptimization;
  28155. })(SceneOptimization);
  28156. BABYLON.ShadowsOptimization = ShadowsOptimization;
  28157. var PostProcessesOptimization = (function (_super) {
  28158. __extends(PostProcessesOptimization, _super);
  28159. function PostProcessesOptimization() {
  28160. _super.apply(this, arguments);
  28161. this.apply = function (scene) {
  28162. scene.postProcessesEnabled = false;
  28163. return true;
  28164. };
  28165. }
  28166. return PostProcessesOptimization;
  28167. })(SceneOptimization);
  28168. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  28169. var LensFlaresOptimization = (function (_super) {
  28170. __extends(LensFlaresOptimization, _super);
  28171. function LensFlaresOptimization() {
  28172. _super.apply(this, arguments);
  28173. this.apply = function (scene) {
  28174. scene.lensFlaresEnabled = false;
  28175. return true;
  28176. };
  28177. }
  28178. return LensFlaresOptimization;
  28179. })(SceneOptimization);
  28180. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  28181. var ParticlesOptimization = (function (_super) {
  28182. __extends(ParticlesOptimization, _super);
  28183. function ParticlesOptimization() {
  28184. _super.apply(this, arguments);
  28185. this.apply = function (scene) {
  28186. scene.particlesEnabled = false;
  28187. return true;
  28188. };
  28189. }
  28190. return ParticlesOptimization;
  28191. })(SceneOptimization);
  28192. BABYLON.ParticlesOptimization = ParticlesOptimization;
  28193. var RenderTargetsOptimization = (function (_super) {
  28194. __extends(RenderTargetsOptimization, _super);
  28195. function RenderTargetsOptimization() {
  28196. _super.apply(this, arguments);
  28197. this.apply = function (scene) {
  28198. scene.renderTargetsEnabled = false;
  28199. return true;
  28200. };
  28201. }
  28202. return RenderTargetsOptimization;
  28203. })(SceneOptimization);
  28204. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  28205. var MergeMeshesOptimization = (function (_super) {
  28206. __extends(MergeMeshesOptimization, _super);
  28207. function MergeMeshesOptimization() {
  28208. var _this = this;
  28209. _super.apply(this, arguments);
  28210. this._canBeMerged = function (abstractMesh) {
  28211. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  28212. return false;
  28213. }
  28214. var mesh = abstractMesh;
  28215. if (!mesh.isVisible || !mesh.isEnabled()) {
  28216. return false;
  28217. }
  28218. if (mesh.instances.length > 0) {
  28219. return false;
  28220. }
  28221. if (mesh.skeleton || mesh.hasLODLevels) {
  28222. return false;
  28223. }
  28224. return true;
  28225. };
  28226. this.apply = function (scene) {
  28227. var globalPool = scene.meshes.slice(0);
  28228. var globalLength = globalPool.length;
  28229. for (var index = 0; index < globalLength; index++) {
  28230. var currentPool = new Array();
  28231. var current = globalPool[index];
  28232. // Checks
  28233. if (!_this._canBeMerged(current)) {
  28234. continue;
  28235. }
  28236. currentPool.push(current);
  28237. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  28238. var otherMesh = globalPool[subIndex];
  28239. if (!_this._canBeMerged(otherMesh)) {
  28240. continue;
  28241. }
  28242. if (otherMesh.material !== current.material) {
  28243. continue;
  28244. }
  28245. if (otherMesh.checkCollisions !== current.checkCollisions) {
  28246. continue;
  28247. }
  28248. currentPool.push(otherMesh);
  28249. globalLength--;
  28250. globalPool.splice(subIndex, 1);
  28251. subIndex--;
  28252. }
  28253. if (currentPool.length < 2) {
  28254. continue;
  28255. }
  28256. // Merge meshes
  28257. BABYLON.Mesh.MergeMeshes(currentPool);
  28258. }
  28259. return true;
  28260. };
  28261. }
  28262. return MergeMeshesOptimization;
  28263. })(SceneOptimization);
  28264. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  28265. // Options
  28266. var SceneOptimizerOptions = (function () {
  28267. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  28268. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  28269. if (trackerDuration === void 0) { trackerDuration = 2000; }
  28270. this.targetFrameRate = targetFrameRate;
  28271. this.trackerDuration = trackerDuration;
  28272. this.optimizations = new Array();
  28273. }
  28274. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  28275. var result = new SceneOptimizerOptions(targetFrameRate);
  28276. var priority = 0;
  28277. result.optimizations.push(new MergeMeshesOptimization(priority));
  28278. result.optimizations.push(new ShadowsOptimization(priority));
  28279. result.optimizations.push(new LensFlaresOptimization(priority));
  28280. // Next priority
  28281. priority++;
  28282. result.optimizations.push(new PostProcessesOptimization(priority));
  28283. result.optimizations.push(new ParticlesOptimization(priority));
  28284. // Next priority
  28285. priority++;
  28286. result.optimizations.push(new TextureOptimization(priority, 1024));
  28287. return result;
  28288. };
  28289. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  28290. var result = new SceneOptimizerOptions(targetFrameRate);
  28291. var priority = 0;
  28292. result.optimizations.push(new MergeMeshesOptimization(priority));
  28293. result.optimizations.push(new ShadowsOptimization(priority));
  28294. result.optimizations.push(new LensFlaresOptimization(priority));
  28295. // Next priority
  28296. priority++;
  28297. result.optimizations.push(new PostProcessesOptimization(priority));
  28298. result.optimizations.push(new ParticlesOptimization(priority));
  28299. // Next priority
  28300. priority++;
  28301. result.optimizations.push(new TextureOptimization(priority, 512));
  28302. // Next priority
  28303. priority++;
  28304. result.optimizations.push(new RenderTargetsOptimization(priority));
  28305. // Next priority
  28306. priority++;
  28307. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  28308. return result;
  28309. };
  28310. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  28311. var result = new SceneOptimizerOptions(targetFrameRate);
  28312. var priority = 0;
  28313. result.optimizations.push(new MergeMeshesOptimization(priority));
  28314. result.optimizations.push(new ShadowsOptimization(priority));
  28315. result.optimizations.push(new LensFlaresOptimization(priority));
  28316. // Next priority
  28317. priority++;
  28318. result.optimizations.push(new PostProcessesOptimization(priority));
  28319. result.optimizations.push(new ParticlesOptimization(priority));
  28320. // Next priority
  28321. priority++;
  28322. result.optimizations.push(new TextureOptimization(priority, 256));
  28323. // Next priority
  28324. priority++;
  28325. result.optimizations.push(new RenderTargetsOptimization(priority));
  28326. // Next priority
  28327. priority++;
  28328. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  28329. return result;
  28330. };
  28331. return SceneOptimizerOptions;
  28332. })();
  28333. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  28334. // Scene optimizer tool
  28335. var SceneOptimizer = (function () {
  28336. function SceneOptimizer() {
  28337. }
  28338. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  28339. // TODO: add an epsilon
  28340. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  28341. if (onSuccess) {
  28342. onSuccess();
  28343. }
  28344. return;
  28345. }
  28346. // Apply current level of optimizations
  28347. var allDone = true;
  28348. var noOptimizationApplied = true;
  28349. for (var index = 0; index < options.optimizations.length; index++) {
  28350. var optimization = options.optimizations[index];
  28351. if (optimization.priority === currentPriorityLevel) {
  28352. noOptimizationApplied = false;
  28353. allDone = allDone && optimization.apply(scene);
  28354. }
  28355. }
  28356. // If no optimization was applied, this is a failure :(
  28357. if (noOptimizationApplied) {
  28358. if (onFailure) {
  28359. onFailure();
  28360. }
  28361. return;
  28362. }
  28363. // If all optimizations were done, move to next level
  28364. if (allDone) {
  28365. currentPriorityLevel++;
  28366. }
  28367. // Let's the system running for a specific amount of time before checking FPS
  28368. scene.executeWhenReady(function () {
  28369. setTimeout(function () {
  28370. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  28371. }, options.trackerDuration);
  28372. });
  28373. };
  28374. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  28375. if (!options) {
  28376. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  28377. }
  28378. // Let's the system running for a specific amount of time before checking FPS
  28379. scene.executeWhenReady(function () {
  28380. setTimeout(function () {
  28381. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  28382. }, options.trackerDuration);
  28383. });
  28384. };
  28385. return SceneOptimizer;
  28386. })();
  28387. BABYLON.SceneOptimizer = SceneOptimizer;
  28388. })(BABYLON || (BABYLON = {}));
  28389. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  28390. var BABYLON;
  28391. (function (BABYLON) {
  28392. var Internals;
  28393. (function (Internals) {
  28394. var MeshLODLevel = (function () {
  28395. function MeshLODLevel(distance, mesh) {
  28396. this.distance = distance;
  28397. this.mesh = mesh;
  28398. }
  28399. return MeshLODLevel;
  28400. })();
  28401. Internals.MeshLODLevel = MeshLODLevel;
  28402. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28403. })(BABYLON || (BABYLON = {}));
  28404. //# sourceMappingURL=babylon.meshLODLevel.js.map
  28405. var BABYLON;
  28406. (function (BABYLON) {
  28407. var AudioEngine = (function () {
  28408. function AudioEngine() {
  28409. this._audioContext = null;
  28410. this._audioContextInitialized = false;
  28411. this.canUseWebAudio = false;
  28412. this.WarnedWebAudioUnsupported = false;
  28413. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  28414. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  28415. this.canUseWebAudio = true;
  28416. }
  28417. }
  28418. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  28419. get: function () {
  28420. if (!this._audioContextInitialized) {
  28421. this._initializeAudioContext();
  28422. }
  28423. return this._audioContext;
  28424. },
  28425. enumerable: true,
  28426. configurable: true
  28427. });
  28428. AudioEngine.prototype._initializeAudioContext = function () {
  28429. try {
  28430. if (this.canUseWebAudio) {
  28431. this._audioContext = new AudioContext();
  28432. // create a global volume gain node
  28433. this.masterGain = this._audioContext.createGain();
  28434. this.masterGain.gain.value = 1;
  28435. this.masterGain.connect(this._audioContext.destination);
  28436. this._audioContextInitialized = true;
  28437. }
  28438. }
  28439. catch (e) {
  28440. this.canUseWebAudio = false;
  28441. BABYLON.Tools.Error("Web Audio: " + e.message);
  28442. }
  28443. };
  28444. AudioEngine.prototype.dispose = function () {
  28445. if (this.canUseWebAudio && this._audioContextInitialized) {
  28446. if (this._connectedAnalyser) {
  28447. this._connectedAnalyser.stopDebugCanvas();
  28448. this._connectedAnalyser.dispose();
  28449. this.masterGain.disconnect();
  28450. this.masterGain.connect(this._audioContext.destination);
  28451. this._connectedAnalyser = null;
  28452. }
  28453. this.masterGain.gain.value = 1;
  28454. }
  28455. this.WarnedWebAudioUnsupported = false;
  28456. };
  28457. AudioEngine.prototype.getGlobalVolume = function () {
  28458. if (this.canUseWebAudio && this._audioContextInitialized) {
  28459. return this.masterGain.gain.value;
  28460. }
  28461. else {
  28462. return -1;
  28463. }
  28464. };
  28465. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  28466. if (this.canUseWebAudio && this._audioContextInitialized) {
  28467. this.masterGain.gain.value = newVolume;
  28468. }
  28469. };
  28470. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  28471. if (this._connectedAnalyser) {
  28472. this._connectedAnalyser.stopDebugCanvas();
  28473. }
  28474. if (this.canUseWebAudio && this._audioContextInitialized) {
  28475. this._connectedAnalyser = analyser;
  28476. this.masterGain.disconnect();
  28477. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  28478. }
  28479. };
  28480. return AudioEngine;
  28481. })();
  28482. BABYLON.AudioEngine = AudioEngine;
  28483. })(BABYLON || (BABYLON = {}));
  28484. //# sourceMappingURL=babylon.audioEngine.js.map
  28485. var BABYLON;
  28486. (function (BABYLON) {
  28487. var Sound = (function () {
  28488. /**
  28489. * Create a sound and attach it to a scene
  28490. * @param name Name of your sound
  28491. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  28492. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  28493. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  28494. */
  28495. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  28496. var _this = this;
  28497. this.autoplay = false;
  28498. this.loop = false;
  28499. this.useCustomAttenuation = false;
  28500. this.spatialSound = false;
  28501. this.refDistance = 1;
  28502. this.rolloffFactor = 1;
  28503. this.maxDistance = 100;
  28504. this.distanceModel = "linear";
  28505. this._panningModel = "equalpower";
  28506. this._playbackRate = 1;
  28507. this._startTime = 0;
  28508. this._startOffset = 0;
  28509. this._position = BABYLON.Vector3.Zero();
  28510. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  28511. this._volume = 1;
  28512. this._isLoaded = false;
  28513. this._isReadyToPlay = false;
  28514. this.isPlaying = false;
  28515. this.isPaused = false;
  28516. this._isDirectional = false;
  28517. // Used if you'd like to create a directional sound.
  28518. // If not set, the sound will be omnidirectional
  28519. this._coneInnerAngle = 360;
  28520. this._coneOuterAngle = 360;
  28521. this._coneOuterGain = 0;
  28522. this.name = name;
  28523. this._scene = scene;
  28524. this._readyToPlayCallback = readyToPlayCallback;
  28525. // Default custom attenuation function is a linear attenuation
  28526. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  28527. if (currentDistance < maxDistance) {
  28528. return currentVolume * (1 - currentDistance / maxDistance);
  28529. }
  28530. else {
  28531. return 0;
  28532. }
  28533. };
  28534. if (options) {
  28535. this.autoplay = options.autoplay || false;
  28536. this.loop = options.loop || false;
  28537. // if volume === 0, we need another way to check this option
  28538. if (options.volume !== undefined) {
  28539. this._volume = options.volume;
  28540. }
  28541. this.spatialSound = options.spatialSound || false;
  28542. this.maxDistance = options.maxDistance || 100;
  28543. this.useCustomAttenuation = options.useCustomAttenuation || false;
  28544. this.rolloffFactor = options.rolloffFactor || 1;
  28545. this.refDistance = options.refDistance || 1;
  28546. this.distanceModel = options.distanceModel || "linear";
  28547. this._playbackRate = options.playbackRate || 1;
  28548. }
  28549. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28550. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  28551. this._soundGain.gain.value = this._volume;
  28552. this._inputAudioNode = this._soundGain;
  28553. this._ouputAudioNode = this._soundGain;
  28554. if (this.spatialSound) {
  28555. this._createSpatialParameters();
  28556. }
  28557. this._scene.mainSoundTrack.AddSound(this);
  28558. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  28559. if (urlOrArrayBuffer) {
  28560. // If it's an URL
  28561. if (typeof (urlOrArrayBuffer) === "string") {
  28562. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  28563. _this._soundLoaded(data);
  28564. }, null, null, true);
  28565. }
  28566. else {
  28567. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  28568. this._soundLoaded(urlOrArrayBuffer);
  28569. }
  28570. else {
  28571. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  28572. }
  28573. }
  28574. }
  28575. }
  28576. else {
  28577. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  28578. this._scene.mainSoundTrack.AddSound(this);
  28579. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  28580. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  28581. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  28582. }
  28583. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  28584. if (this._readyToPlayCallback) {
  28585. window.setTimeout(function () {
  28586. _this._readyToPlayCallback();
  28587. }, 1000);
  28588. }
  28589. }
  28590. }
  28591. Sound.prototype.dispose = function () {
  28592. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  28593. if (this.isPlaying) {
  28594. this.stop();
  28595. }
  28596. this._isReadyToPlay = false;
  28597. if (this.soundTrackId === -1) {
  28598. this._scene.mainSoundTrack.RemoveSound(this);
  28599. }
  28600. else {
  28601. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  28602. }
  28603. if (this._soundGain) {
  28604. this._soundGain.disconnect();
  28605. this._soundGain = null;
  28606. }
  28607. if (this._soundPanner) {
  28608. this._soundPanner.disconnect();
  28609. this._soundPanner = null;
  28610. }
  28611. if (this._soundSource) {
  28612. this._soundSource.disconnect();
  28613. this._soundSource = null;
  28614. }
  28615. this._audioBuffer = null;
  28616. if (this._connectedMesh) {
  28617. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  28618. this._connectedMesh = null;
  28619. }
  28620. }
  28621. };
  28622. Sound.prototype._soundLoaded = function (audioData) {
  28623. var _this = this;
  28624. this._isLoaded = true;
  28625. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  28626. _this._audioBuffer = buffer;
  28627. _this._isReadyToPlay = true;
  28628. if (_this.autoplay) {
  28629. _this.play();
  28630. }
  28631. if (_this._readyToPlayCallback) {
  28632. _this._readyToPlayCallback();
  28633. }
  28634. }, function (error) {
  28635. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  28636. });
  28637. };
  28638. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  28639. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28640. this._audioBuffer = audioBuffer;
  28641. this._isReadyToPlay = true;
  28642. }
  28643. };
  28644. Sound.prototype.updateOptions = function (options) {
  28645. if (options) {
  28646. this.loop = options.loop || this.loop;
  28647. this.maxDistance = options.maxDistance || this.maxDistance;
  28648. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  28649. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  28650. this.refDistance = options.refDistance || this.refDistance;
  28651. this.distanceModel = options.distanceModel || this.distanceModel;
  28652. this._playbackRate = options.playbackRate || this._playbackRate;
  28653. }
  28654. };
  28655. Sound.prototype._createSpatialParameters = function () {
  28656. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28657. if (this._scene.headphone) {
  28658. this._panningModel = "HRTF";
  28659. }
  28660. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  28661. if (this.useCustomAttenuation) {
  28662. // Tricks to disable in a way embedded Web Audio attenuation
  28663. this._soundPanner.distanceModel = "linear";
  28664. this._soundPanner.maxDistance = Number.MAX_VALUE;
  28665. this._soundPanner.refDistance = 1;
  28666. this._soundPanner.rolloffFactor = 1;
  28667. this._soundPanner.panningModel = this._panningModel;
  28668. }
  28669. else {
  28670. this._soundPanner.distanceModel = this.distanceModel;
  28671. this._soundPanner.maxDistance = this.maxDistance;
  28672. this._soundPanner.refDistance = this.refDistance;
  28673. this._soundPanner.rolloffFactor = this.rolloffFactor;
  28674. this._soundPanner.panningModel = this._panningModel;
  28675. }
  28676. this._soundPanner.connect(this._ouputAudioNode);
  28677. this._inputAudioNode = this._soundPanner;
  28678. }
  28679. };
  28680. Sound.prototype.switchPanningModelToHRTF = function () {
  28681. this._panningModel = "HRTF";
  28682. this._switchPanningModel();
  28683. };
  28684. Sound.prototype.switchPanningModelToEqualPower = function () {
  28685. this._panningModel = "equalpower";
  28686. this._switchPanningModel();
  28687. };
  28688. Sound.prototype._switchPanningModel = function () {
  28689. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28690. this._soundPanner.panningModel = this._panningModel;
  28691. }
  28692. };
  28693. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  28694. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28695. this._ouputAudioNode.disconnect();
  28696. this._ouputAudioNode.connect(soundTrackAudioNode);
  28697. }
  28698. };
  28699. /**
  28700. * Transform this sound into a directional source
  28701. * @param coneInnerAngle Size of the inner cone in degree
  28702. * @param coneOuterAngle Size of the outer cone in degree
  28703. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  28704. */
  28705. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  28706. if (coneOuterAngle < coneInnerAngle) {
  28707. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  28708. return;
  28709. }
  28710. this._coneInnerAngle = coneInnerAngle;
  28711. this._coneOuterAngle = coneOuterAngle;
  28712. this._coneOuterGain = coneOuterGain;
  28713. this._isDirectional = true;
  28714. if (this.isPlaying && this.loop) {
  28715. this.stop();
  28716. this.play();
  28717. }
  28718. };
  28719. Sound.prototype.setPosition = function (newPosition) {
  28720. this._position = newPosition;
  28721. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28722. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  28723. }
  28724. };
  28725. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  28726. this._localDirection = newLocalDirection;
  28727. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  28728. this._updateDirection();
  28729. }
  28730. };
  28731. Sound.prototype._updateDirection = function () {
  28732. var mat = this._connectedMesh.getWorldMatrix();
  28733. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  28734. direction.normalize();
  28735. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  28736. };
  28737. Sound.prototype.updateDistanceFromListener = function () {
  28738. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  28739. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  28740. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  28741. }
  28742. };
  28743. Sound.prototype.setAttenuationFunction = function (callback) {
  28744. this._customAttenuationFunction = callback;
  28745. };
  28746. /**
  28747. * Play the sound
  28748. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  28749. */
  28750. Sound.prototype.play = function (time) {
  28751. var _this = this;
  28752. if (this._isReadyToPlay && this._scene.audioEnabled) {
  28753. try {
  28754. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  28755. if (!this._soundSource) {
  28756. if (this.spatialSound) {
  28757. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  28758. if (this._isDirectional) {
  28759. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  28760. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  28761. this._soundPanner.coneOuterGain = this._coneOuterGain;
  28762. if (this._connectedMesh) {
  28763. this._updateDirection();
  28764. }
  28765. else {
  28766. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  28767. }
  28768. }
  28769. }
  28770. }
  28771. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  28772. this._soundSource.buffer = this._audioBuffer;
  28773. this._soundSource.connect(this._inputAudioNode);
  28774. this._soundSource.loop = this.loop;
  28775. this._soundSource.playbackRate.value = this._playbackRate;
  28776. this._startTime = startTime;
  28777. this._soundSource.onended = function () {
  28778. _this._onended();
  28779. };
  28780. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  28781. this.isPlaying = true;
  28782. this.isPaused = false;
  28783. }
  28784. catch (ex) {
  28785. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  28786. }
  28787. }
  28788. };
  28789. Sound.prototype._onended = function () {
  28790. this.isPlaying = false;
  28791. if (this.onended) {
  28792. this.onended();
  28793. }
  28794. };
  28795. /**
  28796. * Stop the sound
  28797. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  28798. */
  28799. Sound.prototype.stop = function (time) {
  28800. if (this.isPlaying) {
  28801. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  28802. this._soundSource.stop(stopTime);
  28803. this.isPlaying = false;
  28804. }
  28805. };
  28806. Sound.prototype.pause = function () {
  28807. if (this.isPlaying) {
  28808. this.stop(0);
  28809. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  28810. this.isPaused = true;
  28811. }
  28812. };
  28813. Sound.prototype.setVolume = function (newVolume, time) {
  28814. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  28815. if (time) {
  28816. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  28817. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  28818. }
  28819. else {
  28820. this._soundGain.gain.value = newVolume;
  28821. }
  28822. }
  28823. this._volume = newVolume;
  28824. };
  28825. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  28826. this._playbackRate = newPlaybackRate;
  28827. if (this.isPlaying) {
  28828. this._soundSource.playbackRate.value = this._playbackRate;
  28829. }
  28830. };
  28831. Sound.prototype.getVolume = function () {
  28832. return this._volume;
  28833. };
  28834. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  28835. var _this = this;
  28836. this._connectedMesh = meshToConnectTo;
  28837. if (!this.spatialSound) {
  28838. this._createSpatialParameters();
  28839. this.spatialSound = true;
  28840. if (this.isPlaying && this.loop) {
  28841. this.stop();
  28842. this.play();
  28843. }
  28844. }
  28845. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  28846. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  28847. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  28848. };
  28849. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  28850. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  28851. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  28852. this._updateDirection();
  28853. }
  28854. };
  28855. return Sound;
  28856. })();
  28857. BABYLON.Sound = Sound;
  28858. })(BABYLON || (BABYLON = {}));
  28859. //# sourceMappingURL=babylon.sound.js.map
  28860. var BABYLON;
  28861. (function (BABYLON) {
  28862. var SoundTrack = (function () {
  28863. function SoundTrack(scene, options) {
  28864. this.id = -1;
  28865. this._isMainTrack = false;
  28866. this._scene = scene;
  28867. this._audioEngine = BABYLON.Engine.audioEngine;
  28868. this.soundCollection = new Array();
  28869. if (this._audioEngine.canUseWebAudio) {
  28870. this._trackGain = this._audioEngine.audioContext.createGain();
  28871. this._trackGain.connect(this._audioEngine.masterGain);
  28872. if (options) {
  28873. if (options.volume) {
  28874. this._trackGain.gain.value = options.volume;
  28875. }
  28876. if (options.mainTrack) {
  28877. this._isMainTrack = options.mainTrack;
  28878. }
  28879. }
  28880. }
  28881. if (!this._isMainTrack) {
  28882. this._scene.soundTracks.push(this);
  28883. this.id = this._scene.soundTracks.length - 1;
  28884. }
  28885. }
  28886. SoundTrack.prototype.dispose = function () {
  28887. if (this._audioEngine.canUseWebAudio) {
  28888. if (this._connectedAnalyser) {
  28889. this._connectedAnalyser.stopDebugCanvas();
  28890. }
  28891. while (this.soundCollection.length) {
  28892. this.soundCollection[0].dispose();
  28893. }
  28894. this._trackGain.disconnect();
  28895. this._trackGain = null;
  28896. }
  28897. };
  28898. SoundTrack.prototype.AddSound = function (sound) {
  28899. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28900. sound.connectToSoundTrackAudioNode(this._trackGain);
  28901. }
  28902. if (sound.soundTrackId) {
  28903. if (sound.soundTrackId === -1) {
  28904. this._scene.mainSoundTrack.RemoveSound(sound);
  28905. }
  28906. else {
  28907. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  28908. }
  28909. }
  28910. this.soundCollection.push(sound);
  28911. sound.soundTrackId = this.id;
  28912. };
  28913. SoundTrack.prototype.RemoveSound = function (sound) {
  28914. var index = this.soundCollection.indexOf(sound);
  28915. if (index !== -1) {
  28916. this.soundCollection.splice(index, 1);
  28917. }
  28918. };
  28919. SoundTrack.prototype.setVolume = function (newVolume) {
  28920. if (this._audioEngine.canUseWebAudio) {
  28921. this._trackGain.gain.value = newVolume;
  28922. }
  28923. };
  28924. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  28925. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28926. for (var i = 0; i < this.soundCollection.length; i++) {
  28927. this.soundCollection[i].switchPanningModelToHRTF();
  28928. }
  28929. }
  28930. };
  28931. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  28932. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28933. for (var i = 0; i < this.soundCollection.length; i++) {
  28934. this.soundCollection[i].switchPanningModelToEqualPower();
  28935. }
  28936. }
  28937. };
  28938. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  28939. if (this._connectedAnalyser) {
  28940. this._connectedAnalyser.stopDebugCanvas();
  28941. }
  28942. this._connectedAnalyser = analyser;
  28943. if (this._audioEngine.canUseWebAudio) {
  28944. this._trackGain.disconnect();
  28945. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  28946. }
  28947. };
  28948. return SoundTrack;
  28949. })();
  28950. BABYLON.SoundTrack = SoundTrack;
  28951. })(BABYLON || (BABYLON = {}));
  28952. //# sourceMappingURL=babylon.soundtrack.js.map
  28953. var BABYLON;
  28954. (function (BABYLON) {
  28955. var DebugLayer = (function () {
  28956. function DebugLayer(scene) {
  28957. var _this = this;
  28958. this._transformationMatrix = BABYLON.Matrix.Identity();
  28959. this._enabled = false;
  28960. this._labelsEnabled = false;
  28961. this._displayStatistics = true;
  28962. this._displayTree = false;
  28963. this._displayLogs = false;
  28964. this._identityMatrix = BABYLON.Matrix.Identity();
  28965. this.axisRatio = 0.02;
  28966. this.accentColor = "orange";
  28967. this._scene = scene;
  28968. this._syncPositions = function () {
  28969. var engine = _this._scene.getEngine();
  28970. var canvasRect = engine.getRenderingCanvasClientRect();
  28971. if (_this._showUI) {
  28972. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  28973. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  28974. _this._statsDiv.style.width = "400px";
  28975. _this._statsDiv.style.height = "auto";
  28976. _this._statsSubsetDiv.style.maxHeight = "240px";
  28977. _this._optionsDiv.style.left = "0px";
  28978. _this._optionsDiv.style.top = "10px";
  28979. _this._optionsDiv.style.width = "200px";
  28980. _this._optionsDiv.style.height = "auto";
  28981. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  28982. _this._logDiv.style.left = "0px";
  28983. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  28984. _this._logDiv.style.width = "600px";
  28985. _this._logDiv.style.height = "160px";
  28986. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  28987. _this._treeDiv.style.top = "10px";
  28988. _this._treeDiv.style.width = "300px";
  28989. _this._treeDiv.style.height = "auto";
  28990. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  28991. }
  28992. _this._globalDiv.style.left = canvasRect.left + "px";
  28993. _this._globalDiv.style.top = canvasRect.top + "px";
  28994. _this._drawingCanvas.style.left = "0px";
  28995. _this._drawingCanvas.style.top = "0px";
  28996. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  28997. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  28998. var devicePixelRatio = window.devicePixelRatio || 1;
  28999. var context = _this._drawingContext;
  29000. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  29001. _this._ratio = devicePixelRatio / backingStoreRatio;
  29002. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29003. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29004. };
  29005. this._onCanvasClick = function (evt) {
  29006. _this._clickPosition = {
  29007. x: evt.clientX * _this._ratio,
  29008. y: evt.clientY * _this._ratio
  29009. };
  29010. };
  29011. this._syncUI = function () {
  29012. if (_this._showUI) {
  29013. if (_this._displayStatistics) {
  29014. _this._displayStats();
  29015. _this._statsDiv.style.display = "";
  29016. }
  29017. else {
  29018. _this._statsDiv.style.display = "none";
  29019. }
  29020. if (_this._displayLogs) {
  29021. _this._logDiv.style.display = "";
  29022. }
  29023. else {
  29024. _this._logDiv.style.display = "none";
  29025. }
  29026. if (_this._displayTree) {
  29027. _this._treeDiv.style.display = "";
  29028. if (_this._needToRefreshMeshesTree) {
  29029. _this._needToRefreshMeshesTree = false;
  29030. _this._refreshMeshesTreeContent();
  29031. }
  29032. }
  29033. else {
  29034. _this._treeDiv.style.display = "none";
  29035. }
  29036. }
  29037. };
  29038. this._syncData = function () {
  29039. if (_this._labelsEnabled || !_this._showUI) {
  29040. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29041. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29042. var engine = _this._scene.getEngine();
  29043. var viewport = _this._camera.viewport;
  29044. var globalViewport = viewport.toGlobal(engine);
  29045. // Meshes
  29046. var meshes = _this._camera.getActiveMeshes();
  29047. for (var index = 0; index < meshes.length; index++) {
  29048. var mesh = meshes.data[index];
  29049. var position = mesh.getBoundingInfo().boundingSphere.center;
  29050. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29051. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29052. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29053. }
  29054. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29055. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  29056. mesh.renderOverlay = !mesh.renderOverlay;
  29057. }, function () {
  29058. return mesh.renderOverlay ? 'red' : 'black';
  29059. });
  29060. }
  29061. }
  29062. // Cameras
  29063. var cameras = _this._scene.cameras;
  29064. for (index = 0; index < cameras.length; index++) {
  29065. var camera = cameras[index];
  29066. if (camera === _this._camera) {
  29067. continue;
  29068. }
  29069. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29070. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29071. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29072. _this._camera.detachControl(engine.getRenderingCanvas());
  29073. _this._camera = camera;
  29074. _this._camera.attachControl(engine.getRenderingCanvas());
  29075. }, function () {
  29076. return "purple";
  29077. });
  29078. }
  29079. }
  29080. // Lights
  29081. var lights = _this._scene.lights;
  29082. for (index = 0; index < lights.length; index++) {
  29083. var light = lights[index];
  29084. if (light.position) {
  29085. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29086. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29087. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29088. light.setEnabled(!light.isEnabled());
  29089. }, function () {
  29090. return light.isEnabled() ? "orange" : "gray";
  29091. });
  29092. }
  29093. }
  29094. }
  29095. }
  29096. _this._clickPosition = undefined;
  29097. };
  29098. }
  29099. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29100. while (this._treeSubsetDiv.hasChildNodes()) {
  29101. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29102. }
  29103. // Add meshes
  29104. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29105. sortedArray.sort(function (a, b) {
  29106. if (a.name === b.name) {
  29107. return 0;
  29108. }
  29109. return (a.name > b.name) ? 1 : -1;
  29110. });
  29111. for (var index = 0; index < sortedArray.length; index++) {
  29112. var mesh = sortedArray[index];
  29113. if (!mesh.isEnabled()) {
  29114. continue;
  29115. }
  29116. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29117. m.isVisible = element.checked;
  29118. }, mesh);
  29119. }
  29120. };
  29121. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29122. this._drawingContext.beginPath();
  29123. this._drawingContext.moveTo(zero.x, zero.y);
  29124. this._drawingContext.lineTo(unit.x, unit.y);
  29125. this._drawingContext.strokeStyle = color;
  29126. this._drawingContext.lineWidth = 4;
  29127. this._drawingContext.stroke();
  29128. this._drawingContext.font = "normal 14px Segoe UI";
  29129. this._drawingContext.fillStyle = color;
  29130. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29131. };
  29132. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29133. var position = mesh.getBoundingInfo().boundingSphere.center;
  29134. var worldMatrix = mesh.getWorldMatrix();
  29135. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29136. var unit = (unprojectedVector.subtract(position)).length();
  29137. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29138. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29139. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29140. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29141. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29142. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29143. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29144. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29145. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29146. };
  29147. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29148. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29149. this._drawingContext.font = "normal 12px Segoe UI";
  29150. var textMetrics = this._drawingContext.measureText(text);
  29151. var centerX = projectedPosition.x - textMetrics.width / 2;
  29152. var centerY = projectedPosition.y;
  29153. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29154. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29155. onClick();
  29156. }
  29157. this._drawingContext.beginPath();
  29158. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29159. this._drawingContext.fillStyle = getFillStyle();
  29160. this._drawingContext.globalAlpha = 0.5;
  29161. this._drawingContext.fill();
  29162. this._drawingContext.globalAlpha = 1.0;
  29163. this._drawingContext.strokeStyle = '#FFFFFF';
  29164. this._drawingContext.lineWidth = 1;
  29165. this._drawingContext.stroke();
  29166. this._drawingContext.fillStyle = "#FFFFFF";
  29167. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29168. this._drawingContext.beginPath();
  29169. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29170. this._drawingContext.fill();
  29171. }
  29172. };
  29173. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29174. if (!this._clickPosition) {
  29175. return false;
  29176. }
  29177. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29178. return false;
  29179. }
  29180. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29181. return false;
  29182. }
  29183. return true;
  29184. };
  29185. DebugLayer.prototype.isVisible = function () {
  29186. return this._enabled;
  29187. };
  29188. DebugLayer.prototype.hide = function () {
  29189. if (!this._enabled) {
  29190. return;
  29191. }
  29192. this._enabled = false;
  29193. var engine = this._scene.getEngine();
  29194. this._scene.unregisterBeforeRender(this._syncData);
  29195. this._scene.unregisterAfterRender(this._syncUI);
  29196. document.body.removeChild(this._globalDiv);
  29197. window.removeEventListener("resize", this._syncPositions);
  29198. this._scene.forceShowBoundingBoxes = false;
  29199. this._scene.forceWireframe = false;
  29200. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29201. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29202. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29203. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29204. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29205. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29206. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29207. this._scene.shadowsEnabled = true;
  29208. this._scene.particlesEnabled = true;
  29209. this._scene.postProcessesEnabled = true;
  29210. this._scene.collisionsEnabled = true;
  29211. this._scene.lightsEnabled = true;
  29212. this._scene.texturesEnabled = true;
  29213. this._scene.lensFlaresEnabled = true;
  29214. this._scene.proceduralTexturesEnabled = true;
  29215. this._scene.renderTargetsEnabled = true;
  29216. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29217. };
  29218. DebugLayer.prototype.show = function (showUI, camera) {
  29219. if (showUI === void 0) { showUI = true; }
  29220. if (camera === void 0) { camera = null; }
  29221. if (this._enabled) {
  29222. return;
  29223. }
  29224. this._enabled = true;
  29225. if (camera) {
  29226. this._camera = camera;
  29227. }
  29228. else {
  29229. this._camera = this._scene.activeCamera;
  29230. }
  29231. this._showUI = showUI;
  29232. var engine = this._scene.getEngine();
  29233. this._globalDiv = document.createElement("div");
  29234. document.body.appendChild(this._globalDiv);
  29235. this._generateDOMelements();
  29236. window.addEventListener("resize", this._syncPositions);
  29237. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29238. this._syncPositions();
  29239. this._scene.registerBeforeRender(this._syncData);
  29240. this._scene.registerAfterRender(this._syncUI);
  29241. };
  29242. DebugLayer.prototype._clearLabels = function () {
  29243. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29244. for (var index = 0; index < this._scene.meshes.length; index++) {
  29245. var mesh = this._scene.meshes[index];
  29246. mesh.renderOverlay = false;
  29247. }
  29248. };
  29249. DebugLayer.prototype._generateheader = function (root, text) {
  29250. var header = document.createElement("div");
  29251. header.innerHTML = text + "&nbsp;";
  29252. header.style.textAlign = "right";
  29253. header.style.width = "100%";
  29254. header.style.color = "white";
  29255. header.style.backgroundColor = "Black";
  29256. header.style.padding = "5px 5px 4px 0px";
  29257. header.style.marginLeft = "-5px";
  29258. header.style.fontWeight = "bold";
  29259. root.appendChild(header);
  29260. };
  29261. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29262. var label = document.createElement("label");
  29263. label.innerHTML = title;
  29264. label.style.color = color;
  29265. root.appendChild(label);
  29266. root.appendChild(document.createElement("br"));
  29267. };
  29268. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29269. if (tag === void 0) { tag = null; }
  29270. var label = document.createElement("label");
  29271. var boundingBoxesCheckbox = document.createElement("input");
  29272. boundingBoxesCheckbox.type = "checkbox";
  29273. boundingBoxesCheckbox.checked = initialState;
  29274. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29275. task(evt.target, tag);
  29276. });
  29277. label.appendChild(boundingBoxesCheckbox);
  29278. var container = document.createElement("span");
  29279. var leftPart = document.createElement("span");
  29280. var rightPart = document.createElement("span");
  29281. rightPart.style.cssFloat = "right";
  29282. leftPart.innerHTML = leftTitle;
  29283. rightPart.innerHTML = rightTitle;
  29284. rightPart.style.fontSize = "12px";
  29285. rightPart.style.maxWidth = "200px";
  29286. container.appendChild(leftPart);
  29287. container.appendChild(rightPart);
  29288. label.appendChild(container);
  29289. root.appendChild(label);
  29290. root.appendChild(document.createElement("br"));
  29291. };
  29292. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29293. if (tag === void 0) { tag = null; }
  29294. var label = document.createElement("label");
  29295. var checkBox = document.createElement("input");
  29296. checkBox.type = "checkbox";
  29297. checkBox.checked = initialState;
  29298. checkBox.addEventListener("change", function (evt) {
  29299. task(evt.target, tag);
  29300. });
  29301. label.appendChild(checkBox);
  29302. label.appendChild(document.createTextNode(title));
  29303. root.appendChild(label);
  29304. root.appendChild(document.createElement("br"));
  29305. };
  29306. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29307. if (tag === void 0) { tag = null; }
  29308. var button = document.createElement("button");
  29309. button.innerHTML = title;
  29310. button.style.height = "24px";
  29311. button.style.color = "#444444";
  29312. button.style.border = "1px solid white";
  29313. button.className = "debugLayerButton";
  29314. button.addEventListener("click", function (evt) {
  29315. task(evt.target, tag);
  29316. });
  29317. root.appendChild(button);
  29318. root.appendChild(document.createElement("br"));
  29319. };
  29320. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29321. if (tag === void 0) { tag = null; }
  29322. var label = document.createElement("label");
  29323. var boundingBoxesRadio = document.createElement("input");
  29324. boundingBoxesRadio.type = "radio";
  29325. boundingBoxesRadio.name = name;
  29326. boundingBoxesRadio.checked = initialState;
  29327. boundingBoxesRadio.addEventListener("change", function (evt) {
  29328. task(evt.target, tag);
  29329. });
  29330. label.appendChild(boundingBoxesRadio);
  29331. label.appendChild(document.createTextNode(title));
  29332. root.appendChild(label);
  29333. root.appendChild(document.createElement("br"));
  29334. };
  29335. DebugLayer.prototype._generateDOMelements = function () {
  29336. var _this = this;
  29337. this._globalDiv.id = "DebugLayer";
  29338. this._globalDiv.style.position = "absolute";
  29339. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29340. this._globalDiv.style.fontSize = "14px";
  29341. this._globalDiv.style.color = "white";
  29342. // Drawing canvas
  29343. this._drawingCanvas = document.createElement("canvas");
  29344. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29345. this._drawingCanvas.style.position = "absolute";
  29346. this._drawingCanvas.style.pointerEvents = "none";
  29347. this._drawingContext = this._drawingCanvas.getContext("2d");
  29348. this._globalDiv.appendChild(this._drawingCanvas);
  29349. if (this._showUI) {
  29350. var background = "rgba(128, 128, 128, 0.4)";
  29351. var border = "rgb(180, 180, 180) solid 1px";
  29352. // Stats
  29353. this._statsDiv = document.createElement("div");
  29354. this._statsDiv.id = "DebugLayerStats";
  29355. this._statsDiv.style.border = border;
  29356. this._statsDiv.style.position = "absolute";
  29357. this._statsDiv.style.background = background;
  29358. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29359. this._generateheader(this._statsDiv, "STATISTICS");
  29360. this._statsSubsetDiv = document.createElement("div");
  29361. this._statsSubsetDiv.style.paddingTop = "5px";
  29362. this._statsSubsetDiv.style.paddingBottom = "5px";
  29363. this._statsSubsetDiv.style.overflowY = "auto";
  29364. this._statsDiv.appendChild(this._statsSubsetDiv);
  29365. // Tree
  29366. this._treeDiv = document.createElement("div");
  29367. this._treeDiv.id = "DebugLayerTree";
  29368. this._treeDiv.style.border = border;
  29369. this._treeDiv.style.position = "absolute";
  29370. this._treeDiv.style.background = background;
  29371. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29372. this._treeDiv.style.display = "none";
  29373. this._generateheader(this._treeDiv, "MESHES TREE");
  29374. this._treeSubsetDiv = document.createElement("div");
  29375. this._treeSubsetDiv.style.paddingTop = "5px";
  29376. this._treeSubsetDiv.style.paddingRight = "5px";
  29377. this._treeSubsetDiv.style.overflowY = "auto";
  29378. this._treeSubsetDiv.style.maxHeight = "300px";
  29379. this._treeDiv.appendChild(this._treeSubsetDiv);
  29380. this._needToRefreshMeshesTree = true;
  29381. // Logs
  29382. this._logDiv = document.createElement("div");
  29383. this._logDiv.style.border = border;
  29384. this._logDiv.id = "DebugLayerLogs";
  29385. this._logDiv.style.position = "absolute";
  29386. this._logDiv.style.background = background;
  29387. this._logDiv.style.padding = "0px 0px 0px 5px";
  29388. this._logDiv.style.display = "none";
  29389. this._generateheader(this._logDiv, "LOGS");
  29390. this._logSubsetDiv = document.createElement("div");
  29391. this._logSubsetDiv.style.height = "127px";
  29392. this._logSubsetDiv.style.paddingTop = "5px";
  29393. this._logSubsetDiv.style.overflowY = "auto";
  29394. this._logSubsetDiv.style.fontSize = "12px";
  29395. this._logSubsetDiv.style.fontFamily = "consolas";
  29396. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29397. this._logDiv.appendChild(this._logSubsetDiv);
  29398. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29399. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29400. };
  29401. // Options
  29402. this._optionsDiv = document.createElement("div");
  29403. this._optionsDiv.id = "DebugLayerOptions";
  29404. this._optionsDiv.style.border = border;
  29405. this._optionsDiv.style.position = "absolute";
  29406. this._optionsDiv.style.background = background;
  29407. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29408. this._optionsDiv.style.overflowY = "auto";
  29409. this._generateheader(this._optionsDiv, "OPTIONS");
  29410. this._optionsSubsetDiv = document.createElement("div");
  29411. this._optionsSubsetDiv.style.paddingTop = "5px";
  29412. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29413. this._optionsSubsetDiv.style.overflowY = "auto";
  29414. this._optionsSubsetDiv.style.maxHeight = "200px";
  29415. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29416. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29417. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  29418. _this._displayStatistics = element.checked;
  29419. });
  29420. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  29421. _this._displayLogs = element.checked;
  29422. });
  29423. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29424. _this._displayTree = element.checked;
  29425. _this._needToRefreshMeshesTree = true;
  29426. });
  29427. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29428. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29429. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  29430. _this._scene.forceShowBoundingBoxes = element.checked;
  29431. });
  29432. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29433. _this._labelsEnabled = element.checked;
  29434. if (!_this._labelsEnabled) {
  29435. _this._clearLabels();
  29436. }
  29437. });
  29438. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29439. if (element.checked) {
  29440. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29441. }
  29442. else {
  29443. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29444. }
  29445. });
  29446. ;
  29447. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29448. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29449. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29450. if (element.checked) {
  29451. _this._scene.forceWireframe = false;
  29452. _this._scene.forcePointsCloud = false;
  29453. }
  29454. });
  29455. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29456. if (element.checked) {
  29457. _this._scene.forceWireframe = true;
  29458. _this._scene.forcePointsCloud = false;
  29459. }
  29460. });
  29461. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29462. if (element.checked) {
  29463. _this._scene.forceWireframe = false;
  29464. _this._scene.forcePointsCloud = true;
  29465. }
  29466. });
  29467. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29468. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29469. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  29470. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  29471. });
  29472. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  29473. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  29474. });
  29475. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  29476. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  29477. });
  29478. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  29479. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  29480. });
  29481. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  29482. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  29483. });
  29484. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  29485. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  29486. });
  29487. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  29488. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  29489. });
  29490. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  29491. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  29492. });
  29493. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29494. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29495. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  29496. _this._scene.animationsEnabled = element.checked;
  29497. });
  29498. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  29499. _this._scene.collisionsEnabled = element.checked;
  29500. });
  29501. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  29502. _this._scene.fogEnabled = element.checked;
  29503. });
  29504. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  29505. _this._scene.lensFlaresEnabled = element.checked;
  29506. });
  29507. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  29508. _this._scene.lightsEnabled = element.checked;
  29509. });
  29510. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  29511. _this._scene.particlesEnabled = element.checked;
  29512. });
  29513. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  29514. _this._scene.postProcessesEnabled = element.checked;
  29515. });
  29516. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  29517. _this._scene.proceduralTexturesEnabled = element.checked;
  29518. });
  29519. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  29520. _this._scene.renderTargetsEnabled = element.checked;
  29521. });
  29522. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  29523. _this._scene.shadowsEnabled = element.checked;
  29524. });
  29525. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  29526. _this._scene.skeletonsEnabled = element.checked;
  29527. });
  29528. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  29529. _this._scene.spritesEnabled = element.checked;
  29530. });
  29531. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  29532. _this._scene.texturesEnabled = element.checked;
  29533. });
  29534. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29535. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29536. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29537. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29538. if (element.checked) {
  29539. _this._scene.headphone = true;
  29540. }
  29541. });
  29542. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29543. if (element.checked) {
  29544. _this._scene.headphone = false;
  29545. }
  29546. });
  29547. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29548. _this._scene.audioEnabled = !element.checked;
  29549. });
  29550. }
  29551. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29552. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29553. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  29554. _this._scene.dumpNextRenderTargets = true;
  29555. });
  29556. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29557. this._globalDiv.appendChild(this._statsDiv);
  29558. this._globalDiv.appendChild(this._logDiv);
  29559. this._globalDiv.appendChild(this._optionsDiv);
  29560. this._globalDiv.appendChild(this._treeDiv);
  29561. }
  29562. };
  29563. DebugLayer.prototype._displayStats = function () {
  29564. var scene = this._scene;
  29565. var engine = scene.getEngine();
  29566. var glInfo = engine.getGlInfo();
  29567. 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>";
  29568. if (this.customStatsFunction) {
  29569. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29570. }
  29571. };
  29572. return DebugLayer;
  29573. })();
  29574. BABYLON.DebugLayer = DebugLayer;
  29575. })(BABYLON || (BABYLON = {}));
  29576. //# sourceMappingURL=babylon.debugLayer.js.map
  29577. var __extends = this.__extends || function (d, b) {
  29578. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  29579. function __() { this.constructor = d; }
  29580. __.prototype = b.prototype;
  29581. d.prototype = new __();
  29582. };
  29583. var BABYLON;
  29584. (function (BABYLON) {
  29585. var RawTexture = (function (_super) {
  29586. __extends(RawTexture, _super);
  29587. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  29588. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29589. if (invertY === void 0) { invertY = false; }
  29590. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29591. _super.call(this, null, scene, !generateMipMaps, invertY);
  29592. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  29593. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29594. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29595. }
  29596. // Statics
  29597. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29598. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29599. if (invertY === void 0) { invertY = false; }
  29600. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29601. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  29602. };
  29603. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29604. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29605. if (invertY === void 0) { invertY = false; }
  29606. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29607. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29608. };
  29609. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29610. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29611. if (invertY === void 0) { invertY = false; }
  29612. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29613. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29614. };
  29615. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29616. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29617. if (invertY === void 0) { invertY = false; }
  29618. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29619. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  29620. };
  29621. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29622. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29623. if (invertY === void 0) { invertY = false; }
  29624. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29625. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  29626. };
  29627. return RawTexture;
  29628. })(BABYLON.Texture);
  29629. BABYLON.RawTexture = RawTexture;
  29630. })(BABYLON || (BABYLON = {}));
  29631. //# sourceMappingURL=babylon.rawTexture.js.map
  29632. var __extends = this.__extends || function (d, b) {
  29633. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  29634. function __() { this.constructor = d; }
  29635. __.prototype = b.prototype;
  29636. d.prototype = new __();
  29637. };
  29638. var BABYLON;
  29639. (function (BABYLON) {
  29640. var IndexedVector2 = (function (_super) {
  29641. __extends(IndexedVector2, _super);
  29642. function IndexedVector2(original, index) {
  29643. _super.call(this, original.x, original.y);
  29644. this.index = index;
  29645. }
  29646. return IndexedVector2;
  29647. })(BABYLON.Vector2);
  29648. var PolygonPoints = (function () {
  29649. function PolygonPoints() {
  29650. this.elements = new Array();
  29651. }
  29652. PolygonPoints.prototype.add = function (originalPoints) {
  29653. var _this = this;
  29654. var result = new Array();
  29655. originalPoints.forEach(function (point) {
  29656. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  29657. var newPoint = new IndexedVector2(point, _this.elements.length);
  29658. result.push(newPoint);
  29659. _this.elements.push(newPoint);
  29660. }
  29661. });
  29662. return result;
  29663. };
  29664. PolygonPoints.prototype.computeBounds = function () {
  29665. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29666. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29667. this.elements.forEach(function (point) {
  29668. // x
  29669. if (point.x < lmin.x) {
  29670. lmin.x = point.x;
  29671. }
  29672. else if (point.x > lmax.x) {
  29673. lmax.x = point.x;
  29674. }
  29675. // y
  29676. if (point.y < lmin.y) {
  29677. lmin.y = point.y;
  29678. }
  29679. else if (point.y > lmax.y) {
  29680. lmax.y = point.y;
  29681. }
  29682. });
  29683. return {
  29684. min: lmin,
  29685. max: lmax,
  29686. width: lmax.x - lmin.x,
  29687. height: lmax.y - lmin.y
  29688. };
  29689. };
  29690. return PolygonPoints;
  29691. })();
  29692. var Polygon = (function () {
  29693. function Polygon() {
  29694. }
  29695. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  29696. return [
  29697. new BABYLON.Vector2(xmin, ymin),
  29698. new BABYLON.Vector2(xmax, ymin),
  29699. new BABYLON.Vector2(xmax, ymax),
  29700. new BABYLON.Vector2(xmin, ymax)
  29701. ];
  29702. };
  29703. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  29704. if (cx === void 0) { cx = 0; }
  29705. if (cy === void 0) { cy = 0; }
  29706. if (numberOfSides === void 0) { numberOfSides = 32; }
  29707. var result = new Array();
  29708. var angle = 0;
  29709. var increment = (Math.PI * 2) / numberOfSides;
  29710. for (var i = 0; i < numberOfSides; i++) {
  29711. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  29712. angle -= increment;
  29713. }
  29714. return result;
  29715. };
  29716. Polygon.Parse = function (input) {
  29717. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  29718. var i, result = [];
  29719. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  29720. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  29721. }
  29722. return result;
  29723. };
  29724. Polygon.StartingAt = function (x, y) {
  29725. return BABYLON.Path2.StartingAt(x, y);
  29726. };
  29727. return Polygon;
  29728. })();
  29729. BABYLON.Polygon = Polygon;
  29730. var PolygonMeshBuilder = (function () {
  29731. function PolygonMeshBuilder(name, contours, scene) {
  29732. this._points = new PolygonPoints();
  29733. if (!("poly2tri" in window)) {
  29734. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  29735. }
  29736. this._name = name;
  29737. this._scene = scene;
  29738. var points;
  29739. if (contours instanceof BABYLON.Path2) {
  29740. points = contours.getPoints();
  29741. }
  29742. else {
  29743. points = contours;
  29744. }
  29745. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  29746. }
  29747. PolygonMeshBuilder.prototype.addHole = function (hole) {
  29748. this._swctx.addHole(this._points.add(hole));
  29749. return this;
  29750. };
  29751. PolygonMeshBuilder.prototype.build = function (updatable) {
  29752. if (updatable === void 0) { updatable = false; }
  29753. var result = new BABYLON.Mesh(this._name, this._scene);
  29754. var normals = [];
  29755. var positions = [];
  29756. var uvs = [];
  29757. var bounds = this._points.computeBounds();
  29758. this._points.elements.forEach(function (p) {
  29759. normals.push(0, 1.0, 0);
  29760. positions.push(p.x, 0, p.y);
  29761. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  29762. });
  29763. var indices = [];
  29764. this._swctx.triangulate();
  29765. this._swctx.getTriangles().forEach(function (triangle) {
  29766. triangle.getPoints().forEach(function (point) {
  29767. indices.push(point.index);
  29768. });
  29769. });
  29770. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  29771. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  29772. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  29773. result.setIndices(indices);
  29774. return result;
  29775. };
  29776. return PolygonMeshBuilder;
  29777. })();
  29778. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  29779. })(BABYLON || (BABYLON = {}));
  29780. //# sourceMappingURL=babylon.polygonMesh.js.map
  29781. var BABYLON;
  29782. (function (BABYLON) {
  29783. var SimplificationSettings = (function () {
  29784. function SimplificationSettings(quality, distance, optimizeMesh) {
  29785. this.quality = quality;
  29786. this.distance = distance;
  29787. this.optimizeMesh = optimizeMesh;
  29788. }
  29789. return SimplificationSettings;
  29790. })();
  29791. BABYLON.SimplificationSettings = SimplificationSettings;
  29792. var SimplificationQueue = (function () {
  29793. function SimplificationQueue() {
  29794. this.running = false;
  29795. this._simplificationArray = [];
  29796. }
  29797. SimplificationQueue.prototype.addTask = function (task) {
  29798. this._simplificationArray.push(task);
  29799. };
  29800. SimplificationQueue.prototype.executeNext = function () {
  29801. var task = this._simplificationArray.pop();
  29802. if (task) {
  29803. this.running = true;
  29804. this.runSimplification(task);
  29805. }
  29806. else {
  29807. this.running = false;
  29808. }
  29809. };
  29810. SimplificationQueue.prototype.runSimplification = function (task) {
  29811. var _this = this;
  29812. if (task.parallelProcessing) {
  29813. //parallel simplifier
  29814. task.settings.forEach(function (setting) {
  29815. var simplifier = _this.getSimplifier(task);
  29816. simplifier.simplify(setting, function (newMesh) {
  29817. task.mesh.addLODLevel(setting.distance, newMesh);
  29818. newMesh.isVisible = true;
  29819. //check if it is the last
  29820. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  29821. //all done, run the success callback.
  29822. task.successCallback();
  29823. }
  29824. _this.executeNext();
  29825. });
  29826. });
  29827. }
  29828. else {
  29829. //single simplifier.
  29830. var simplifier = this.getSimplifier(task);
  29831. var runDecimation = function (setting, callback) {
  29832. simplifier.simplify(setting, function (newMesh) {
  29833. task.mesh.addLODLevel(setting.distance, newMesh);
  29834. newMesh.isVisible = true;
  29835. //run the next quality level
  29836. callback();
  29837. });
  29838. };
  29839. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  29840. runDecimation(task.settings[loop.index], function () {
  29841. loop.executeNext();
  29842. });
  29843. }, function () {
  29844. //execution ended, run the success callback.
  29845. if (task.successCallback) {
  29846. task.successCallback();
  29847. }
  29848. _this.executeNext();
  29849. });
  29850. }
  29851. };
  29852. SimplificationQueue.prototype.getSimplifier = function (task) {
  29853. switch (task.simplificationType) {
  29854. case 0 /* QUADRATIC */:
  29855. default:
  29856. return new QuadraticErrorSimplification(task.mesh);
  29857. }
  29858. };
  29859. return SimplificationQueue;
  29860. })();
  29861. BABYLON.SimplificationQueue = SimplificationQueue;
  29862. /**
  29863. * The implemented types of simplification.
  29864. * At the moment only Quadratic Error Decimation is implemented.
  29865. */
  29866. (function (SimplificationType) {
  29867. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  29868. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  29869. var SimplificationType = BABYLON.SimplificationType;
  29870. var DecimationTriangle = (function () {
  29871. function DecimationTriangle(vertices) {
  29872. this.vertices = vertices;
  29873. this.error = new Array(4);
  29874. this.deleted = false;
  29875. this.isDirty = false;
  29876. this.deletePending = false;
  29877. this.borderFactor = 0;
  29878. }
  29879. return DecimationTriangle;
  29880. })();
  29881. BABYLON.DecimationTriangle = DecimationTriangle;
  29882. var DecimationVertex = (function () {
  29883. function DecimationVertex(position, id) {
  29884. this.position = position;
  29885. this.id = id;
  29886. this.isBorder = true;
  29887. this.q = new QuadraticMatrix();
  29888. this.triangleCount = 0;
  29889. this.triangleStart = 0;
  29890. this.originalOffsets = [];
  29891. }
  29892. DecimationVertex.prototype.updatePosition = function (newPosition) {
  29893. this.position.copyFrom(newPosition);
  29894. };
  29895. return DecimationVertex;
  29896. })();
  29897. BABYLON.DecimationVertex = DecimationVertex;
  29898. var QuadraticMatrix = (function () {
  29899. function QuadraticMatrix(data) {
  29900. this.data = new Array(10);
  29901. for (var i = 0; i < 10; ++i) {
  29902. if (data && data[i]) {
  29903. this.data[i] = data[i];
  29904. }
  29905. else {
  29906. this.data[i] = 0;
  29907. }
  29908. }
  29909. }
  29910. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  29911. 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];
  29912. return det;
  29913. };
  29914. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  29915. for (var i = 0; i < 10; ++i) {
  29916. this.data[i] += matrix.data[i];
  29917. }
  29918. };
  29919. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  29920. for (var i = 0; i < 10; ++i) {
  29921. this.data[i] += data[i];
  29922. }
  29923. };
  29924. QuadraticMatrix.prototype.add = function (matrix) {
  29925. var m = new QuadraticMatrix();
  29926. for (var i = 0; i < 10; ++i) {
  29927. m.data[i] = this.data[i] + matrix.data[i];
  29928. }
  29929. return m;
  29930. };
  29931. QuadraticMatrix.FromData = function (a, b, c, d) {
  29932. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  29933. };
  29934. //returning an array to avoid garbage collection
  29935. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  29936. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  29937. };
  29938. return QuadraticMatrix;
  29939. })();
  29940. BABYLON.QuadraticMatrix = QuadraticMatrix;
  29941. var Reference = (function () {
  29942. function Reference(vertexId, triangleId) {
  29943. this.vertexId = vertexId;
  29944. this.triangleId = triangleId;
  29945. }
  29946. return Reference;
  29947. })();
  29948. BABYLON.Reference = Reference;
  29949. /**
  29950. * An implementation of the Quadratic Error simplification algorithm.
  29951. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  29952. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  29953. * @author RaananW
  29954. */
  29955. var QuadraticErrorSimplification = (function () {
  29956. function QuadraticErrorSimplification(_mesh) {
  29957. this._mesh = _mesh;
  29958. this.initialized = false;
  29959. this.syncIterations = 5000;
  29960. this.aggressiveness = 7;
  29961. this.decimationIterations = 100;
  29962. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  29963. }
  29964. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  29965. var _this = this;
  29966. this.initDecimatedMesh();
  29967. //iterating through the submeshes array, one after the other.
  29968. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  29969. _this.initWithMesh(loop.index, function () {
  29970. _this.runDecimation(settings, loop.index, function () {
  29971. loop.executeNext();
  29972. });
  29973. }, settings.optimizeMesh);
  29974. }, function () {
  29975. setTimeout(function () {
  29976. successCallback(_this._reconstructedMesh);
  29977. }, 0);
  29978. });
  29979. };
  29980. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  29981. var _this = this;
  29982. var gCount = 0;
  29983. triangle.vertices.forEach(function (vertex) {
  29984. var count = 0;
  29985. var vPos = vertex.position;
  29986. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  29987. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  29988. ++count;
  29989. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  29990. ++count;
  29991. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  29992. ++count;
  29993. if (count > 1) {
  29994. ++gCount;
  29995. }
  29996. ;
  29997. });
  29998. if (gCount > 1) {
  29999. console.log(triangle, gCount);
  30000. }
  30001. return gCount > 1;
  30002. };
  30003. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30004. var _this = this;
  30005. var targetCount = ~~(this.triangles.length * settings.quality);
  30006. var deletedTriangles = 0;
  30007. var triangleCount = this.triangles.length;
  30008. var iterationFunction = function (iteration, callback) {
  30009. setTimeout(function () {
  30010. if (iteration % 5 === 0) {
  30011. _this.updateMesh(iteration === 0);
  30012. }
  30013. for (var i = 0; i < _this.triangles.length; ++i) {
  30014. _this.triangles[i].isDirty = false;
  30015. }
  30016. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30017. var trianglesIterator = function (i) {
  30018. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30019. var t = _this.triangles[tIdx];
  30020. if (!t)
  30021. return;
  30022. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30023. return;
  30024. }
  30025. for (var j = 0; j < 3; ++j) {
  30026. if (t.error[j] < threshold) {
  30027. var deleted0 = [];
  30028. var deleted1 = [];
  30029. var v0 = t.vertices[j];
  30030. var v1 = t.vertices[(j + 1) % 3];
  30031. if (v0.isBorder !== v1.isBorder)
  30032. continue;
  30033. var p = BABYLON.Vector3.Zero();
  30034. var n = BABYLON.Vector3.Zero();
  30035. var uv = BABYLON.Vector2.Zero();
  30036. var color = new BABYLON.Color4(0, 0, 0, 1);
  30037. _this.calculateError(v0, v1, p, n, uv, color);
  30038. var delTr = [];
  30039. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30040. continue;
  30041. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30042. continue;
  30043. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30044. continue;
  30045. var uniqueArray = [];
  30046. delTr.forEach(function (deletedT) {
  30047. if (uniqueArray.indexOf(deletedT) === -1) {
  30048. deletedT.deletePending = true;
  30049. uniqueArray.push(deletedT);
  30050. }
  30051. });
  30052. if (uniqueArray.length % 2 != 0) {
  30053. continue;
  30054. }
  30055. v0.q = v1.q.add(v0.q);
  30056. v0.updatePosition(p);
  30057. var tStart = _this.references.length;
  30058. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30059. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30060. var tCount = _this.references.length - tStart;
  30061. if (tCount <= v0.triangleCount) {
  30062. if (tCount) {
  30063. for (var c = 0; c < tCount; c++) {
  30064. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30065. }
  30066. }
  30067. }
  30068. else {
  30069. v0.triangleStart = tStart;
  30070. }
  30071. v0.triangleCount = tCount;
  30072. break;
  30073. }
  30074. }
  30075. };
  30076. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  30077. return (triangleCount - deletedTriangles <= targetCount);
  30078. });
  30079. }, 0);
  30080. };
  30081. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30082. if (triangleCount - deletedTriangles <= targetCount)
  30083. loop.breakLoop();
  30084. else {
  30085. iterationFunction(loop.index, function () {
  30086. loop.executeNext();
  30087. });
  30088. }
  30089. }, function () {
  30090. setTimeout(function () {
  30091. //reconstruct this part of the mesh
  30092. _this.reconstructMesh(submeshIndex);
  30093. successCallback();
  30094. }, 0);
  30095. });
  30096. };
  30097. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30098. var _this = this;
  30099. this.vertices = [];
  30100. this.triangles = [];
  30101. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30102. var indices = this._mesh.getIndices();
  30103. var submesh = this._mesh.subMeshes[submeshIndex];
  30104. var findInVertices = function (positionToSearch) {
  30105. if (optimizeMesh) {
  30106. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30107. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30108. return _this.vertices[ii];
  30109. }
  30110. }
  30111. }
  30112. return null;
  30113. };
  30114. var vertexReferences = [];
  30115. var vertexInit = function (i) {
  30116. var offset = i + submesh.verticesStart;
  30117. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30118. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30119. vertex.originalOffsets.push(offset);
  30120. if (vertex.id == _this.vertices.length) {
  30121. _this.vertices.push(vertex);
  30122. }
  30123. vertexReferences.push(vertex.id);
  30124. };
  30125. //var totalVertices = mesh.getTotalVertices();
  30126. var totalVertices = submesh.verticesCount;
  30127. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30128. var indicesInit = function (i) {
  30129. var offset = (submesh.indexStart / 3) + i;
  30130. var pos = (offset * 3);
  30131. var i0 = indices[pos + 0];
  30132. var i1 = indices[pos + 1];
  30133. var i2 = indices[pos + 2];
  30134. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30135. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30136. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30137. var triangle = new DecimationTriangle([v0, v1, v2]);
  30138. triangle.originalOffset = pos;
  30139. _this.triangles.push(triangle);
  30140. };
  30141. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30142. _this.init(callback);
  30143. });
  30144. });
  30145. };
  30146. QuadraticErrorSimplification.prototype.init = function (callback) {
  30147. var _this = this;
  30148. var triangleInit1 = function (i) {
  30149. var t = _this.triangles[i];
  30150. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30151. for (var j = 0; j < 3; j++) {
  30152. 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))));
  30153. }
  30154. };
  30155. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30156. var triangleInit2 = function (i) {
  30157. var t = _this.triangles[i];
  30158. for (var j = 0; j < 3; ++j) {
  30159. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30160. }
  30161. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30162. };
  30163. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30164. _this.initialized = true;
  30165. callback();
  30166. });
  30167. });
  30168. };
  30169. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30170. var newTriangles = [];
  30171. var i;
  30172. for (i = 0; i < this.vertices.length; ++i) {
  30173. this.vertices[i].triangleCount = 0;
  30174. }
  30175. var t;
  30176. var j;
  30177. for (i = 0; i < this.triangles.length; ++i) {
  30178. if (!this.triangles[i].deleted) {
  30179. t = this.triangles[i];
  30180. for (j = 0; j < 3; ++j) {
  30181. t.vertices[j].triangleCount = 1;
  30182. }
  30183. newTriangles.push(t);
  30184. }
  30185. }
  30186. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  30187. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  30188. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  30189. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  30190. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30191. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30192. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30193. var vertexCount = 0;
  30194. for (i = 0; i < this.vertices.length; ++i) {
  30195. var vertex = this.vertices[i];
  30196. vertex.id = vertexCount;
  30197. if (vertex.triangleCount) {
  30198. vertex.originalOffsets.forEach(function (originalOffset) {
  30199. newPositionData.push(vertex.position.x);
  30200. newPositionData.push(vertex.position.y);
  30201. newPositionData.push(vertex.position.z);
  30202. newNormalData.push(normalData[originalOffset * 3]);
  30203. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30204. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30205. if (uvs && uvs.length) {
  30206. newUVsData.push(uvs[(originalOffset * 2)]);
  30207. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30208. }
  30209. else if (colorsData && colorsData.length) {
  30210. newColorsData.push(colorsData[(originalOffset * 4)]);
  30211. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30212. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30213. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30214. }
  30215. ++vertexCount;
  30216. });
  30217. }
  30218. }
  30219. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30220. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30221. var submeshesArray = this._reconstructedMesh.subMeshes;
  30222. this._reconstructedMesh.subMeshes = [];
  30223. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30224. var originalIndices = this._mesh.getIndices();
  30225. for (i = 0; i < newTriangles.length; ++i) {
  30226. var t = newTriangles[i];
  30227. //now get the new referencing point for each vertex
  30228. [0, 1, 2].forEach(function (idx) {
  30229. var id = originalIndices[t.originalOffset + idx];
  30230. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30231. if (offset < 0)
  30232. offset = 0;
  30233. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30234. });
  30235. }
  30236. //overwriting the old vertex buffers and indices.
  30237. this._reconstructedMesh.setIndices(newIndicesArray);
  30238. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30239. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30240. if (newUVsData.length > 0)
  30241. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30242. if (newColorsData.length > 0)
  30243. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30244. //create submesh
  30245. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30246. if (submeshIndex > 0) {
  30247. this._reconstructedMesh.subMeshes = [];
  30248. submeshesArray.forEach(function (submesh) {
  30249. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30250. });
  30251. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30252. }
  30253. };
  30254. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30255. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30256. this._reconstructedMesh.material = this._mesh.material;
  30257. this._reconstructedMesh.parent = this._mesh.parent;
  30258. this._reconstructedMesh.isVisible = false;
  30259. };
  30260. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30261. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30262. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30263. if (t.deleted)
  30264. continue;
  30265. var s = this.references[vertex1.triangleStart + i].vertexId;
  30266. var v1 = t.vertices[(s + 1) % 3];
  30267. var v2 = t.vertices[(s + 2) % 3];
  30268. if ((v1 === vertex2 || v2 === vertex2)) {
  30269. deletedArray[i] = true;
  30270. delTr.push(t);
  30271. continue;
  30272. }
  30273. var d1 = v1.position.subtract(point);
  30274. d1 = d1.normalize();
  30275. var d2 = v2.position.subtract(point);
  30276. d2 = d2.normalize();
  30277. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30278. return true;
  30279. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30280. deletedArray[i] = false;
  30281. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30282. return true;
  30283. }
  30284. return false;
  30285. };
  30286. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30287. var newDeleted = deletedTriangles;
  30288. for (var i = 0; i < vertex.triangleCount; ++i) {
  30289. var ref = this.references[vertex.triangleStart + i];
  30290. var t = this.triangles[ref.triangleId];
  30291. if (t.deleted)
  30292. continue;
  30293. if (deletedArray[i] && t.deletePending) {
  30294. t.deleted = true;
  30295. newDeleted++;
  30296. continue;
  30297. }
  30298. t.vertices[ref.vertexId] = origVertex;
  30299. t.isDirty = true;
  30300. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30301. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30302. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30303. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30304. this.references.push(ref);
  30305. }
  30306. return newDeleted;
  30307. };
  30308. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30309. for (var i = 0; i < this.vertices.length; ++i) {
  30310. var vCount = [];
  30311. var vId = [];
  30312. var v = this.vertices[i];
  30313. var j;
  30314. for (j = 0; j < v.triangleCount; ++j) {
  30315. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30316. for (var ii = 0; ii < 3; ii++) {
  30317. var ofs = 0;
  30318. var vv = triangle.vertices[ii];
  30319. while (ofs < vCount.length) {
  30320. if (vId[ofs] === vv.id)
  30321. break;
  30322. ++ofs;
  30323. }
  30324. if (ofs === vCount.length) {
  30325. vCount.push(1);
  30326. vId.push(vv.id);
  30327. }
  30328. else {
  30329. vCount[ofs]++;
  30330. }
  30331. }
  30332. }
  30333. for (j = 0; j < vCount.length; ++j) {
  30334. if (vCount[j] === 1) {
  30335. this.vertices[vId[j]].isBorder = true;
  30336. }
  30337. else {
  30338. this.vertices[vId[j]].isBorder = false;
  30339. }
  30340. }
  30341. }
  30342. };
  30343. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30344. if (identifyBorders === void 0) { identifyBorders = false; }
  30345. var i;
  30346. if (!identifyBorders) {
  30347. var newTrianglesVector = [];
  30348. for (i = 0; i < this.triangles.length; ++i) {
  30349. if (!this.triangles[i].deleted) {
  30350. newTrianglesVector.push(this.triangles[i]);
  30351. }
  30352. }
  30353. this.triangles = newTrianglesVector;
  30354. }
  30355. for (i = 0; i < this.vertices.length; ++i) {
  30356. this.vertices[i].triangleCount = 0;
  30357. this.vertices[i].triangleStart = 0;
  30358. }
  30359. var t;
  30360. var j;
  30361. var v;
  30362. for (i = 0; i < this.triangles.length; ++i) {
  30363. t = this.triangles[i];
  30364. for (j = 0; j < 3; ++j) {
  30365. v = t.vertices[j];
  30366. v.triangleCount++;
  30367. }
  30368. }
  30369. var tStart = 0;
  30370. for (i = 0; i < this.vertices.length; ++i) {
  30371. this.vertices[i].triangleStart = tStart;
  30372. tStart += this.vertices[i].triangleCount;
  30373. this.vertices[i].triangleCount = 0;
  30374. }
  30375. var newReferences = new Array(this.triangles.length * 3);
  30376. for (i = 0; i < this.triangles.length; ++i) {
  30377. t = this.triangles[i];
  30378. for (j = 0; j < 3; ++j) {
  30379. v = t.vertices[j];
  30380. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30381. v.triangleCount++;
  30382. }
  30383. }
  30384. this.references = newReferences;
  30385. if (identifyBorders) {
  30386. this.identifyBorder();
  30387. }
  30388. };
  30389. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30390. var x = point.x;
  30391. var y = point.y;
  30392. var z = point.z;
  30393. 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];
  30394. };
  30395. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30396. var q = vertex1.q.add(vertex2.q);
  30397. var border = vertex1.isBorder && vertex2.isBorder;
  30398. var error = 0;
  30399. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30400. if (qDet !== 0 && !border) {
  30401. if (!pointResult) {
  30402. pointResult = BABYLON.Vector3.Zero();
  30403. }
  30404. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30405. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30406. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30407. error = this.vertexError(q, pointResult);
  30408. }
  30409. else {
  30410. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30411. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30412. var error1 = this.vertexError(q, vertex1.position);
  30413. var error2 = this.vertexError(q, vertex2.position);
  30414. var error3 = this.vertexError(q, p3);
  30415. error = Math.min(error1, error2, error3);
  30416. if (error === error1) {
  30417. if (pointResult) {
  30418. pointResult.copyFrom(vertex1.position);
  30419. }
  30420. }
  30421. else if (error === error2) {
  30422. if (pointResult) {
  30423. pointResult.copyFrom(vertex2.position);
  30424. }
  30425. }
  30426. else {
  30427. if (pointResult) {
  30428. pointResult.copyFrom(p3);
  30429. }
  30430. }
  30431. }
  30432. return error;
  30433. };
  30434. return QuadraticErrorSimplification;
  30435. })();
  30436. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30437. })(BABYLON || (BABYLON = {}));
  30438. //# sourceMappingURL=babylon.meshSimplification.js.map
  30439. var BABYLON;
  30440. (function (BABYLON) {
  30441. var Analyser = (function () {
  30442. function Analyser(scene) {
  30443. this.SMOOTHING = 0.75;
  30444. this.FFT_SIZE = 512;
  30445. this.BARGRAPHAMPLITUDE = 256;
  30446. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  30447. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  30448. this._scene = scene;
  30449. this._audioEngine = BABYLON.Engine.audioEngine;
  30450. if (this._audioEngine.canUseWebAudio) {
  30451. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  30452. this._webAudioAnalyser.minDecibels = -140;
  30453. this._webAudioAnalyser.maxDecibels = 0;
  30454. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30455. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30456. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  30457. }
  30458. }
  30459. Analyser.prototype.getFrequencyBinCount = function () {
  30460. if (this._audioEngine.canUseWebAudio) {
  30461. return this._webAudioAnalyser.frequencyBinCount;
  30462. }
  30463. else {
  30464. return 0;
  30465. }
  30466. };
  30467. Analyser.prototype.getByteFrequencyData = function () {
  30468. if (this._audioEngine.canUseWebAudio) {
  30469. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30470. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30471. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  30472. }
  30473. return this._byteFreqs;
  30474. };
  30475. Analyser.prototype.getByteTimeDomainData = function () {
  30476. if (this._audioEngine.canUseWebAudio) {
  30477. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30478. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30479. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  30480. }
  30481. return this._byteTime;
  30482. };
  30483. Analyser.prototype.getFloatFrequencyData = function () {
  30484. if (this._audioEngine.canUseWebAudio) {
  30485. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30486. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30487. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  30488. }
  30489. return this._floatFreqs;
  30490. };
  30491. Analyser.prototype.drawDebugCanvas = function () {
  30492. var _this = this;
  30493. if (this._audioEngine.canUseWebAudio) {
  30494. if (!this._debugCanvas) {
  30495. this._debugCanvas = document.createElement("canvas");
  30496. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  30497. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  30498. this._debugCanvas.style.position = "absolute";
  30499. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  30500. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  30501. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  30502. document.body.appendChild(this._debugCanvas);
  30503. this._registerFunc = function () {
  30504. _this.drawDebugCanvas();
  30505. };
  30506. this._scene.registerBeforeRender(this._registerFunc);
  30507. }
  30508. if (this._registerFunc) {
  30509. var workingArray = this.getByteFrequencyData();
  30510. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  30511. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  30512. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  30513. var value = workingArray[i];
  30514. var percent = value / this.BARGRAPHAMPLITUDE;
  30515. var height = this.DEBUGCANVASSIZE.height * percent;
  30516. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  30517. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  30518. var hue = i / this.getFrequencyBinCount() * 360;
  30519. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  30520. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  30521. }
  30522. }
  30523. }
  30524. };
  30525. Analyser.prototype.stopDebugCanvas = function () {
  30526. if (this._debugCanvas) {
  30527. this._scene.unregisterBeforeRender(this._registerFunc);
  30528. this._registerFunc = null;
  30529. document.body.removeChild(this._debugCanvas);
  30530. this._debugCanvas = null;
  30531. this._debugCanvasContext = null;
  30532. }
  30533. };
  30534. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  30535. if (this._audioEngine.canUseWebAudio) {
  30536. inputAudioNode.connect(this._webAudioAnalyser);
  30537. this._webAudioAnalyser.connect(outputAudioNode);
  30538. }
  30539. };
  30540. Analyser.prototype.dispose = function () {
  30541. if (this._audioEngine.canUseWebAudio) {
  30542. this._webAudioAnalyser.disconnect();
  30543. }
  30544. };
  30545. return Analyser;
  30546. })();
  30547. BABYLON.Analyser = Analyser;
  30548. })(BABYLON || (BABYLON = {}));
  30549. //# sourceMappingURL=babylon.analyser.js.map
  30550. var BABYLON;
  30551. (function (BABYLON) {
  30552. var DepthRenderer = (function () {
  30553. function DepthRenderer(scene, type) {
  30554. var _this = this;
  30555. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  30556. this._viewMatrix = BABYLON.Matrix.Zero();
  30557. this._projectionMatrix = BABYLON.Matrix.Zero();
  30558. this._transformMatrix = BABYLON.Matrix.Zero();
  30559. this._worldViewProjection = BABYLON.Matrix.Zero();
  30560. this._scene = scene;
  30561. var engine = scene.getEngine();
  30562. // Render target
  30563. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  30564. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30565. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30566. this._depthMap.refreshRate = 1;
  30567. this._depthMap.renderParticles = false;
  30568. this._depthMap.renderList = null;
  30569. // set default depth value to 1.0 (far away)
  30570. this._depthMap.onClear = function (engine) {
  30571. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  30572. };
  30573. // Custom render function
  30574. var renderSubMesh = function (subMesh) {
  30575. var mesh = subMesh.getRenderingMesh();
  30576. var scene = _this._scene;
  30577. var engine = scene.getEngine();
  30578. // Culling
  30579. engine.setState(subMesh.getMaterial().backFaceCulling);
  30580. // Managing instances
  30581. var batch = mesh._getInstancesRenderList(subMesh._id);
  30582. if (batch.mustReturn) {
  30583. return;
  30584. }
  30585. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  30586. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  30587. engine.enableEffect(_this._effect);
  30588. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  30589. var material = subMesh.getMaterial();
  30590. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30591. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  30592. // Alpha test
  30593. if (material && material.needAlphaTesting()) {
  30594. var alphaTexture = material.getAlphaTestTexture();
  30595. _this._effect.setTexture("diffuseSampler", alphaTexture);
  30596. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30597. }
  30598. // Bones
  30599. if (mesh.useBones) {
  30600. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30601. }
  30602. // Draw
  30603. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  30604. }
  30605. };
  30606. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  30607. var index;
  30608. for (index = 0; index < opaqueSubMeshes.length; index++) {
  30609. renderSubMesh(opaqueSubMeshes.data[index]);
  30610. }
  30611. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  30612. renderSubMesh(alphaTestSubMeshes.data[index]);
  30613. }
  30614. };
  30615. }
  30616. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  30617. var defines = [];
  30618. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30619. var mesh = subMesh.getMesh();
  30620. var scene = mesh.getScene();
  30621. var material = subMesh.getMaterial();
  30622. // Alpha test
  30623. if (material && material.needAlphaTesting()) {
  30624. defines.push("#define ALPHATEST");
  30625. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30626. attribs.push(BABYLON.VertexBuffer.UVKind);
  30627. defines.push("#define UV1");
  30628. }
  30629. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30630. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30631. defines.push("#define UV2");
  30632. }
  30633. }
  30634. // Bones
  30635. if (mesh.useBones) {
  30636. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30637. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30638. defines.push("#define BONES");
  30639. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30640. }
  30641. // Instances
  30642. if (useInstances) {
  30643. defines.push("#define INSTANCES");
  30644. attribs.push("world0");
  30645. attribs.push("world1");
  30646. attribs.push("world2");
  30647. attribs.push("world3");
  30648. }
  30649. // Get correct effect
  30650. var join = defines.join("\n");
  30651. if (this._cachedDefines !== join) {
  30652. this._cachedDefines = join;
  30653. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  30654. }
  30655. return this._effect.isReady();
  30656. };
  30657. DepthRenderer.prototype.getDepthMap = function () {
  30658. return this._depthMap;
  30659. };
  30660. // Methods
  30661. DepthRenderer.prototype.dispose = function () {
  30662. this._depthMap.dispose();
  30663. };
  30664. return DepthRenderer;
  30665. })();
  30666. BABYLON.DepthRenderer = DepthRenderer;
  30667. })(BABYLON || (BABYLON = {}));
  30668. //# sourceMappingURL=babylon.depthRenderer.js.map
  30669. var __extends = this.__extends || function (d, b) {
  30670. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30671. function __() { this.constructor = d; }
  30672. __.prototype = b.prototype;
  30673. d.prototype = new __();
  30674. };
  30675. var BABYLON;
  30676. (function (BABYLON) {
  30677. var SSAORenderingPipeline = (function (_super) {
  30678. __extends(SSAORenderingPipeline, _super);
  30679. /**
  30680. * @constructor
  30681. * @param {string} name - The rendering pipeline name
  30682. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  30683. * @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 }
  30684. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  30685. */
  30686. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  30687. var _this = this;
  30688. _super.call(this, scene.getEngine(), name);
  30689. // Members
  30690. /**
  30691. * The PassPostProcess id in the pipeline that contains the original scene color
  30692. * @type {string}
  30693. */
  30694. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  30695. /**
  30696. * The SSAO PostProcess id in the pipeline
  30697. * @type {string}
  30698. */
  30699. this.SSAORenderEffect = "SSAORenderEffect";
  30700. /**
  30701. * The horizontal blur PostProcess id in the pipeline
  30702. * @type {string}
  30703. */
  30704. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  30705. /**
  30706. * The vertical blur PostProcess id in the pipeline
  30707. * @type {string}
  30708. */
  30709. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  30710. /**
  30711. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  30712. * @type {string}
  30713. */
  30714. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  30715. /**
  30716. * The output strength of the SSAO post-process. Default value is 1.0.
  30717. * @type {number}
  30718. */
  30719. this.totalStrength = 1.0;
  30720. /**
  30721. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  30722. * @type {number}
  30723. */
  30724. this.radius = 0.0002;
  30725. /**
  30726. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  30727. * Must not be equal to fallOff and superior to fallOff.
  30728. * Default value is 0.0075
  30729. * @type {number}
  30730. */
  30731. this.area = 0.0075;
  30732. /**
  30733. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  30734. * Must not be equal to area and inferior to area.
  30735. * Default value is 0.0002
  30736. * @type {number}
  30737. */
  30738. this.fallOff = 0.0002;
  30739. this._firstUpdate = true;
  30740. this._scene = scene;
  30741. // Set up assets
  30742. this._createRandomTexture();
  30743. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  30744. var ssaoRatio = ratio.ssaoRatio || ratio;
  30745. var combineRatio = ratio.combineRatio || ratio;
  30746. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  30747. this._createSSAOPostProcess(ssaoRatio);
  30748. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  30749. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  30750. this._createSSAOCombinePostProcess(combineRatio);
  30751. // Set up pipeline
  30752. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  30753. return _this._originalColorPostProcess;
  30754. }, true));
  30755. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  30756. return _this._ssaoPostProcess;
  30757. }, true));
  30758. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  30759. return _this._blurHPostProcess;
  30760. }, true));
  30761. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  30762. return _this._blurVPostProcess;
  30763. }, true));
  30764. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  30765. return _this._ssaoCombinePostProcess;
  30766. }, true));
  30767. // Finish
  30768. scene.postProcessRenderPipelineManager.addPipeline(this);
  30769. if (cameras)
  30770. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  30771. }
  30772. // Public Methods
  30773. /**
  30774. * Returns the horizontal blur PostProcess
  30775. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  30776. */
  30777. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  30778. return this._blurHPostProcess;
  30779. };
  30780. /**
  30781. * Returns the vertical blur PostProcess
  30782. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  30783. */
  30784. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  30785. return this._blurVPostProcess;
  30786. };
  30787. /**
  30788. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  30789. */
  30790. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  30791. if (disableDepthRender === void 0) { disableDepthRender = false; }
  30792. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  30793. this._originalColorPostProcess = undefined;
  30794. this._ssaoPostProcess = undefined;
  30795. this._blurHPostProcess = undefined;
  30796. this._blurVPostProcess = undefined;
  30797. this._ssaoCombinePostProcess = undefined;
  30798. this._randomTexture.dispose();
  30799. if (disableDepthRender)
  30800. this._scene.disableDepthRenderer();
  30801. };
  30802. // Private Methods
  30803. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  30804. var _this = this;
  30805. var sampleSphere = [
  30806. 0.5381,
  30807. 0.1856,
  30808. -0.4319,
  30809. 0.1379,
  30810. 0.2486,
  30811. 0.4430,
  30812. 0.3371,
  30813. 0.5679,
  30814. -0.0057,
  30815. -0.6999,
  30816. -0.0451,
  30817. -0.0019,
  30818. 0.0689,
  30819. -0.1598,
  30820. -0.8547,
  30821. 0.0560,
  30822. 0.0069,
  30823. -0.1843,
  30824. -0.0146,
  30825. 0.1402,
  30826. 0.0762,
  30827. 0.0100,
  30828. -0.1924,
  30829. -0.0344,
  30830. -0.3577,
  30831. -0.5301,
  30832. -0.4358,
  30833. -0.3169,
  30834. 0.1063,
  30835. 0.0158,
  30836. 0.0103,
  30837. -0.5869,
  30838. 0.0046,
  30839. -0.0897,
  30840. -0.4940,
  30841. 0.3287,
  30842. 0.7119,
  30843. -0.0154,
  30844. -0.0918,
  30845. -0.0533,
  30846. 0.0596,
  30847. -0.5411,
  30848. 0.0352,
  30849. -0.0631,
  30850. 0.5460,
  30851. -0.4776,
  30852. 0.2847,
  30853. -0.0271
  30854. ];
  30855. var samplesFactor = 1.0 / 16.0;
  30856. 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);
  30857. this._ssaoPostProcess.onApply = function (effect) {
  30858. if (_this._firstUpdate) {
  30859. effect.setArray3("sampleSphere", sampleSphere);
  30860. effect.setFloat("samplesFactor", samplesFactor);
  30861. effect.setFloat("randTextureTiles", 4.0 / ratio);
  30862. _this._firstUpdate = false;
  30863. }
  30864. effect.setFloat("totalStrength", _this.totalStrength);
  30865. effect.setFloat("radius", _this.radius);
  30866. effect.setFloat("area", _this.area);
  30867. effect.setFloat("fallOff", _this.fallOff);
  30868. effect.setTexture("textureSampler", _this._depthTexture);
  30869. effect.setTexture("randomSampler", _this._randomTexture);
  30870. };
  30871. };
  30872. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  30873. var _this = this;
  30874. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30875. this._ssaoCombinePostProcess.onApply = function (effect) {
  30876. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  30877. };
  30878. };
  30879. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  30880. var size = 512;
  30881. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  30882. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30883. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30884. var context = this._randomTexture.getContext();
  30885. var rand = function (min, max) {
  30886. return Math.random() * (max - min) + min;
  30887. };
  30888. for (var x = 0; x < size; x++) {
  30889. for (var y = 0; y < size; y++) {
  30890. var randVector = BABYLON.Vector3.Zero();
  30891. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  30892. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  30893. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  30894. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  30895. context.fillRect(x, y, 1, 1);
  30896. }
  30897. }
  30898. this._randomTexture.update(false);
  30899. };
  30900. return SSAORenderingPipeline;
  30901. })(BABYLON.PostProcessRenderPipeline);
  30902. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  30903. })(BABYLON || (BABYLON = {}));
  30904. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  30905. var __extends = this.__extends || function (d, b) {
  30906. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30907. function __() { this.constructor = d; }
  30908. __.prototype = b.prototype;
  30909. d.prototype = new __();
  30910. };
  30911. var BABYLON;
  30912. (function (BABYLON) {
  30913. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  30914. var VolumetricLightScatteringPostProcess = (function (_super) {
  30915. __extends(VolumetricLightScatteringPostProcess, _super);
  30916. /**
  30917. * @constructor
  30918. * @param {string} name - The post-process name
  30919. * @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)
  30920. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  30921. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  30922. * @param {number} samples - The post-process quality, default 100
  30923. * @param {number} samplingMode - The post-process filtering mode
  30924. * @param {BABYLON.Engine} engine - The babylon engine
  30925. * @param {boolean} reusable - If the post-process is reusable
  30926. */
  30927. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  30928. var _this = this;
  30929. if (samples === void 0) { samples = 100; }
  30930. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  30931. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  30932. this._screenCoordinates = BABYLON.Vector2.Zero();
  30933. /**
  30934. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  30935. * @type {boolean}
  30936. */
  30937. this.useCustomMeshPosition = false;
  30938. /**
  30939. * If the post-process should inverse the light scattering direction
  30940. * @type {boolean}
  30941. */
  30942. this.invert = true;
  30943. /**
  30944. * Array containing the excluded meshes not rendered in the internal pass
  30945. */
  30946. this.excludedMeshes = new Array();
  30947. this.exposure = 0.3;
  30948. this.decay = 0.96815;
  30949. this.weight = 0.58767;
  30950. this.density = 0.926;
  30951. var scene = camera.getScene();
  30952. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  30953. // Configure mesh
  30954. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  30955. // Configure
  30956. this._createPass(scene, ratio.passRatio || ratio);
  30957. this.onApply = function (effect) {
  30958. _this._updateMeshScreenCoordinates(scene);
  30959. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  30960. effect.setFloat("exposure", _this.exposure);
  30961. effect.setFloat("decay", _this.decay);
  30962. effect.setFloat("weight", _this.weight);
  30963. effect.setFloat("density", _this.density);
  30964. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  30965. };
  30966. }
  30967. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  30968. var mesh = subMesh.getMesh();
  30969. var defines = [];
  30970. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30971. var material = subMesh.getMaterial();
  30972. var needUV = false;
  30973. // Render this.mesh as default
  30974. if (mesh === this.mesh) {
  30975. defines.push("#define BASIC_RENDER");
  30976. defines.push("#define NEED_UV");
  30977. needUV = true;
  30978. }
  30979. // Alpha test
  30980. if (material) {
  30981. if (material.needAlphaTesting() || mesh === this.mesh)
  30982. defines.push("#define ALPHATEST");
  30983. if (material.opacityTexture !== undefined) {
  30984. defines.push("#define OPACITY");
  30985. if (material.opacityTexture.getAlphaFromRGB)
  30986. defines.push("#define OPACITYRGB");
  30987. if (!needUV)
  30988. defines.push("#define NEED_UV");
  30989. }
  30990. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30991. attribs.push(BABYLON.VertexBuffer.UVKind);
  30992. defines.push("#define UV1");
  30993. }
  30994. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30995. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30996. defines.push("#define UV2");
  30997. }
  30998. }
  30999. // Bones
  31000. if (mesh.useBones) {
  31001. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31002. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31003. defines.push("#define BONES");
  31004. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31005. }
  31006. // Instances
  31007. if (useInstances) {
  31008. defines.push("#define INSTANCES");
  31009. attribs.push("world0");
  31010. attribs.push("world1");
  31011. attribs.push("world2");
  31012. attribs.push("world3");
  31013. }
  31014. // Get correct effect
  31015. var join = defines.join("\n");
  31016. if (this._cachedDefines !== join) {
  31017. this._cachedDefines = join;
  31018. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  31019. }
  31020. return this._volumetricLightScatteringPass.isReady();
  31021. };
  31022. /**
  31023. * Sets the new light position for light scattering effect
  31024. * @param {BABYLON.Vector3} The new custom light position
  31025. */
  31026. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  31027. this._customMeshPosition = position;
  31028. };
  31029. /**
  31030. * Returns the light position for light scattering effect
  31031. * @return {BABYLON.Vector3} The custom light position
  31032. */
  31033. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  31034. return this._customMeshPosition;
  31035. };
  31036. /**
  31037. * Disposes the internal assets and detaches the post-process from the camera
  31038. */
  31039. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  31040. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  31041. if (rttIndex !== -1) {
  31042. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  31043. }
  31044. this._volumetricLightScatteringRTT.dispose();
  31045. _super.prototype.dispose.call(this, camera);
  31046. };
  31047. /**
  31048. * Returns the render target texture used by the post-process
  31049. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  31050. */
  31051. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  31052. return this._volumetricLightScatteringRTT;
  31053. };
  31054. // Private methods
  31055. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  31056. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  31057. return true;
  31058. }
  31059. return false;
  31060. };
  31061. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  31062. var _this = this;
  31063. var engine = scene.getEngine();
  31064. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  31065. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31066. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31067. this._volumetricLightScatteringRTT.renderList = null;
  31068. this._volumetricLightScatteringRTT.renderParticles = false;
  31069. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  31070. // Custom render function for submeshes
  31071. var renderSubMesh = function (subMesh) {
  31072. var mesh = subMesh.getRenderingMesh();
  31073. if (_this._meshExcluded(mesh)) {
  31074. return;
  31075. }
  31076. var scene = mesh.getScene();
  31077. var engine = scene.getEngine();
  31078. // Culling
  31079. engine.setState(subMesh.getMaterial().backFaceCulling);
  31080. // Managing instances
  31081. var batch = mesh._getInstancesRenderList(subMesh._id);
  31082. if (batch.mustReturn) {
  31083. return;
  31084. }
  31085. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31086. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31087. engine.enableEffect(_this._volumetricLightScatteringPass);
  31088. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  31089. var material = subMesh.getMaterial();
  31090. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  31091. // Alpha test
  31092. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  31093. var alphaTexture = material.getAlphaTestTexture();
  31094. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  31095. if (alphaTexture) {
  31096. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31097. }
  31098. if (material.opacityTexture !== undefined) {
  31099. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  31100. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  31101. }
  31102. }
  31103. // Bones
  31104. if (mesh.useBones) {
  31105. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31106. }
  31107. // Draw
  31108. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  31109. }
  31110. };
  31111. // Render target texture callbacks
  31112. var savedSceneClearColor;
  31113. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  31114. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  31115. savedSceneClearColor = scene.clearColor;
  31116. scene.clearColor = sceneClearColor;
  31117. };
  31118. this._volumetricLightScatteringRTT.onAfterRender = function () {
  31119. scene.clearColor = savedSceneClearColor;
  31120. };
  31121. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  31122. var engine = scene.getEngine();
  31123. var index;
  31124. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31125. renderSubMesh(opaqueSubMeshes.data[index]);
  31126. }
  31127. engine.setAlphaTesting(true);
  31128. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31129. renderSubMesh(alphaTestSubMeshes.data[index]);
  31130. }
  31131. engine.setAlphaTesting(false);
  31132. if (transparentSubMeshes.length) {
  31133. for (index = 0; index < transparentSubMeshes.length; index++) {
  31134. var submesh = transparentSubMeshes.data[index];
  31135. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  31136. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  31137. }
  31138. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  31139. sortedArray.sort(function (a, b) {
  31140. // Alpha index first
  31141. if (a._alphaIndex > b._alphaIndex) {
  31142. return 1;
  31143. }
  31144. if (a._alphaIndex < b._alphaIndex) {
  31145. return -1;
  31146. }
  31147. // Then distance to camera
  31148. if (a._distanceToCamera < b._distanceToCamera) {
  31149. return 1;
  31150. }
  31151. if (a._distanceToCamera > b._distanceToCamera) {
  31152. return -1;
  31153. }
  31154. return 0;
  31155. });
  31156. // Render sub meshes
  31157. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31158. for (index = 0; index < sortedArray.length; index++) {
  31159. renderSubMesh(sortedArray[index]);
  31160. }
  31161. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31162. }
  31163. };
  31164. };
  31165. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  31166. var transform = scene.getTransformMatrix();
  31167. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  31168. this._screenCoordinates.x = pos.x / this._viewPort.width;
  31169. this._screenCoordinates.y = pos.y / this._viewPort.height;
  31170. if (this.invert)
  31171. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  31172. };
  31173. // Static methods
  31174. /**
  31175. * Creates a default mesh for the Volumeric Light Scattering post-process
  31176. * @param {string} The mesh name
  31177. * @param {BABYLON.Scene} The scene where to create the mesh
  31178. * @return {BABYLON.Mesh} the default mesh
  31179. */
  31180. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  31181. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  31182. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  31183. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  31184. return mesh;
  31185. };
  31186. return VolumetricLightScatteringPostProcess;
  31187. })(BABYLON.PostProcess);
  31188. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  31189. })(BABYLON || (BABYLON = {}));
  31190. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  31191. var __extends = this.__extends || function (d, b) {
  31192. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31193. function __() { this.constructor = d; }
  31194. __.prototype = b.prototype;
  31195. d.prototype = new __();
  31196. };
  31197. var BABYLON;
  31198. (function (BABYLON) {
  31199. var LensRenderingPipeline = (function (_super) {
  31200. __extends(LensRenderingPipeline, _super);
  31201. /**
  31202. * @constructor
  31203. *
  31204. * Effect parameters are as follow:
  31205. * {
  31206. * chromatic_aberration: number; // from 0 to x (1 for realism)
  31207. * edge_blur: number; // from 0 to x (1 for realism)
  31208. * distortion: number; // from 0 to x (1 for realism)
  31209. * grain_amount: number; // from 0 to 1
  31210. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  31211. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  31212. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  31213. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  31214. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  31215. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  31216. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  31217. * }
  31218. * Note: if an effect parameter is unset, effect is disabled
  31219. *
  31220. * @param {string} name - The rendering pipeline name
  31221. * @param {object} parameters - An object containing all parameters (see above)
  31222. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31223. * @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)
  31224. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31225. */
  31226. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  31227. var _this = this;
  31228. if (ratio === void 0) { ratio = 1.0; }
  31229. _super.call(this, scene.getEngine(), name);
  31230. // Lens effects can be of the following:
  31231. // - chromatic aberration (slight shift of RGB colors)
  31232. // - blur on the edge of the lens
  31233. // - lens distortion
  31234. // - depth-of-field blur & highlights enhancing
  31235. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  31236. // - grain effect (noise or custom texture)
  31237. // Two additional texture samplers are needed:
  31238. // - depth map (for depth-of-field)
  31239. // - grain texture
  31240. /**
  31241. * The chromatic aberration PostProcess id in the pipeline
  31242. * @type {string}
  31243. */
  31244. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  31245. /**
  31246. * The highlights enhancing PostProcess id in the pipeline
  31247. * @type {string}
  31248. */
  31249. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  31250. /**
  31251. * The depth-of-field PostProcess id in the pipeline
  31252. * @type {string}
  31253. */
  31254. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  31255. this._scene = scene;
  31256. // Fetch texture samplers
  31257. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31258. if (parameters.grain_texture) {
  31259. this._grainTexture = parameters.grain_texture;
  31260. }
  31261. else {
  31262. this._createGrainTexture();
  31263. }
  31264. // save parameters
  31265. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  31266. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  31267. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  31268. this._distortion = parameters.distortion ? parameters.distortion : 0;
  31269. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  31270. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  31271. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  31272. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  31273. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  31274. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  31275. // Create effects
  31276. this._createChromaticAberrationPostProcess(ratio);
  31277. this._createHighlightsPostProcess(ratio);
  31278. this._createDepthOfFieldPostProcess(ratio);
  31279. // Set up pipeline
  31280. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  31281. return _this._chromaticAberrationPostProcess;
  31282. }, true));
  31283. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () {
  31284. return _this._highlightsPostProcess;
  31285. }, true));
  31286. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  31287. return _this._depthOfFieldPostProcess;
  31288. }, true));
  31289. if (this._highlightsGain == -1) {
  31290. this._disableEffect(this.HighlightsEnhancingEffect, null);
  31291. }
  31292. // Finish
  31293. scene.postProcessRenderPipelineManager.addPipeline(this);
  31294. if (cameras) {
  31295. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31296. }
  31297. }
  31298. // public methods (self explanatory)
  31299. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  31300. this._edgeBlur = amount;
  31301. };
  31302. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  31303. this._edgeBlur = 0;
  31304. };
  31305. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  31306. this._grainAmount = amount;
  31307. };
  31308. LensRenderingPipeline.prototype.disableGrain = function () {
  31309. this._grainAmount = 0;
  31310. };
  31311. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  31312. this._chromaticAberration = amount;
  31313. };
  31314. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  31315. this._chromaticAberration = 0;
  31316. };
  31317. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  31318. this._distortion = amount;
  31319. };
  31320. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  31321. this._distortion = 0;
  31322. };
  31323. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  31324. this._dofDepth = amount;
  31325. };
  31326. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  31327. this._dofDepth = -1;
  31328. };
  31329. LensRenderingPipeline.prototype.setAperture = function (amount) {
  31330. this._dofAperture = amount;
  31331. };
  31332. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  31333. this._dofPentagon = true;
  31334. };
  31335. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  31336. this._dofPentagon = false;
  31337. };
  31338. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  31339. this._blurNoise = true;
  31340. };
  31341. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  31342. this._blurNoise = false;
  31343. };
  31344. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  31345. this._highlightsGain = amount;
  31346. };
  31347. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  31348. if (this._highlightsGain == -1) {
  31349. this._highlightsGain = 1.0;
  31350. }
  31351. this._highlightsThreshold = amount;
  31352. };
  31353. LensRenderingPipeline.prototype.disableHighlights = function () {
  31354. this._highlightsGain = -1;
  31355. };
  31356. /**
  31357. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  31358. */
  31359. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31360. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31361. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31362. this._chromaticAberrationPostProcess = undefined;
  31363. this._highlightsPostProcess = undefined;
  31364. this._depthOfFieldPostProcess = undefined;
  31365. this._grainTexture.dispose();
  31366. if (disableDepthRender)
  31367. this._scene.disableDepthRenderer();
  31368. };
  31369. // colors shifting and distortion
  31370. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  31371. var _this = this;
  31372. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31373. this._chromaticAberrationPostProcess.onApply = function (effect) {
  31374. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  31375. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31376. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31377. };
  31378. };
  31379. // highlights enhancing
  31380. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  31381. var _this = this;
  31382. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31383. this._highlightsPostProcess.onApply = function (effect) {
  31384. effect.setFloat('gain', _this._highlightsGain);
  31385. effect.setFloat('threshold', _this._highlightsThreshold);
  31386. effect.setBool('pentagon', _this._dofPentagon);
  31387. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  31388. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31389. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31390. };
  31391. };
  31392. // colors shifting and distortion
  31393. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  31394. var _this = this;
  31395. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  31396. "focus_depth",
  31397. "aperture",
  31398. "pentagon",
  31399. "maxZ",
  31400. "edge_blur",
  31401. "chromatic_aberration",
  31402. "distortion",
  31403. "blur_noise",
  31404. "grain_amount",
  31405. "screen_width",
  31406. "screen_height",
  31407. "highlights"
  31408. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31409. this._depthOfFieldPostProcess.onApply = function (effect) {
  31410. effect.setBool('blur_noise', _this._blurNoise);
  31411. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  31412. effect.setFloat('grain_amount', _this._grainAmount);
  31413. effect.setTexture("depthSampler", _this._depthTexture);
  31414. effect.setTexture("grainSampler", _this._grainTexture);
  31415. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  31416. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  31417. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31418. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31419. effect.setFloat('distortion', _this._distortion);
  31420. effect.setFloat('focus_depth', _this._dofDepth);
  31421. effect.setFloat('aperture', _this._dofAperture);
  31422. effect.setFloat('edge_blur', _this._edgeBlur);
  31423. effect.setBool('highlights', (_this._highlightsGain != -1));
  31424. };
  31425. };
  31426. // creates a black and white random noise texture, 512x512
  31427. LensRenderingPipeline.prototype._createGrainTexture = function () {
  31428. var size = 512;
  31429. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31430. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31431. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31432. var context = this._grainTexture.getContext();
  31433. var rand = function (min, max) {
  31434. return Math.random() * (max - min) + min;
  31435. };
  31436. var value;
  31437. for (var x = 0; x < size; x++) {
  31438. for (var y = 0; y < size; y++) {
  31439. value = Math.floor(rand(0.42, 0.58) * 255);
  31440. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  31441. context.fillRect(x, y, 1, 1);
  31442. }
  31443. }
  31444. this._grainTexture.update(false);
  31445. };
  31446. return LensRenderingPipeline;
  31447. })(BABYLON.PostProcessRenderPipeline);
  31448. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  31449. })(BABYLON || (BABYLON = {}));
  31450. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  31451. //
  31452. // This post-process allows the modification of rendered colors by using
  31453. // a 'look-up table' (LUT). This effect is also called Color Grading.
  31454. //
  31455. // The object needs to be provided an url to a texture containing the color
  31456. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  31457. // Use an image editing software to tweak the LUT to match your needs.
  31458. //
  31459. // For an example of a color LUT, see here:
  31460. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  31461. // For explanations on color grading, see here:
  31462. // http://udn.epicgames.com/Three/ColorGrading.html
  31463. //
  31464. var __extends = this.__extends || function (d, b) {
  31465. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31466. function __() { this.constructor = d; }
  31467. __.prototype = b.prototype;
  31468. d.prototype = new __();
  31469. };
  31470. var BABYLON;
  31471. (function (BABYLON) {
  31472. var ColorCorrectionPostProcess = (function (_super) {
  31473. __extends(ColorCorrectionPostProcess, _super);
  31474. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  31475. var _this = this;
  31476. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  31477. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  31478. this._colorTableTexture.anisotropicFilteringLevel = 1;
  31479. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31480. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31481. this.onApply = function (effect) {
  31482. effect.setTexture("colorTable", _this._colorTableTexture);
  31483. };
  31484. }
  31485. return ColorCorrectionPostProcess;
  31486. })(BABYLON.PostProcess);
  31487. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  31488. })(BABYLON || (BABYLON = {}));
  31489. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  31490. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 skyColor;\r\nuniform vec3 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec3 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = vec4(c, 1);\r\n\r\n}","colorPixelShader":"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n\tgl_FragColor = color;\n}","colorVertexShader":"precision highp float;\n\n// Attributes\nattribute vec3 position;\n\n// Uniforms\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\n}","colorCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\nuniform vec4 vSpecularColor;\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\nuniform vec3 vLightSpecular0;\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\nuniform vec3 vLightSpecular1;\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\nuniform vec3 vLightSpecular2;\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\nuniform vec3 vLightSpecular3;\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\nuniform mat4 view;\r\n\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn vPositionUVW;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn visibility;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn 1.0 - ChebychevInequality(moments, depth.z, bias);\r\n}\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n\tvec3 specular;\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., vSpecularColor.a));\r\n\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n\tresult.specular = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\tresult.specular = specComp * specularColor;\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z);\r\n#else\r\n\t#ifdef SHADOWPCF0\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z);\r\n#else\r\n\t#ifdef SHADOWPCF1\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z);\r\n#else\r\n\t#ifdef SHADOWPCF2\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z);\r\n#else\r\n\t#ifdef SHADOWPCF3\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\r\n\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTION\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef SPECULAR\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform float maxZ;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform float focus_depth;\r\nuniform float aperture;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI 3.14159265\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(vec2 coords, float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = min(3.0, ceil(size / 1.0));\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\r\n\tcol += texture2D(textureSampler, coords + vec2(-0.53*w, 0.15*h))*0.93;\r\n\tcol += texture2D(textureSampler, coords + vec2(0.42*w, -0.69*h))*0.90;\r\n\tcol += texture2D(textureSampler, coords + vec2(0.20*w, 1.00*h))*0.87;\r\n\tcol += texture2D(textureSampler, coords + vec2(-0.97*w, -0.72*h))*0.85;\r\n\tcol += texture2D(textureSampler, coords + vec2(1.37*w, -0.14*h))*0.83;\r\n\tcol += texture2D(textureSampler, coords + vec2(-1.02*w, 1.16*h))*0.80;\r\n\tcol += texture2D(textureSampler, coords + vec2(-0.03*w, -1.69*h))*0.78;\r\n\tcol += texture2D(textureSampler, coords + vec2(1.27*w, 1.34*h))*0.76;\r\n\tcol += texture2D(textureSampler, coords + vec2(-1.98*w, -0.14*h))*0.74;\r\n\tcol += texture2D(textureSampler, coords + vec2(1.66*w, -1.32*h))*0.72;\r\n\ttotal_weight += 8.18;\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-0.35*w, 2.22*h))*0.70;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-1.31*w, -1.98*h))*0.67;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.42*w, 0.61*h))*0.65;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-2.31*w, 1.25*h))*0.63;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(0.90*w, -2.59*h))*0.61;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(1.14*w, 2.62*h))*0.59;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-2.72*w, -1.21*h))*0.56;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.93*w, -0.98*h))*0.54;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-1.56*w, 2.80*h))*0.52;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-0.77*w, -3.22*h))*0.49;\r\n\t\ttotal_weight += 5.96;\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.83*w, 1.92*h))*0.46;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-3.49*w, 0.51*h))*0.44;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.30*w, -2.82*h))*0.41;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(0.22*w, 3.74*h))*0.38;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-2.76*w, -2.68*h))*0.34;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(3.95*w, 0.11*h))*0.31;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-3.07*w, 2.65*h))*0.26;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(0.48*w, -4.13*h))*0.22;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.49*w, 3.46*h))*0.15;\r\n\t\ttotal_weight += 2.97;\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\tcol.a = 1.0;\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b = 0.0; }\r\n\t// if(blur_level == 2.0) { col.r = 0.0; }\r\n\t// if(blur_level == 3.0) { col.g = 0.0; }\r\n\r\n\treturn col;\r\n}\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\r\n\tvec4 final_color;\r\n\tvec2 distorted_coords = getDistortedCoords(vUV);\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\t// blur from depth of field effect\r\n\tfloat dof_blur_amount = 0.0;\r\n\tfloat depth_bias = 0.0;\t\t// positive if the pixel is further than focus depth; negative if closer\r\n\tif (focus_depth != -1.0) {\r\n\t\tvec4 depth_sample = texture2D(depthSampler, distorted_coords);\r\n\t\tfloat depth = depth_sample.r;\r\n\t\tdepth_bias = depth - focus_depth;\r\n\r\n\t\t// compute blur amount with distance\r\n\t\tif (depth_bias > 0.0) { dof_blur_amount = depth_bias * aperture * 2.2; }\r\n\t\telse { dof_blur_amount = depth_bias * depth_bias * aperture * 30.0; }\r\n\r\n\t\tif (dof_blur_amount < 0.05) { dof_blur_amount = 0.0; }\t// no blur at all\r\n\t}\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, dof_blur_amount);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(distorted_coords, blur_amount * 1.7);\r\n\r\n\t\t// if further than focus depth & we have computed highlights: enhance highlights\r\n\t\tif (depth_bias > 0.0 && highlights) {\r\n\t\t\tgl_FragColor += clamp(dof_blur_amount, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords);\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.20;\r\n\t}\r\n}","displayPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","layerPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\nuniform vec4 vSpecularColor;\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\nuniform vec3 vLightSpecular0;\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\nuniform vec3 vLightSpecular1;\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\nuniform vec3 vLightSpecular2;\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\nuniform vec3 vLightSpecular3;\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\r\n\treturn dot(color, bitShift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv));\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn 0.;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat ChebychevInequality(vec2 moments, float t)\r\n{\r\n\tif (t <= moments.x)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat variance = moments.y - (moments.x * moments.x);\r\n\tvariance = max(variance, 0.);\r\n\r\n\tfloat d = t - moments.x;\r\n\treturn variance / (variance + d * d);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\tresult[1] = specComp * specularColor;\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\tresult[1] = specComp * specularColor;\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn position;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef SPECULAR\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform bool pentagon;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tif (pentagon) {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n\t}\r\n\telse {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n\t}\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","marblePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","oculusDistortionCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","particlesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#endif\r\n\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\r\n}\r\n","volumetricLightScatteringPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\t#ifndef BASIC_RENDER\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = diffuseColor;\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","woodPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  31491. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var i=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o}();o.CollisionCache=i;var e=function(){function i(i,e,r){this.collider=i,this._collisionCache=e,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return i.prototype.collideWithWorld=function(o,i,e,r){var t=.01;if(this.collider.retry>=e)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,i,t);var s=this._collisionCache.getMeshes();for(var l in s)if(s.hasOwnProperty(l)&&parseInt(l)!=r){var n=s[l];n.checkCollisions&&this.checkCollision(n)}return this.collider.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&this.collider._getResponse(o,i),i.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,i,e,r))):void o.addToRef(i,this.finalPosition)},i.prototype.checkCollision=function(i){if(this.collider._canDoCollision(o.Vector3.FromArray(i.sphereCenter),i.sphereRadius,o.Vector3.FromArray(i.boxMinimum),o.Vector3.FromArray(i.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var e=o.Matrix.FromArray(i.worldMatrixFromCache);e.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,i)}},i.prototype.processCollisionsForSubMeshes=function(o,i){var e,r;if(r=i.subMeshes,e=r.length,!i.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(i.geometryId);if(!t)return void console.log(\"couldn't find geometry\",i.geometryId);for(var s=0;e>s;s++){var l=r[s];e>1&&!this.checkSubmeshCollision(l)||this.collideForSubMesh(l,o,t)}},i.prototype.collideForSubMesh=function(i,e,r){for(var t=[],s=0;s<r.positions.length;s+=3){var l=o.Vector3.FromArray([r.positions[s],r.positions[s+1],r.positions[s+2]]);t.push(l)}i._lastColliderTransformMatrix=e.clone(),i._lastColliderWorldVertices=[],i._trianglePlanes=[];for(var n=i.verticesStart,a=i.verticesStart+i.verticesCount,s=n;a>s;s++)i._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(t[s],e));this.collider._collide(i._trianglePlanes=[],i._lastColliderWorldVertices,r.indices,i.indexStart,i.indexStart+i.indexCount,i.verticesStart,i.hasMaterial)},i.prototype.checkSubmeshCollision=function(i){return this.collider._canDoCollision(o.Vector3.FromArray(i.sphereCenter),i.sphereRadius,o.Vector3.FromArray(i.boxMinimum),o.Vector3.FromArray(i.boxMaximum))},i}();o.CollideWorker=e;var r=function(){function r(){}return r.prototype.onInit=function(o){this._collisionCache=new i;var e={error:0,taskType:0};postMessage(e,void 0)},r.prototype.onUpdate=function(o){for(var i in o.updatedGeometries)o.updatedGeometries.hasOwnProperty(i)&&this._collisionCache.addGeometry(o.updatedGeometries[i]);for(var e in o.updatedMeshes)o.updatedMeshes.hasOwnProperty(e)&&this._collisionCache.addMesh(o.updatedMeshes[e]);var r={error:0,taskType:1};postMessage(r,void 0)},r.prototype.onCollision=function(i){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(i.collider.radius);var s=new e(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(i.collider.position),o.Vector3.FromArray(i.collider.velocity),i.maximumRetry,i.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:i.collisionId,newPosition:r.asArray()},n={error:0,taskType:2,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(o){var i=o.data;switch(i.taskType){case 0:t.onInit(i.payload);break;case 2:t.onCollision(i.payload);break;case 1:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var o=(e.WorkerReplyType,function(){function o(){var i=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){i._addUpdateMeshesList[e.uniqueId]=o.SerializeMesh(e)},this.onGeometryUpdated=function(e){i._addUpdateGeometriesList[e.id]=o.SerializeGeometry(e)},this._afterRender=function(){if(i._init&&!(0==i._toRemoveGeometryArray.length&&0==i._toRemoveMeshesArray.length&&0==Object.keys(i._addUpdateGeometriesList).length&&0==Object.keys(i._addUpdateMeshesList).length||i._runningUpdated>4)){++i._runningUpdated;var e={updatedMeshes:i._addUpdateMeshesList,updatedGeometries:i._addUpdateGeometriesList,removedGeometries:i._toRemoveGeometryArray,removedMeshes:i._toRemoveMeshesArray},o={payload:e,taskType:1},t=[];for(var r in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(r)&&(t.push(o.payload.updatedGeometries[r].indices.buffer),t.push(o.payload.updatedGeometries[r].normals.buffer),t.push(o.payload.updatedGeometries[r].positions.buffer));i._worker.postMessage(o,t),i._addUpdateMeshesList={},i._addUpdateGeometriesList={},i._toRemoveGeometryArray=[],i._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(o){var t=o.data;if(0!=t.error)return void e.Tools.Warn(\"error returned from worker!\");switch(t.taskType){case 0:i._init=!0,i._scene.meshes.forEach(function(e){i.onMeshAdded(e)}),i._scene.getGeometries().forEach(function(e){i.onGeometryAdded(e)});break;case 1:i._runningUpdated--;break;case 2:i._runningCollisionTask=!1;var r=t.payload;if(!i._collisionsCallbackArray[r.collisionId])return;i._collisionsCallbackArray[r.collisionId](r.collisionId,e.Vector3.FromArray(r.newPosition),i._scene.getMeshByUniqueID(r.collidedMeshUniqueId)),i._collisionsCallbackArray[r.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){if(!this._init,!this._collisionsCallbackArray[n]){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),this._collisionsCallbackArray[n]=s;var a={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:i.radius.asArray()},collisionId:n,excludedMeshUniqueId:r?r.uniqueId:null,maximumRetry:t},d={payload:a,taskType:2};this._worker.postMessage(d)}},o.prototype.init=function(o){this._scene=o,this._scene.registerAfterRender(this._afterRender);var i=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(i),this._worker.onmessage=this._onMessageFromWorker;var t={payload:{},taskType:0};this._worker.postMessage(t)},o.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},o.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},o.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},o.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},o.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},o.SerializeMesh=function(e){var o=[];e.subMeshes&&(o=e.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var i=e.geometry?e.geometry.id:null;return{uniqueId:e.uniqueId,id:e.id,name:e.name,geometryId:i,sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:e.worldMatrixFromCache.asArray(),subMeshes:o,checkCollisions:e.checkCollisions}},o.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},o}());e.CollisionCoordinatorWorker=o;var i=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(null,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=i}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function t(t,i,o){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),this.r=t,this.g=i,this.b=o}return t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},t.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},t.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b)},t.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},t.prototype.clone=function(){return new t(this.r,this.g,this.b)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},t.prototype.copyFromFloats=function(t,i,o){return this.r=t,this.g=i,this.b=o,this},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1],i[o+2])},t.FromInts=function(i,o,n){return new t(i/255,o/255,n/255)},t.Lerp=function(i,o,n){var r=i.r+(o.r-i.r)*n,s=i.g+(o.g-i.g)*n,e=i.b+(o.b-i.b)*n;return new t(r,s,e)},t.Red=function(){return new t(1,0,0)},t.Green=function(){return new t(0,1,0)},t.Blue=function(){return new t(0,0,1)},t.Black=function(){return new t(0,0,0)},t.White=function(){return new t(1,1,1)},t.Purple=function(){return new t(.5,0,.5)},t.Magenta=function(){return new t(1,0,1)},t.Yellow=function(){return new t(1,1,0)},t.Gray=function(){return new t(.5,.5,.5)},t}();t.Color3=i;var o=function(){function t(t,i,o,n){this.r=t,this.g=i,this.b=o,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.Lerp=function(i,o,n){var r=new t(0,0,0,0);return t.LerpToRef(i,o,n,r),r},t.LerpToRef=function(t,i,o,n){n.r=t.r+(i.r-t.r)*o,n.g=t.g+(i.g-t.g)*o,n.b=t.b+(i.b-t.b)*o,n.a=t.a+(i.a-t.a)*o},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.FromInts=function(i,o,n,r){return new t(i/255,o/255,n/255,r/255)},t}();t.Color4=o;var n=function(){function t(t,i){this.x=t,this.y=i}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},t.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y)},t.prototype.addVector3=function(i){return new t(this.x+i.x,this.y+i.y)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y)},t.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},t.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},t.prototype.multiply=function(i){return new t(this.x*i.x,this.y*i.y)},t.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},t.prototype.multiplyByFloats=function(i,o){return new t(this.x*i,this.y*o)},t.prototype.divide=function(i){return new t(this.x/i.x,this.y/i.y)},t.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},t.prototype.negate=function(){return new t(-this.x,-this.y)},t.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},t.prototype.scale=function(i){return new t(this.x*i,this.y*i)},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},t.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},t.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},t.prototype.clone=function(){return new t(this.x,this.y)},t.Zero=function(){return new t(0,0)},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1])},t.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1]},t.CatmullRom=function(i,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-i.x+n.x)*s+(2*i.x-5*o.x+4*n.x-r.x)*e+(-i.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-i.y+n.y)*s+(2*i.y-5*o.y+4*n.y-r.y)*e+(-i.y+3*o.y-3*n.y+r.y)*a);return new t(h,u)},t.Clamp=function(i,o,n){var r=i.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=i.y;return s=s>n.y?n.y:s,s=s<o.y?o.y:s,new t(r,s)},t.Hermite=function(i,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,m=a-2*e+s,l=a-e,f=i.x*h+n.x*u+o.x*m+r.x*l,x=i.y*h+n.y*u+o.y*m+r.y*l;return new t(f,x)},t.Lerp=function(i,o,n){var r=i.x+(o.x-i.x)*n,s=i.y+(o.y-i.y)*n;return new t(r,s)},t.Dot=function(t,i){return t.x*i.x+t.y*i.y},t.Normalize=function(t){var i=t.clone();return i.normalize(),i},t.Minimize=function(i,o){var n=i.x<o.x?i.x:o.x,r=i.y<o.y?i.y:o.y;return new t(n,r)},t.Maximize=function(i,o){var n=i.x>o.x?i.x:o.x,r=i.y>o.y?i.y:o.y;return new t(n,r)},t.Transform=function(i,o){var n=i.x*o.m[0]+i.y*o.m[4],r=i.x*o.m[1]+i.y*o.m[5];return new t(n,r)},t.Distance=function(i,o){return Math.sqrt(t.DistanceSquared(i,o))},t.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y;return o*o+n*n},t}();t.Vector2=n;var r=function(){function i(t,i,o){this.x=t,this.y=i,this.z=o}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),o=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),r=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),a=Math.sin(.5*this.y);return t.x=n*a,t.y=-r*a,t.z=o*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,o,n){return new i(this.x-t,this.y-o,this.z-n)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-o,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i){return Math.abs(this.x-i.x)<t.Engine.Epsilon&&Math.abs(this.y-i.y)<t.Engine.Epsilon&&Math.abs(this.z-i.z)<t.Engine.Epsilon},i.prototype.equalsToFloats=function(t,i,o){return this.x===t&&this.y===i&&this.z===o},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,o,n){return new i(this.x*t,this.y*o,this.z*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,o){return this.x=t,this.y=i,this.z=o,this},i.GetClipFactor=function(t,o,n,r){var s=i.Dot(t,n)-r,e=i.Dot(o,n)-r,a=s/(s-e);return a},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatsToRef=function(t,i,o,n){n.x=t,n.y=i,n.z=o},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,o){var n=i.Zero();return i.TransformCoordinatesToRef(t,o,n),n},i.TransformCoordinatesToRef=function(t,i,o){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],r=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];o.x=n/e,o.y=r/e,o.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,o,n,r){var s=t*n.m[0]+i*n.m[4]+o*n.m[8]+n.m[12],e=t*n.m[1]+i*n.m[5]+o*n.m[9]+n.m[13],a=t*n.m[2]+i*n.m[6]+o*n.m[10]+n.m[14],h=t*n.m[3]+i*n.m[7]+o*n.m[11]+n.m[15];r.x=s/h,r.y=e/h,r.z=a/h},i.TransformCoordinatesToRefSIMD=function(t,i,o){var n=SIMD.float32x4.loadXYZ(t._data,0),r=SIMD.float32x4.load(i.m,0),s=SIMD.float32x4.load(i.m,4),e=SIMD.float32x4.load(i.m,8),a=SIMD.float32x4.load(i.m,12),h=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,0,0,0,0),r),SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,1,1,1,1),s)),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,2,2,2,2),e),a));h=SIMD.float32x4.div(h,SIMD.float32x4.swizzle(h,3,3,3,3)),SIMD.float32x4.storeXYZ(o._data,0,h)},i.TransformCoordinatesFromFloatsToRefSIMD=function(t,i,o,n,r){var s=SIMD.float32x4.splat(t),e=SIMD.float32x4.splat(i),a=SIMD.float32x4.splat(o),h=SIMD.float32x4.load(n.m,0),u=SIMD.float32x4.load(n.m,4),m=SIMD.float32x4.load(n.m,8),l=SIMD.float32x4.load(n.m,12),f=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(s,h),SIMD.float32x4.mul(e,u)),SIMD.float32x4.add(SIMD.float32x4.mul(a,m),l));f=SIMD.float32x4.div(f,SIMD.float32x4.swizzle(f,3,3,3,3)),SIMD.float32x4.storeXYZ(r._data,0,f)},i.TransformNormal=function(t,o){var n=i.Zero();return i.TransformNormalToRef(t,o,n),n},i.TransformNormalToRef=function(t,i,o){o.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],o.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,o,n,r){r.x=t*n.m[0]+i*n.m[4]+o*n.m[8],r.y=t*n.m[1]+i*n.m[5]+o*n.m[9],r.z=t*n.m[2]+i*n.m[6]+o*n.m[10]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a),m=.5*(2*o.z+(-t.z+n.z)*s+(2*t.z-5*o.z+4*n.z-r.z)*e+(-t.z+3*o.z-3*n.z+r.z)*a);return new i(h,u,m)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;s=s>n.y?n.y:s,s=s<o.y?o.y:s;var e=t.z;return e=e>n.z?n.z:e,e=e<o.z?o.z:e,new i(r,s,e)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,m=a-2*e+s,l=a-e,f=t.x*h+n.x*u+o.x*m+r.x*l,x=t.y*h+n.y*u+o.y*m+r.y*l,y=t.z*h+n.z*u+o.z*m+r.z*l;return new i(f,x,y)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n,e=t.z+(o.z-t.z)*n;return new i(r,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,o){var n=i.Zero();return i.CrossToRef(t,o,n),n},i.CrossToRef=function(t,i,o){o.x=t.y*i.z-t.z*i.y,o.y=t.z*i.x-t.x*i.z,o.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,o,n,r){var s=r.width,e=r.height,h=r.x,u=r.y,m=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),l=o.multiply(n).multiply(m);return i.TransformCoordinates(t,l)},i.UnprojectFromTransform=function(o,n,r,s,e){var a=s.multiply(e);a.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var h=i.TransformCoordinates(o,a),u=o.x*a.m[3]+o.y*a.m[7]+o.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(u,1)&&(h=h.scale(1/u)),h},i.Unproject=function(o,n,r,s,e,a){var h=s.multiply(e).multiply(a);h.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var u=i.TransformCoordinates(o,h),m=o.x*h.m[3]+o.y*h.m[7]+o.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(m,1)&&(u=u.scale(1/m)),u},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z;return o*o+n*n+r*r},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i}();t.Vector3=r;var s=function(){function i(t,i,o,n){this.x=t,this.y=i,this.z=o,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,o,n,r){return new i(this.x-t,this.y-o,this.z-n,this.w-r)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-o,r.w=this.w-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i){return Math.abs(this.x-i.x)<t.Engine.Epsilon&&Math.abs(this.y-i.y)<t.Engine.Epsilon&&Math.abs(this.z-i.z)<t.Engine.Epsilon&&Math.abs(this.w-i.w)<t.Engine.Epsilon},i.prototype.equalsToFloats=function(t,i,o,n){return this.x===t&&this.y===i&&this.z===o&&this.w===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,o,n,r){return new i(this.x*t,this.y*o,this.z*n,this.w*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatsToRef=function(t,i,o,n,r){r.x=t,r.y=i,r.z=o,r.w=n},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z,s=t.w-i.w;return o*o+n*n+r*r+s*s},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i}();t.Vector4=s;var e=function(){function t(t,i,o,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=o,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var o=new t(0,0,0,1);return this.multiplyToRef(i,o),o},t.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,i.y=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,i.z=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,i.w=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w,this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=r.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,o=this.y,n=this.z,r=this.w,s=i*o,e=i*n,a=r*o,h=r*n,u=r*i,m=o*n,l=i*i,f=o*o,x=l+f;return 0!==x&&1!==x?(t.x=Math.atan2(e+a,u-m),t.y=Math.acos(1-2*x),t.z=Math.atan2(e-a,u+m)):0===x?(t.x=0,t.y=0,t.z=Math.atan2(s-h,.5-f-n*n)):(t.x=Math.atan2(s-h,.5-f-n*n),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,o=this.y*this.y,n=this.z*this.z,r=this.x*this.y,s=this.z*this.w,e=this.z*this.x,a=this.y*this.w,h=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(o+n),t.m[1]=2*(r+s),t.m[2]=2*(e-a),t.m[3]=0,t.m[4]=2*(r-s),t.m[5]=1-2*(n+i),t.m[6]=2*(h+u),t.m[7]=0,t.m[8]=2*(e+a),t.m[9]=2*(h-u),t.m[10]=1-2*(o+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var o=new t;return t.FromRotationMatrixToRef(i,o),o},t.FromRotationMatrixToRef=function(t,i){var o,n=t.m,r=n[0],s=n[4],e=n[8],a=n[1],h=n[5],u=n[9],m=n[2],l=n[6],f=n[10],x=r+h+f;x>0?(o=.5/Math.sqrt(x+1),i.w=.25/o,i.x=(l-u)*o,i.y=(e-m)*o,i.z=(a-s)*o):r>h&&r>f?(o=2*Math.sqrt(1+r-h-f),i.w=(l-u)/o,i.x=.25*o,i.y=(s+a)/o,i.z=(e+m)/o):h>f?(o=2*Math.sqrt(1+h-r-f),i.w=(e-m)/o,i.x=(s+a)/o,i.y=.25*o,i.z=(u+l)/o):(o=2*Math.sqrt(1+f-r-h),i.w=(a-s)/o,i.x=(e+m)/o,i.y=(u+l)/o,i.z=.25*o)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,o){var n=new t,r=Math.sin(o/2);return n.w=Math.cos(o/2),n.x=i.x*r,n.y=i.y*r,n.z=i.z*r,n},t.FromArray=function(i,o){return o||(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.RotationYawPitchRoll=function(i,o,n){var r=new t;return t.RotationYawPitchRollToRef(i,o,n,r),r},t.RotationYawPitchRollToRef=function(t,i,o,n){var r=.5*o,s=.5*i,e=.5*t,a=Math.sin(r),h=Math.cos(r),u=Math.sin(s),m=Math.cos(s),l=Math.sin(e),f=Math.cos(e);n.x=f*u*h+l*m*a,n.y=l*m*h-f*u*a,n.z=f*m*a-l*u*h,n.w=f*m*h+l*u*a},t.RotationAlphaBetaGamma=function(i,o,n){var r=new t;return t.RotationAlphaBetaGammaToRef(i,o,n,r),r},t.RotationAlphaBetaGammaToRef=function(t,i,o,n){var r=.5*(o+t),s=.5*(o-t),e=.5*i;n.x=Math.cos(s)*Math.sin(e),n.y=Math.sin(s)*Math.sin(e),n.z=Math.sin(r)*Math.cos(e),n.w=Math.cos(r)*Math.cos(e)},t.Slerp=function(i,o,n){var r,s,e=n,a=i.x*o.x+i.y*o.y+i.z*o.z+i.w*o.w,h=!1;if(0>a&&(h=!0,a=-a),a>.999999)s=1-e,r=h?-e:e;else{var u=Math.acos(a),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,r=h?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+r*o.x,s*i.y+r*o.y,s*i.z+r*o.z,s*i.w+r*o.w)},t}();t.Quaternion=e;var a=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],o=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],r=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*o)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*r)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*s)-this.m[3]*(this.m[4]*o-this.m[5]*r+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.invertToRef=function(t){var i=this.m[0],o=this.m[1],n=this.m[2],r=this.m[3],s=this.m[4],e=this.m[5],a=this.m[6],h=this.m[7],u=this.m[8],m=this.m[9],l=this.m[10],f=this.m[11],x=this.m[12],y=this.m[13],c=this.m[14],p=this.m[15],z=l*p-f*c,M=m*p-f*y,w=m*c-l*y,d=u*p-f*x,I=u*c-l*x,D=u*y-m*x,S=e*z-a*M+h*w,v=-(s*z-a*d+h*I),g=s*M-e*d+h*D,T=-(s*w-e*I+a*D),R=1/(i*S+o*v+n*g+r*T),_=a*p-h*c,b=e*p-h*y,A=e*c-a*y,F=s*p-h*x,P=s*c-a*x,C=s*y-e*x,L=a*f-h*l,q=e*f-h*m,E=e*l-a*m,Z=s*f-h*u,V=s*l-a*u,N=s*m-e*u;return t.m[0]=S*R,t.m[4]=v*R,t.m[8]=g*R,t.m[12]=T*R,t.m[1]=-(o*z-n*M+r*w)*R,t.m[5]=(i*z-n*d+r*I)*R,t.m[9]=-(i*M-o*d+r*D)*R,t.m[13]=(i*w-o*I+n*D)*R,t.m[2]=(o*_-n*b+r*A)*R,t.m[6]=-(i*_-n*F+r*P)*R,t.m[10]=(i*b-o*F+r*C)*R,t.m[14]=-(i*A-o*P+n*C)*R,t.m[3]=-(o*L-n*q+r*E)*R,t.m[7]=(i*L-n*Z+r*V)*R,t.m[11]=-(i*q-o*Z+r*N)*R,t.m[15]=(i*E-o*V+n*N)*R,this},i.prototype.invertToRefSIMD=function(t){var i,o,n,r,s,e,a,h,u,m,l=this.m,f=t.m,x=SIMD.float32x4.load(l,0),y=SIMD.float32x4.load(l,4),c=SIMD.float32x4.load(l,8),p=SIMD.float32x4.load(l,12);return s=SIMD.float32x4.shuffle(x,y,0,1,4,5),o=SIMD.float32x4.shuffle(c,p,0,1,4,5),i=SIMD.float32x4.shuffle(s,o,0,2,4,6),o=SIMD.float32x4.shuffle(o,s,1,3,5,7),s=SIMD.float32x4.shuffle(x,y,2,3,6,7),r=SIMD.float32x4.shuffle(c,p,2,3,6,7),n=SIMD.float32x4.shuffle(s,r,0,2,4,6),r=SIMD.float32x4.shuffle(r,s,1,3,5,7),s=SIMD.float32x4.mul(n,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.mul(o,s),a=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(SIMD.float32x4.mul(o,s),e),a=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),a),a=SIMD.float32x4.swizzle(a,2,3,0,1),s=SIMD.float32x4.mul(o,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),e),u=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),u),u=SIMD.float32x4.swizzle(u,2,3,0,1),s=SIMD.float32x4.mul(SIMD.float32x4.swizzle(o,2,3,0,1),r),s=SIMD.float32x4.swizzle(s,1,0,3,2),n=SIMD.float32x4.swizzle(n,2,3,0,1),e=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),e),h=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),h),h=SIMD.float32x4.swizzle(h,2,3,0,1),s=SIMD.float32x4.mul(i,o),s=SIMD.float32x4.swizzle(s,1,0,3,2),h=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(SIMD.float32x4.mul(n,s),u),s=SIMD.float32x4.swizzle(s,2,3,0,1),h=SIMD.float32x4.sub(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(n,s)),s=SIMD.float32x4.mul(i,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),h),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),a),h=SIMD.float32x4.sub(h,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.mul(i,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),a),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),u),m=SIMD.float32x4.mul(i,e),m=SIMD.float32x4.add(SIMD.float32x4.swizzle(m,2,3,0,1),m),m=SIMD.float32x4.add(SIMD.float32x4.swizzle(m,1,0,3,2),m),s=SIMD.float32x4.reciprocalApproximation(m),m=SIMD.float32x4.sub(SIMD.float32x4.add(s,s),SIMD.float32x4.mul(m,SIMD.float32x4.mul(s,s))),m=SIMD.float32x4.swizzle(m,0,0,0,0),e=SIMD.float32x4.mul(m,e),a=SIMD.float32x4.mul(m,a),h=SIMD.float32x4.mul(m,h),u=SIMD.float32x4.mul(m,u),SIMD.float32x4.store(f,0,e),SIMD.float32x4.store(f,4,a),SIMD.float32x4.store(f,8,h),SIMD.float32x4.store(f,12,u),this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var o=new i;return this.multiplyToRef(t,o),o},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var o=0;16>o;o++)t[i+o]=this.m[o];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,o){var n=this.m[0],r=this.m[1],s=this.m[2],e=this.m[3],a=this.m[4],h=this.m[5],u=this.m[6],m=this.m[7],l=this.m[8],f=this.m[9],x=this.m[10],y=this.m[11],c=this.m[12],p=this.m[13],z=this.m[14],M=this.m[15],w=t.m[0],d=t.m[1],I=t.m[2],D=t.m[3],S=t.m[4],v=t.m[5],g=t.m[6],T=t.m[7],R=t.m[8],_=t.m[9],b=t.m[10],A=t.m[11],F=t.m[12],P=t.m[13],C=t.m[14],L=t.m[15];return i[o]=n*w+r*S+s*R+e*F,i[o+1]=n*d+r*v+s*_+e*P,i[o+2]=n*I+r*g+s*b+e*C,i[o+3]=n*D+r*T+s*A+e*L,i[o+4]=a*w+h*S+u*R+m*F,i[o+5]=a*d+h*v+u*_+m*P,i[o+6]=a*I+h*g+u*b+m*C,i[o+7]=a*D+h*T+u*A+m*L,i[o+8]=l*w+f*S+x*R+y*F,i[o+9]=l*d+f*v+x*_+y*P,i[o+10]=l*I+f*g+x*b+y*C,i[o+11]=l*D+f*T+x*A+y*L,i[o+12]=c*w+p*S+z*R+M*F,i[o+13]=c*d+p*v+z*_+M*P,i[o+14]=c*I+p*g+z*b+M*C,i[o+15]=c*D+p*T+z*A+M*L,this},i.prototype.multiplyToArraySIMD=function(t,i,o){void 0===o&&(o=0);var n=this.m,r=t.m,s=SIMD.float32x4.load(r,0),e=SIMD.float32x4.load(r,4),a=SIMD.float32x4.load(r,8),h=SIMD.float32x4.load(r,12),u=SIMD.float32x4.load(n,0);SIMD.float32x4.store(i,o+0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,3,3,3,3),h)))));var m=SIMD.float32x4.load(n,4);SIMD.float32x4.store(i,o+4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,3,3,3,3),h)))));var l=SIMD.float32x4.load(n,8);SIMD.float32x4.store(i,o+8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,3,3,3,3),h)))));var f=SIMD.float32x4.load(n,12);SIMD.float32x4.store(i,o+12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,3,3,3,3),h)))))},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.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])},i.prototype.decompose=function(o,n,r){r.x=this.m[12],r.y=this.m[13],r.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,a=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(o.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),o.y=a*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),o.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===o.x||0===o.y||0===o.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=i.FromValues(this.m[0]/o.x,this.m[1]/o.x,this.m[2]/o.x,0,this.m[4]/o.y,this.m[5]/o.y,this.m[6]/o.y,0,this.m[8]/o.z,this.m[9]/o.z,this.m[10]/o.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,n),!0},i.FromArray=function(t,o){var n=new i;return o||(o=0),i.FromArrayToRef(t,o,n),n},i.FromArrayToRef=function(t,i,o){for(var n=0;16>n;n++)o.m[n]=t[n+i]},i.FromValuesToRef=function(t,i,o,n,r,s,e,a,h,u,m,l,f,x,y,c,p){\np.m[0]=t,p.m[1]=i,p.m[2]=o,p.m[3]=n,p.m[4]=r,p.m[5]=s,p.m[6]=e,p.m[7]=a,p.m[8]=h,p.m[9]=u,p.m[10]=m,p.m[11]=l,p.m[12]=f,p.m[13]=x,p.m[14]=y,p.m[15]=c},i.FromValues=function(t,o,n,r,s,e,a,h,u,m,l,f,x,y,c,p){var z=new i;return z.m[0]=t,z.m[1]=o,z.m[2]=n,z.m[3]=r,z.m[4]=s,z.m[5]=e,z.m[6]=a,z.m[7]=h,z.m[8]=u,z.m[9]=m,z.m[10]=l,z.m[11]=f,z.m[12]=x,z.m[13]=y,z.m[14]=c,z.m[15]=p,z},i.Compose=function(t,o,n){var r=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return o.toRotationMatrix(s),r=r.multiply(s),r.setTranslation(n),r},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var o=new i;return i.RotationXToRef(t,o),o},i.Invert=function(t){var o=new i;return t.invertToRef(o),o},i.RotationXToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-o,i.m[6]=o,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var o=new i;return i.RotationYToRef(t,o),o},i.RotationYToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-o,i.m[8]=o,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var o=new i;return i.RotationZToRef(t,o),o},i.RotationZToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=o,i.m[4]=-o,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,o){var n=Math.sin(-o),r=Math.cos(-o),s=1-r;t.normalize();var e=i.Zero();return e.m[0]=t.x*t.x*s+r,e.m[1]=t.x*t.y*s-t.z*n,e.m[2]=t.x*t.z*s+t.y*n,e.m[3]=0,e.m[4]=t.y*t.x*s+t.z*n,e.m[5]=t.y*t.y*s+r,e.m[6]=t.y*t.z*s-t.x*n,e.m[7]=0,e.m[8]=t.z*t.x*s-t.y*n,e.m[9]=t.z*t.y*s+t.x*n,e.m[10]=t.z*t.z*s+r,e.m[11]=0,e.m[15]=1,e},i.RotationYawPitchRoll=function(t,o,n){var r=new i;return i.RotationYawPitchRollToRef(t,o,n,r),r},i.RotationYawPitchRollToRef=function(t,i,o,n){e.RotationYawPitchRollToRef(t,i,o,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},i.Scaling=function(t,o,n){var r=i.Zero();return i.ScalingToRef(t,o,n,r),r},i.ScalingToRef=function(t,i,o,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=o,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},i.Translation=function(t,o,n){var r=i.Identity();return i.TranslationToRef(t,o,n,r),r},i.TranslationToRef=function(t,o,n,r){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,o,n,1,r)},i.LookAtLH=function(t,o,n){var r=i.Zero();return i.LookAtLHToRef(t,o,n,r),r},i.LookAtLHToRef=function(t,o,n,s){o.subtractToRef(t,this._zAxis),this._zAxis.normalize(),r.CrossToRef(n,this._zAxis,this._xAxis),this._xAxis.normalize(),r.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-r.Dot(this._xAxis,t),a=-r.Dot(this._yAxis,t),h=-r.Dot(this._zAxis,t);return i.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,e,a,h,1,s)},i.LookAtLHToRefSIMD=function(t,i,o,n){var r=n.m,s=SIMD.float32x4(i.x,i.y,i.z,0),e=SIMD.float32x4(t.x,t.y,t.z,0),a=SIMD.float32x4(o.x,o.y,o.z,0),h=SIMD.float32x4.sub(s,e),u=SIMD.float32x4.mul(h,h);u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),h=SIMD.float32x4.mul(h,SIMD.float32x4.reciprocalSqrtApproximation(u)),u=SIMD.float32x4.mul(a,a),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),a=SIMD.float32x4.mul(a,SIMD.float32x4.reciprocalSqrtApproximation(u));var m=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,1,2,0,3),SIMD.float32x4.swizzle(a,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,2,0,1,3),SIMD.float32x4.swizzle(a,1,2,0,3)));u=SIMD.float32x4.mul(m,m),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),m=SIMD.float32x4.mul(m,SIMD.float32x4.reciprocalSqrtApproximation(u));var l=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,1,2,0,3),SIMD.float32x4.swizzle(h,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,2,0,1,3),SIMD.float32x4.swizzle(h,1,2,0,3)));u=SIMD.float32x4.mul(m,m),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),m=SIMD.float32x4.mul(m,SIMD.float32x4.reciprocalSqrtApproximation(u));var f=SIMD.float32x4.splat(0);m=SIMD.float32x4.neg(m);var x=SIMD.float32x4.shuffle(m,l,0,1,4,5),y=SIMD.float32x4.shuffle(h,f,0,1,4,5),c=SIMD.float32x4.shuffle(x,y,0,2,4,6),p=SIMD.float32x4.shuffle(x,y,1,3,5,7);x=SIMD.float32x4.shuffle(m,l,2,3,6,7),y=SIMD.float32x4.shuffle(h,f,2,3,6,7);var z=SIMD.float32x4.shuffle(x,y,0,2,4,6),M=SIMD.float32x4(0,0,0,1),w=SIMD.float32x4(1,0,0,0),d=SIMD.float32x4(0,1,0,0),I=SIMD.float32x4(0,0,1,0),D=SIMD.float32x4.neg(e);D=SIMD.float32x4.withW(D,1),SIMD.float32x4.store(r,0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,3,3,3,3),M))))),SIMD.float32x4.store(r,4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,3,3,3,3),M))))),SIMD.float32x4.store(r,8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,3,3,3,3),M))))),SIMD.float32x4.store(r,12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,3,3,3,3),M)))))},i.OrthoLH=function(t,o,n,r){var s=i.Zero();return i.OrthoLHToRef(t,o,n,r,s),s},i.OrthoLHToRef=function(t,o,n,r,s){var e=2/t,a=2/o,h=1/(r-n),u=n/(n-r);i.FromValuesToRef(e,0,0,0,0,a,0,0,0,0,h,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,o,n,r,s,e){var a=i.Zero();return i.OrthoOffCenterLHToRef(t,o,n,r,s,e,a),a},i.OrthoOffCenterLHToRef=function(t,i,o,n,r,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(n-o),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(r-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(n+o)/(o-n),e.m[14]=r/(r-s),e.m[15]=1},i.PerspectiveLH=function(t,o,n,r){var s=i.Zero();return s.m[0]=2*n/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*n/o,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-r/(n-r),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r),s},i.PerspectiveFovLH=function(t,o,n,r){var s=i.Zero();return i.PerspectiveFovLHToRef(t,o,n,r,s),s},i.PerspectiveFovLHToRef=function(i,o,n,r,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var a=1/Math.tan(.5*i),h=e===t.Camera.FOVMODE_VERTICAL_FIXED;s.m[0]=h?a/o:a,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=h?a:a*o,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-r/(n-r),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r)},i.GetFinalMatrix=function(t,o,n,r,s,e){var a=t.width,h=t.height,u=t.x,m=t.y,l=i.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,e-s,0,u+a/2,h/2+m,s,1);return o.multiply(n).multiply(r).multiply(l)},i.Transpose=function(t){var o=new i;return o.m[0]=t.m[0],o.m[1]=t.m[4],o.m[2]=t.m[8],o.m[3]=t.m[12],o.m[4]=t.m[1],o.m[5]=t.m[5],o.m[6]=t.m[9],o.m[7]=t.m[13],o.m[8]=t.m[2],o.m[9]=t.m[6],o.m[10]=t.m[10],o.m[11]=t.m[14],o.m[12]=t.m[3],o.m[13]=t.m[7],o.m[14]=t.m[11],o.m[15]=t.m[15],o},i.Reflection=function(t){var o=new i;return i.ReflectionToRef(t,o),o},i.ReflectionToRef=function(t,i){t.normalize();var o=t.normal.x,n=t.normal.y,r=t.normal.z,s=-2*o,e=-2*n,a=-2*r;i.m[0]=s*o+1,i.m[1]=e*o,i.m[2]=a*o,i.m[3]=0,i.m[4]=s*n,i.m[5]=e*n+1,i.m[6]=a*n,i.m[7]=0,i.m[8]=s*r,i.m[9]=e*r,i.m[10]=a*r+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=a*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=r.Zero(),i._yAxis=r.Zero(),i._zAxis=r.Zero(),i}();t.Matrix=a;var h=function(){function t(t,i,o,n){this.normal=new r(t,i,o),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var o=a.Transpose(i),n=this.normal.x,r=this.normal.y,s=this.normal.z,e=this.d,h=n*o.m[0]+r*o.m[1]+s*o.m[2]+e*o.m[3],u=n*o.m[4]+r*o.m[5]+s*o.m[6]+e*o.m[7],m=n*o.m[8]+r*o.m[9]+s*o.m[10]+e*o.m[11],l=n*o.m[12]+r*o.m[13]+s*o.m[14]+e*o.m[15];return new t(h,u,m,l)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,o){var n,r=i.x-t.x,s=i.y-t.y,e=i.z-t.z,a=o.x-t.x,h=o.y-t.y,u=o.z-t.z,m=s*u-e*h,l=e*a-r*u,f=r*h-s*a,x=Math.sqrt(m*m+l*l+f*f);return n=0!==x?1/x:0,this.normal.x=m*n,this.normal.y=l*n,this.normal.z=f*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var o=r.Dot(this.normal,t);return i>=o},t.prototype.signedDistanceTo=function(t){return r.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,o,n){var r=new t(0,0,0,0);return r.copyFromPoints(i,o,n),r},t.FromPositionAndNormal=function(i,o){var n=new t(0,0,0,0);return o.normalize(),n.normal=o,n.d=-(o.x*i.x+o.y*i.y+o.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,o){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return r.Dot(o,i)+n},t}();t.Plane=h;var u=function(){function t(t,i,o,n){this.x=t,this.y=i,this.width=o,this.height=n}return t.prototype.toGlobal=function(i){var o=i.getRenderWidth(),n=i.getRenderHeight();return new t(this.x*o,this.y*n,this.width*o,this.height*n)},t}();t.Viewport=u;var m=function(){function t(){}return t.GetPlanes=function(i){for(var o=[],n=0;6>n;n++)o.push(new h(0,0,0,0));return t.GetPlanesToRef(i,o),o},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[10]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=m;var l=function(){function i(t,i,o){void 0===o&&(o=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=o}return i.prototype.intersectsBoxMinMax=function(t,i){var o=0,n=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else{var r=1/this.direction.x,s=(t.x-this.origin.x)*r,e=(i.x-this.origin.x)*r;if(e===-(1/0)&&(e=1/0),s>e){var a=s;s=e,e=a}if(o=Math.max(s,o),n=Math.min(e,n),o>n)return!1}if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(r=1/this.direction.y,s=(t.y-this.origin.y)*r,e=(i.y-this.origin.y)*r,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),o=Math.max(s,o),n=Math.min(e,n),o>n)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(r=1/this.direction.z,s=(t.z-this.origin.z)*r,e=(i.z-this.origin.z)*r,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),o=Math.max(s,o),n=Math.min(e,n),o>n)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,o=t.center.y-this.origin.y,n=t.center.z-this.origin.z,r=i*i+o*o+n*n,s=t.radius*t.radius;if(s>=r)return!0;var e=i*this.direction.x+o*this.direction.y+n*this.direction.z;if(0>e)return!1;var a=r-e*e;return s>=a},i.prototype.intersectsTriangle=function(i,o,n){this._edge1||(this._edge1=r.Zero(),this._edge2=r.Zero(),this._pvec=r.Zero(),this._tvec=r.Zero(),this._qvec=r.Zero()),o.subtractToRef(i,this._edge1),n.subtractToRef(i,this._edge2),r.CrossToRef(this.direction,this._edge2,this._pvec);var s=r.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var a=r.Dot(this._tvec,this._pvec)*e;if(0>a||a>1)return null;r.CrossToRef(this._tvec,this._edge1,this._qvec);var h=r.Dot(this.direction,this._qvec)*e;if(0>h||a+h>1)return null;var u=r.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(a,h,u)},i.CreateNew=function(t,o,n,s,e,a,h){var u=r.Unproject(new r(t,o,0),n,s,e,a,h),m=r.Unproject(new r(t,o,1),n,s,e,a,h),l=m.subtract(u);return l.normalize(),new i(u,l)},i.CreateNewFromTo=function(t,o,n){void 0===n&&(n=a.Identity());var r=o.subtract(t),s=Math.sqrt(r.x*r.x+r.y*r.y+r.z*r.z);return r.normalize(),i.Transform(new i(t,r,s),n)},i.Transform=function(t,o){var n=r.TransformCoordinates(t.origin,o),s=r.TransformNormal(t.direction,o);return new i(n,s,t.length)},i}();t.Ray=l,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new r(1,0,0),t.Y=new r(0,1,0),t.Z=new r(0,0,1),t}());t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,o,n,r){for(var s=1-3*n+3*i,e=3*n-6*i,a=3*i,h=t,u=0;5>u;u++){var m=h*h,l=m*h,f=s*l+e*m+a*h,x=1/(3*s*m+2*e*h+a);h-=(f-t)*x,h=Math.min(1,Math.max(0,h))}return 3*Math.pow(1-h,2)*h*o+3*(1-h)*Math.pow(h,2)*r+Math.pow(h,3)},t}();t.BezierCurve=x,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var y=(t.Orientation,function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,o){var n=o.subtract(i),r=Math.atan2(n.y,n.x);return new t(r)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}());t.Angle=y;var c=function(){function t(t,i,o){this.startPoint=t,this.midPoint=i,this.endPoint=o;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(o.x,2)-Math.pow(o.y,2))/2,a=(t.x-i.x)*(i.y-o.y)-(i.x-o.x)*(t.y-i.y);this.centerPoint=new n((s*(i.y-o.y)-e*(t.y-i.y))/a,((t.x-i.x)*e-(i.x-o.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=y.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),u=y.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=y.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-h>180&&(u-=360),-180>u-h&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-h?0:1,this.angle=y.FromDegrees(0===this.orientation?h-m:m-h)}return t}();t.Arc2=c;var p=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new r(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=p;var z=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n(t,i))}return i.prototype.addLineTo=function(i,o){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new n(i,o),s=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(s).length(),this},i.prototype.addArcTo=function(i,o,r,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var a=this._points[this._points.length-1],h=new n(i,o),u=new n(r,s),m=new c(a,h,u),l=m.angle.radians()/e;0===m.orientation&&(l*=-1);for(var f=m.startAngle.radians()+l,x=0;e>x;x++){var y=Math.cos(f)*m.radius+m.centerPoint.x,p=Math.sin(f)*m.radius+m.centerPoint.y;this.addLineTo(y,p),f+=l}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],o=this._points[0];t+=o.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),n.Zero();for(var o=i*this.length(),r=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,a=this._points[s],h=this._points[e],u=h.subtract(a),m=u.length()+r;if(o>=r&&m>=o){var l=u.normalize(),f=o-r;return new n(a.x+l.x*f,a.y+l.y*f)}r=m}return t.Tools.Error(\"internal error\"),n.Zero()},i.StartingAt=function(t,o){return new i(t,o)},i}();t.Path2=z;var M=function(){function t(t,i){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var o=0;o<t.length;o++)this._curve[o]=t[o].clone();this._compute(i)}return t.prototype.getCurve=function(){return this._curve},t.prototype.getTangents=function(){return this._tangents},t.prototype.getNormals=function(){return this._normals},t.prototype.getBinormals=function(){return this._binormals},t.prototype.getDistances=function(){return this._distances},t.prototype.update=function(t,i){for(var o=0;o<t.length;o++)this._curve[o].x=t[o].x,this._curve[o].y=t[o].y,this._curve[o].z=t[o].z;return this._compute(i),this},t.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._tangents[i-1].normalize();var o=this._tangents[0],n=this._normalVector(this._curve[0],o,t);this._normals[0]=n,this._normals[0].normalize(),this._binormals[0]=r.Cross(o,this._normals[0]),this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,a,h,u,m=1;i>m;m++)s=this._getLastNonNullVector(m),i-1>m&&(e=this._getFirstNonNullVector(m),this._tangents[m]=s.add(e),this._tangents[m].normalize()),this._distances[m]=this._distances[m-1]+s.length(),a=this._tangents[m],h=this._normals[m-1],u=this._binormals[m-1],this._normals[m]=r.Cross(u,a),this._normals[m].normalize(),this._binormals[m]=r.Cross(a,this._normals[m]),this._binormals[m].normalize()},t.prototype._getFirstNonNullVector=function(t){for(var i=1,o=this._curve[t+i].subtract(this._curve[t]);0==o.length()&&t+i+1<this._curve.length;)i++,o=this._curve[t+i].subtract(this._curve[t]);return o},t.prototype._getLastNonNullVector=function(t){for(var i=1,o=this._curve[t].subtract(this._curve[t-i]);0==o.length()&&t>i+1;)i++,o=this._curve[t].subtract(this._curve[t-i]);return o},t.prototype._normalVector=function(t,i,o){var n;if(void 0===o||null===o){var s;1!==i.x?s=new r(1,0,0):1!==i.y?s=new r(0,1,0):1!==i.z&&(s=new r(0,0,1)),n=r.Cross(i,s)}else n=r.Cross(i,o),r.CrossToRef(n,i,n);return n.normalize(),n},t}();t.Path3D=M;var w=function(){function i(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return i.CreateQuadraticBezier=function(t,o,n,s){s=s>2?s:3;for(var e=new Array,a=function(t,i,o,n){var r=(1-t)*(1-t)*i+2*t*(1-t)*o+t*t*n;return r},h=0;s>=h;h++)e.push(new r(a(h/s,t.x,o.x,n.x),a(h/s,t.y,o.y,n.y),a(h/s,t.z,o.z,n.z)));return new i(e)},i.CreateCubicBezier=function(t,o,n,s,e){e=e>3?e:4;for(var a=new Array,h=function(t,i,o,n,r){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*o+3*t*t*(1-t)*n+t*t*t*r;return s},u=0;e>=u;u++)a.push(new r(h(u/e,t.x,o.x,n.x,s.x),h(u/e,t.y,o.y,n.y,s.y),h(u/e,t.z,o.z,n.z,s.z)));return new i(a)},i.CreateHermiteSpline=function(o,n,r,s,e){for(var a=new Array,h=1/e,u=0;e>=u;u++)a.push(t.Vector3.Hermite(o,n,r,s,u*h));return new i(a)},i.prototype.getPoints=function(){return this._points},i.prototype.length=function(){return this._length},i.prototype[\"continue\"]=function(t){for(var o=this._points[this._points.length-1],n=this._points.slice(),r=t.getPoints(),s=1;s<r.length;s++)n.push(r[s].subtract(r[0]).add(o));var e=new i(n);return e},i.prototype._computeLength=function(t){for(var i=0,o=1;o<t.length;o++)i+=t[o].subtract(t[o-1]).length();return i},i}();t.Curve3=w;var d=function(){function t(t,i){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=d;var I=function(){function t(t,i,o){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),void 0===o&&(o=n.Zero()),this.position=t,this.normal=i,this.uv=o}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=I;var D=a.prototype.multiplyToArray,S=a.prototype.invertToRef,v=a.LookAtLHToRef,g=r.TransformCoordinatesToRef,T=r.TransformCoordinatesFromFloatsToRef,R=function(){function i(){}return Object.defineProperty(i,\"IsEnabled\",{get:function(){return i._isEnabled},enumerable:!0,configurable:!0}),i.DisableSIMD=function(){a.prototype.multiplyToArray=D,a.prototype.invertToRef=S,a.LookAtLHToRef=v,r.TransformCoordinatesToRef=g,r.TransformCoordinatesFromFloatsToRef=T,i._isEnabled=!1},i.EnableSIMD=function(){void 0!==window.SIMD&&(a.prototype.multiplyToArray=a.prototype.multiplyToArraySIMD,a.prototype.invertToRef=a.prototype.invertToRefSIMD,a.LookAtLHToRef=a.LookAtLHToRefSIMD,r.TransformCoordinatesToRef=r.TransformCoordinatesToRefSIMD,r.TransformCoordinatesFromFloatsToRef=r.TransformCoordinatesFromFloatsToRefSIMD,Object.defineProperty(t.Vector3.prototype,\"x\",{get:function(){return this._data[0]},set:function(t){this._data||(this._data=new Float32Array(3)),this._data[0]=t}}),Object.defineProperty(t.Vector3.prototype,\"y\",{get:function(){return this._data[1]},set:function(t){this._data[1]=t}}),Object.defineProperty(t.Vector3.prototype,\"z\",{get:function(){return this._data[2]},set:function(t){this._data[2]=t}}),i._isEnabled=!0)},i._isEnabled=!1,i}();t.SIMDHelper=R,void 0!==window.SIMD&&R.EnableSIMD()}(BABYLON||(BABYLON={}));";