babylon.2.1-beta.debug.js 1.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508
  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.y !== 1) {
  2717. point = new Vector3(0, -1, 0);
  2718. }
  2719. else if (vt.x !== 1) {
  2720. point = new Vector3(1, 0, 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 && window.SIMD.float32x4 && window.SIMD.float32x4.swizzle) {
  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. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5794. if (instancesCount) {
  5795. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5796. return;
  5797. }
  5798. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5799. };
  5800. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5801. // Apply states
  5802. this.applyStates();
  5803. this._drawCalls++;
  5804. if (instancesCount) {
  5805. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5806. return;
  5807. }
  5808. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5809. };
  5810. // Shaders
  5811. Engine.prototype._releaseEffect = function (effect) {
  5812. if (this._compiledEffects[effect._key]) {
  5813. delete this._compiledEffects[effect._key];
  5814. if (effect.getProgram()) {
  5815. this._gl.deleteProgram(effect.getProgram());
  5816. }
  5817. }
  5818. };
  5819. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5820. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5821. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5822. var name = vertex + "+" + fragment + "@" + defines;
  5823. if (this._compiledEffects[name]) {
  5824. return this._compiledEffects[name];
  5825. }
  5826. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5827. effect._key = name;
  5828. this._compiledEffects[name] = effect;
  5829. return effect;
  5830. };
  5831. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5832. if (uniformsNames === void 0) { uniformsNames = []; }
  5833. if (samplers === void 0) { samplers = []; }
  5834. if (defines === void 0) { defines = ""; }
  5835. return this.createEffect({
  5836. vertex: "particles",
  5837. fragmentElement: fragmentName
  5838. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5839. };
  5840. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5841. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5842. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5843. var shaderProgram = this._gl.createProgram();
  5844. this._gl.attachShader(shaderProgram, vertexShader);
  5845. this._gl.attachShader(shaderProgram, fragmentShader);
  5846. this._gl.linkProgram(shaderProgram);
  5847. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5848. if (!linked) {
  5849. var error = this._gl.getProgramInfoLog(shaderProgram);
  5850. if (error) {
  5851. throw new Error(error);
  5852. }
  5853. }
  5854. this._gl.deleteShader(vertexShader);
  5855. this._gl.deleteShader(fragmentShader);
  5856. return shaderProgram;
  5857. };
  5858. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5859. var results = [];
  5860. for (var index = 0; index < uniformsNames.length; index++) {
  5861. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5862. }
  5863. return results;
  5864. };
  5865. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5866. var results = [];
  5867. for (var index = 0; index < attributesNames.length; index++) {
  5868. try {
  5869. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5870. }
  5871. catch (e) {
  5872. results.push(-1);
  5873. }
  5874. }
  5875. return results;
  5876. };
  5877. Engine.prototype.enableEffect = function (effect) {
  5878. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5879. if (effect && effect.onBind) {
  5880. effect.onBind(effect);
  5881. }
  5882. return;
  5883. }
  5884. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5885. // Use program
  5886. this._gl.useProgram(effect.getProgram());
  5887. for (var i in this._vertexAttribArrays) {
  5888. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5889. continue;
  5890. }
  5891. this._vertexAttribArrays[i] = false;
  5892. this._gl.disableVertexAttribArray(i);
  5893. }
  5894. var attributesCount = effect.getAttributesCount();
  5895. for (var index = 0; index < attributesCount; index++) {
  5896. // Attributes
  5897. var order = effect.getAttributeLocation(index);
  5898. if (order >= 0) {
  5899. this._vertexAttribArrays[order] = true;
  5900. this._gl.enableVertexAttribArray(order);
  5901. }
  5902. }
  5903. this._currentEffect = effect;
  5904. if (effect.onBind) {
  5905. effect.onBind(effect);
  5906. }
  5907. };
  5908. Engine.prototype.setArray = function (uniform, array) {
  5909. if (!uniform)
  5910. return;
  5911. this._gl.uniform1fv(uniform, array);
  5912. };
  5913. Engine.prototype.setArray2 = function (uniform, array) {
  5914. if (!uniform || array.length % 2 !== 0)
  5915. return;
  5916. this._gl.uniform2fv(uniform, array);
  5917. };
  5918. Engine.prototype.setArray3 = function (uniform, array) {
  5919. if (!uniform || array.length % 3 !== 0)
  5920. return;
  5921. this._gl.uniform3fv(uniform, array);
  5922. };
  5923. Engine.prototype.setArray4 = function (uniform, array) {
  5924. if (!uniform || array.length % 4 !== 0)
  5925. return;
  5926. this._gl.uniform4fv(uniform, array);
  5927. };
  5928. Engine.prototype.setMatrices = function (uniform, matrices) {
  5929. if (!uniform)
  5930. return;
  5931. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5932. };
  5933. Engine.prototype.setMatrix = function (uniform, matrix) {
  5934. if (!uniform)
  5935. return;
  5936. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5937. };
  5938. Engine.prototype.setFloat = function (uniform, value) {
  5939. if (!uniform)
  5940. return;
  5941. this._gl.uniform1f(uniform, value);
  5942. };
  5943. Engine.prototype.setFloat2 = function (uniform, x, y) {
  5944. if (!uniform)
  5945. return;
  5946. this._gl.uniform2f(uniform, x, y);
  5947. };
  5948. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  5949. if (!uniform)
  5950. return;
  5951. this._gl.uniform3f(uniform, x, y, z);
  5952. };
  5953. Engine.prototype.setBool = function (uniform, bool) {
  5954. if (!uniform)
  5955. return;
  5956. this._gl.uniform1i(uniform, bool);
  5957. };
  5958. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  5959. if (!uniform)
  5960. return;
  5961. this._gl.uniform4f(uniform, x, y, z, w);
  5962. };
  5963. Engine.prototype.setColor3 = function (uniform, color3) {
  5964. if (!uniform)
  5965. return;
  5966. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  5967. };
  5968. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  5969. if (!uniform)
  5970. return;
  5971. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  5972. };
  5973. // States
  5974. Engine.prototype.setState = function (culling, zOffset, force) {
  5975. if (zOffset === void 0) { zOffset = 0; }
  5976. // Culling
  5977. if (this._depthCullingState.cull !== culling || force) {
  5978. if (culling) {
  5979. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  5980. this._depthCullingState.cull = true;
  5981. }
  5982. else {
  5983. this._depthCullingState.cull = false;
  5984. }
  5985. }
  5986. // Z offset
  5987. this._depthCullingState.zOffset = zOffset;
  5988. };
  5989. Engine.prototype.setDepthBuffer = function (enable) {
  5990. this._depthCullingState.depthTest = enable;
  5991. };
  5992. Engine.prototype.getDepthWrite = function () {
  5993. return this._depthCullingState.depthMask;
  5994. };
  5995. Engine.prototype.setDepthWrite = function (enable) {
  5996. this._depthCullingState.depthMask = enable;
  5997. };
  5998. Engine.prototype.setColorWrite = function (enable) {
  5999. this._gl.colorMask(enable, enable, enable, enable);
  6000. };
  6001. Engine.prototype.setAlphaMode = function (mode) {
  6002. switch (mode) {
  6003. case Engine.ALPHA_DISABLE:
  6004. this.setDepthWrite(true);
  6005. this._alphaState.alphaBlend = false;
  6006. break;
  6007. case Engine.ALPHA_COMBINE:
  6008. this.setDepthWrite(false);
  6009. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6010. this._alphaState.alphaBlend = true;
  6011. break;
  6012. case Engine.ALPHA_ADD:
  6013. this.setDepthWrite(false);
  6014. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6015. this._alphaState.alphaBlend = true;
  6016. break;
  6017. }
  6018. this._alphaMode = mode;
  6019. };
  6020. Engine.prototype.getAlphaMode = function () {
  6021. return this._alphaMode;
  6022. };
  6023. Engine.prototype.setAlphaTesting = function (enable) {
  6024. this._alphaTest = enable;
  6025. };
  6026. Engine.prototype.getAlphaTesting = function () {
  6027. return this._alphaTest;
  6028. };
  6029. // Textures
  6030. Engine.prototype.wipeCaches = function () {
  6031. this._activeTexturesCache = [];
  6032. this._currentEffect = null;
  6033. this._depthCullingState.reset();
  6034. this._alphaState.reset();
  6035. this._cachedVertexBuffers = null;
  6036. this._cachedIndexBuffer = null;
  6037. this._cachedEffectForVertexBuffers = null;
  6038. };
  6039. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6040. var gl = this._gl;
  6041. gl.bindTexture(gl.TEXTURE_2D, texture);
  6042. var magFilter = gl.NEAREST;
  6043. var minFilter = gl.NEAREST;
  6044. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6045. magFilter = gl.LINEAR;
  6046. minFilter = gl.LINEAR;
  6047. }
  6048. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6049. magFilter = gl.LINEAR;
  6050. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6051. }
  6052. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6053. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6054. gl.bindTexture(gl.TEXTURE_2D, null);
  6055. texture.samplingMode = samplingMode;
  6056. };
  6057. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6058. var _this = this;
  6059. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6060. if (onLoad === void 0) { onLoad = null; }
  6061. if (onError === void 0) { onError = null; }
  6062. if (buffer === void 0) { buffer = null; }
  6063. var texture = this._gl.createTexture();
  6064. var extension;
  6065. var fromData = false;
  6066. if (url.substr(0, 5) === "data:") {
  6067. fromData = true;
  6068. }
  6069. if (!fromData)
  6070. extension = url.substr(url.length - 4, 4).toLowerCase();
  6071. else {
  6072. var oldUrl = url;
  6073. fromData = oldUrl.split(':');
  6074. url = oldUrl;
  6075. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6076. }
  6077. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6078. var isTGA = (extension === ".tga");
  6079. scene._addPendingData(texture);
  6080. texture.url = url;
  6081. texture.noMipmap = noMipmap;
  6082. texture.references = 1;
  6083. texture.samplingMode = samplingMode;
  6084. this._loadedTexturesCache.push(texture);
  6085. var onerror = function () {
  6086. scene._removePendingData(texture);
  6087. if (onError) {
  6088. onError();
  6089. }
  6090. };
  6091. if (isTGA) {
  6092. var callback = function (arrayBuffer) {
  6093. var data = new Uint8Array(arrayBuffer);
  6094. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6095. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6096. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6097. if (onLoad) {
  6098. onLoad();
  6099. }
  6100. }, samplingMode);
  6101. };
  6102. if (!(fromData instanceof Array))
  6103. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6104. callback(arrayBuffer);
  6105. }, onerror, scene.database, true);
  6106. else
  6107. callback(buffer);
  6108. }
  6109. else if (isDDS) {
  6110. callback = function (data) {
  6111. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6112. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6113. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6114. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6115. if (onLoad) {
  6116. onLoad();
  6117. }
  6118. }, samplingMode);
  6119. };
  6120. if (!(fromData instanceof Array))
  6121. BABYLON.Tools.LoadFile(url, function (data) {
  6122. callback(data);
  6123. }, onerror, scene.database, true);
  6124. else
  6125. callback(buffer);
  6126. }
  6127. else {
  6128. var onload = function (img) {
  6129. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6130. var isPot = (img.width === potWidth && img.height === potHeight);
  6131. if (!isPot) {
  6132. _this._prepareWorkingCanvas();
  6133. _this._workingCanvas.width = potWidth;
  6134. _this._workingCanvas.height = potHeight;
  6135. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6136. _this._workingContext.imageSmoothingEnabled = false;
  6137. _this._workingContext.mozImageSmoothingEnabled = false;
  6138. _this._workingContext.oImageSmoothingEnabled = false;
  6139. _this._workingContext.webkitImageSmoothingEnabled = false;
  6140. _this._workingContext.msImageSmoothingEnabled = false;
  6141. }
  6142. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6143. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6144. _this._workingContext.imageSmoothingEnabled = true;
  6145. _this._workingContext.mozImageSmoothingEnabled = true;
  6146. _this._workingContext.oImageSmoothingEnabled = true;
  6147. _this._workingContext.webkitImageSmoothingEnabled = true;
  6148. _this._workingContext.msImageSmoothingEnabled = true;
  6149. }
  6150. }
  6151. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6152. if (onLoad) {
  6153. onLoad();
  6154. }
  6155. }, samplingMode);
  6156. };
  6157. if (!(fromData instanceof Array))
  6158. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6159. else
  6160. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6161. }
  6162. return texture;
  6163. };
  6164. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  6165. var texture = this._gl.createTexture();
  6166. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6167. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6168. // Format
  6169. var internalFormat = this._gl.RGBA;
  6170. switch (format) {
  6171. case Engine.TEXTUREFORMAT_ALPHA:
  6172. internalFormat = this._gl.ALPHA;
  6173. break;
  6174. case Engine.TEXTUREFORMAT_LUMINANCE:
  6175. internalFormat = this._gl.LUMINANCE;
  6176. break;
  6177. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6178. internalFormat = this._gl.LUMINANCE_ALPHA;
  6179. break;
  6180. case Engine.TEXTUREFORMAT_RGB:
  6181. internalFormat = this._gl.RGB;
  6182. break;
  6183. case Engine.TEXTUREFORMAT_RGBA:
  6184. internalFormat = this._gl.RGBA;
  6185. break;
  6186. }
  6187. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6188. if (generateMipMaps) {
  6189. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6190. }
  6191. // Filters
  6192. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6193. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6194. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6195. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6196. this._activeTexturesCache = [];
  6197. texture._baseWidth = width;
  6198. texture._baseHeight = height;
  6199. texture._width = width;
  6200. texture._height = height;
  6201. texture.isReady = true;
  6202. texture.references = 1;
  6203. texture.samplingMode = samplingMode;
  6204. this._loadedTexturesCache.push(texture);
  6205. return texture;
  6206. };
  6207. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  6208. var texture = this._gl.createTexture();
  6209. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6210. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6211. this._activeTexturesCache = [];
  6212. texture._baseWidth = width;
  6213. texture._baseHeight = height;
  6214. texture._width = width;
  6215. texture._height = height;
  6216. texture.isReady = false;
  6217. texture.generateMipMaps = generateMipMaps;
  6218. texture.references = 1;
  6219. texture.samplingMode = samplingMode;
  6220. this.updateTextureSamplingMode(samplingMode, texture);
  6221. this._loadedTexturesCache.push(texture);
  6222. return texture;
  6223. };
  6224. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6225. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6226. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6227. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6228. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6229. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6230. };
  6231. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6232. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6233. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6234. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6235. if (texture.generateMipMaps) {
  6236. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6237. }
  6238. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6239. this._activeTexturesCache = [];
  6240. texture.isReady = true;
  6241. };
  6242. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6243. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6244. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6245. // Scale the video if it is a NPOT using the current working canvas
  6246. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  6247. if (!texture._workingCanvas) {
  6248. texture._workingCanvas = document.createElement("canvas");
  6249. texture._workingContext = texture._workingCanvas.getContext("2d");
  6250. texture._workingCanvas.width = texture._width;
  6251. texture._workingCanvas.height = texture._height;
  6252. }
  6253. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6254. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6255. }
  6256. else {
  6257. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6258. }
  6259. if (texture.generateMipMaps) {
  6260. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6261. }
  6262. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6263. this._activeTexturesCache = [];
  6264. texture.isReady = true;
  6265. };
  6266. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6267. // old version had a "generateMipMaps" arg instead of options.
  6268. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6269. // in the same way, generateDepthBuffer is defaulted to true
  6270. var generateMipMaps = false;
  6271. var generateDepthBuffer = true;
  6272. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6273. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6274. if (options !== undefined) {
  6275. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6276. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6277. type = options.type === undefined ? type : options.type;
  6278. if (options.samplingMode !== undefined) {
  6279. samplingMode = options.samplingMode;
  6280. }
  6281. if (type === Engine.TEXTURETYPE_FLOAT) {
  6282. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6283. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6284. }
  6285. }
  6286. var gl = this._gl;
  6287. var texture = gl.createTexture();
  6288. gl.bindTexture(gl.TEXTURE_2D, texture);
  6289. var width = size.width || size;
  6290. var height = size.height || size;
  6291. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6292. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6293. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6294. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6295. }
  6296. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6297. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6298. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6299. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6300. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6301. var depthBuffer;
  6302. // Create the depth buffer
  6303. if (generateDepthBuffer) {
  6304. depthBuffer = gl.createRenderbuffer();
  6305. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6306. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6307. }
  6308. // Create the framebuffer
  6309. var framebuffer = gl.createFramebuffer();
  6310. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6311. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6312. if (generateDepthBuffer) {
  6313. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6314. }
  6315. // Unbind
  6316. gl.bindTexture(gl.TEXTURE_2D, null);
  6317. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6318. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6319. texture._framebuffer = framebuffer;
  6320. if (generateDepthBuffer) {
  6321. texture._depthBuffer = depthBuffer;
  6322. }
  6323. texture._width = width;
  6324. texture._height = height;
  6325. texture.isReady = true;
  6326. texture.generateMipMaps = generateMipMaps;
  6327. texture.references = 1;
  6328. texture.samplingMode = samplingMode;
  6329. this._activeTexturesCache = [];
  6330. this._loadedTexturesCache.push(texture);
  6331. return texture;
  6332. };
  6333. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6334. var _this = this;
  6335. var gl = this._gl;
  6336. var texture = gl.createTexture();
  6337. texture.isCube = true;
  6338. texture.url = rootUrl;
  6339. texture.references = 1;
  6340. this._loadedTexturesCache.push(texture);
  6341. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6342. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6343. if (isDDS) {
  6344. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6345. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6346. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6347. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6348. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6349. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6350. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6351. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6352. }
  6353. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6354. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6355. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6356. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6357. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6358. _this._activeTexturesCache = [];
  6359. texture._width = info.width;
  6360. texture._height = info.height;
  6361. texture.isReady = true;
  6362. }, null, null, true);
  6363. }
  6364. else {
  6365. cascadeLoad(rootUrl, scene, function (imgs) {
  6366. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6367. var height = width;
  6368. _this._prepareWorkingCanvas();
  6369. _this._workingCanvas.width = width;
  6370. _this._workingCanvas.height = height;
  6371. var faces = [
  6372. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  6373. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  6374. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6375. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  6376. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  6377. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6378. ];
  6379. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6380. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6381. for (var index = 0; index < faces.length; index++) {
  6382. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6383. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6384. }
  6385. if (!noMipmap) {
  6386. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6387. }
  6388. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6389. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6390. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6391. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6392. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6393. _this._activeTexturesCache = [];
  6394. texture._width = width;
  6395. texture._height = height;
  6396. texture.isReady = true;
  6397. }, extensions);
  6398. }
  6399. return texture;
  6400. };
  6401. Engine.prototype._releaseTexture = function (texture) {
  6402. var gl = this._gl;
  6403. if (texture._framebuffer) {
  6404. gl.deleteFramebuffer(texture._framebuffer);
  6405. }
  6406. if (texture._depthBuffer) {
  6407. gl.deleteRenderbuffer(texture._depthBuffer);
  6408. }
  6409. gl.deleteTexture(texture);
  6410. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6411. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6412. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6413. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6414. this._activeTexturesCache[channel] = null;
  6415. }
  6416. var index = this._loadedTexturesCache.indexOf(texture);
  6417. if (index !== -1) {
  6418. this._loadedTexturesCache.splice(index, 1);
  6419. }
  6420. };
  6421. Engine.prototype.bindSamplers = function (effect) {
  6422. this._gl.useProgram(effect.getProgram());
  6423. var samplers = effect.getSamplers();
  6424. for (var index = 0; index < samplers.length; index++) {
  6425. var uniform = effect.getUniform(samplers[index]);
  6426. this._gl.uniform1i(uniform, index);
  6427. }
  6428. this._currentEffect = null;
  6429. };
  6430. Engine.prototype._bindTexture = function (channel, texture) {
  6431. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6432. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6433. this._activeTexturesCache[channel] = null;
  6434. };
  6435. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6436. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6437. };
  6438. Engine.prototype.setTexture = function (channel, texture) {
  6439. if (channel < 0) {
  6440. return;
  6441. }
  6442. // Not ready?
  6443. if (!texture || !texture.isReady()) {
  6444. if (this._activeTexturesCache[channel] != null) {
  6445. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6446. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6447. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6448. this._activeTexturesCache[channel] = null;
  6449. }
  6450. return;
  6451. }
  6452. // Video
  6453. if (texture instanceof BABYLON.VideoTexture) {
  6454. if (texture.update()) {
  6455. this._activeTexturesCache[channel] = null;
  6456. }
  6457. }
  6458. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6459. texture.delayLoad();
  6460. return;
  6461. }
  6462. if (this._activeTexturesCache[channel] === texture) {
  6463. return;
  6464. }
  6465. this._activeTexturesCache[channel] = texture;
  6466. var internalTexture = texture.getInternalTexture();
  6467. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6468. if (internalTexture.isCube) {
  6469. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6470. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6471. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6472. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6473. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6474. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6475. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6476. }
  6477. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6478. }
  6479. else {
  6480. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6481. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6482. internalTexture._cachedWrapU = texture.wrapU;
  6483. switch (texture.wrapU) {
  6484. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6485. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6486. break;
  6487. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6488. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6489. break;
  6490. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6491. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6492. break;
  6493. }
  6494. }
  6495. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6496. internalTexture._cachedWrapV = texture.wrapV;
  6497. switch (texture.wrapV) {
  6498. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6499. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6500. break;
  6501. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6502. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6503. break;
  6504. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6505. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6506. break;
  6507. }
  6508. }
  6509. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6510. }
  6511. };
  6512. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6513. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6514. var value = texture.anisotropicFilteringLevel;
  6515. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6516. value = 1;
  6517. }
  6518. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6519. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6520. texture._cachedAnisotropicFilteringLevel = value;
  6521. }
  6522. };
  6523. Engine.prototype.readPixels = function (x, y, width, height) {
  6524. var data = new Uint8Array(height * width * 4);
  6525. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6526. return data;
  6527. };
  6528. // Dispose
  6529. Engine.prototype.dispose = function () {
  6530. this.hideLoadingUI();
  6531. this.stopRenderLoop();
  6532. while (this.scenes.length) {
  6533. this.scenes[0].dispose();
  6534. }
  6535. // Release audio engine
  6536. Engine.audioEngine.dispose();
  6537. for (var name in this._compiledEffects) {
  6538. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6539. }
  6540. for (var i in this._vertexAttribArrays) {
  6541. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6542. continue;
  6543. }
  6544. this._gl.disableVertexAttribArray(i);
  6545. }
  6546. // Events
  6547. window.removeEventListener("blur", this._onBlur);
  6548. window.removeEventListener("focus", this._onFocus);
  6549. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6550. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6551. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6552. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6553. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6554. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6555. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6556. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6557. };
  6558. // Loading screen
  6559. Engine.prototype.displayLoadingUI = function () {
  6560. var _this = this;
  6561. this._loadingDiv = document.createElement("div");
  6562. this._loadingDiv.style.opacity = "0";
  6563. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6564. // Loading text
  6565. this._loadingTextDiv = document.createElement("div");
  6566. this._loadingTextDiv.style.position = "absolute";
  6567. this._loadingTextDiv.style.left = "0";
  6568. this._loadingTextDiv.style.top = "50%";
  6569. this._loadingTextDiv.style.marginTop = "80px";
  6570. this._loadingTextDiv.style.width = "100%";
  6571. this._loadingTextDiv.style.height = "20px";
  6572. this._loadingTextDiv.style.fontFamily = "Arial";
  6573. this._loadingTextDiv.style.fontSize = "14px";
  6574. this._loadingTextDiv.style.color = "white";
  6575. this._loadingTextDiv.style.textAlign = "center";
  6576. this._loadingTextDiv.innerHTML = "Loading";
  6577. this._loadingDiv.appendChild(this._loadingTextDiv);
  6578. // Loading img
  6579. var imgBack = new Image();
  6580. 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==";
  6581. imgBack.style.position = "absolute";
  6582. imgBack.style.left = "50%";
  6583. imgBack.style.top = "50%";
  6584. imgBack.style.marginLeft = "-50px";
  6585. imgBack.style.marginTop = "-50px";
  6586. imgBack.style.transition = "transform 1.0s ease";
  6587. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6588. var deg = 360;
  6589. var onTransitionEnd = function () {
  6590. deg += 360;
  6591. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6592. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6593. };
  6594. imgBack.addEventListener("transitionend", onTransitionEnd);
  6595. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6596. this._loadingDiv.appendChild(imgBack);
  6597. // front image
  6598. var imgFront = new Image();
  6599. 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=";
  6600. imgFront.style.position = "absolute";
  6601. imgFront.style.left = "50%";
  6602. imgFront.style.top = "50%";
  6603. imgFront.style.marginLeft = "-50px";
  6604. imgFront.style.marginTop = "-50px";
  6605. this._loadingDiv.appendChild(imgFront);
  6606. // Resize
  6607. this._resizeLoadingUI = function () {
  6608. var canvasRect = _this.getRenderingCanvasClientRect();
  6609. _this._loadingDiv.style.position = "absolute";
  6610. _this._loadingDiv.style.left = canvasRect.left + "px";
  6611. _this._loadingDiv.style.top = canvasRect.top + "px";
  6612. _this._loadingDiv.style.width = canvasRect.width + "px";
  6613. _this._loadingDiv.style.height = canvasRect.height + "px";
  6614. };
  6615. this._resizeLoadingUI();
  6616. window.addEventListener("resize", this._resizeLoadingUI);
  6617. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6618. document.body.appendChild(this._loadingDiv);
  6619. setTimeout(function () {
  6620. _this._loadingDiv.style.opacity = "1";
  6621. imgBack.style.transform = "rotateZ(360deg)";
  6622. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6623. }, 0);
  6624. };
  6625. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6626. set: function (text) {
  6627. if (!this._loadingDiv) {
  6628. return;
  6629. }
  6630. this._loadingTextDiv.innerHTML = text;
  6631. },
  6632. enumerable: true,
  6633. configurable: true
  6634. });
  6635. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6636. get: function () {
  6637. return this._loadingDivBackgroundColor;
  6638. },
  6639. set: function (color) {
  6640. this._loadingDivBackgroundColor = color;
  6641. if (!this._loadingDiv) {
  6642. return;
  6643. }
  6644. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6645. },
  6646. enumerable: true,
  6647. configurable: true
  6648. });
  6649. Engine.prototype.hideLoadingUI = function () {
  6650. var _this = this;
  6651. if (!this._loadingDiv) {
  6652. return;
  6653. }
  6654. var onTransitionEnd = function () {
  6655. if (!_this._loadingDiv) {
  6656. return;
  6657. }
  6658. document.body.removeChild(_this._loadingDiv);
  6659. window.removeEventListener("resize", _this._resizeLoadingUI);
  6660. _this._loadingDiv = null;
  6661. };
  6662. this._loadingDiv.style.opacity = "0";
  6663. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  6664. };
  6665. // FPS
  6666. Engine.prototype.getFps = function () {
  6667. return this.fps;
  6668. };
  6669. Engine.prototype.getDeltaTime = function () {
  6670. return this.deltaTime;
  6671. };
  6672. Engine.prototype._measureFps = function () {
  6673. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6674. var length = this.previousFramesDuration.length;
  6675. if (length >= 2) {
  6676. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6677. }
  6678. if (length >= this.fpsRange) {
  6679. if (length > this.fpsRange) {
  6680. this.previousFramesDuration.splice(0, 1);
  6681. length = this.previousFramesDuration.length;
  6682. }
  6683. var sum = 0;
  6684. for (var id = 0; id < length - 1; id++) {
  6685. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6686. }
  6687. this.fps = 1000.0 / (sum / (length - 1));
  6688. }
  6689. };
  6690. // Statics
  6691. Engine.isSupported = function () {
  6692. try {
  6693. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6694. if (navigator.isCocoonJS) {
  6695. return true;
  6696. }
  6697. var tempcanvas = document.createElement("canvas");
  6698. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6699. return gl != null && !!window.WebGLRenderingContext;
  6700. }
  6701. catch (e) {
  6702. return false;
  6703. }
  6704. };
  6705. // Const statics
  6706. Engine._ALPHA_DISABLE = 0;
  6707. Engine._ALPHA_ADD = 1;
  6708. Engine._ALPHA_COMBINE = 2;
  6709. Engine._DELAYLOADSTATE_NONE = 0;
  6710. Engine._DELAYLOADSTATE_LOADED = 1;
  6711. Engine._DELAYLOADSTATE_LOADING = 2;
  6712. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6713. Engine._TEXTUREFORMAT_ALPHA = 0;
  6714. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6715. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6716. Engine._TEXTUREFORMAT_RGB = 4;
  6717. Engine._TEXTUREFORMAT_RGBA = 4;
  6718. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6719. Engine._TEXTURETYPE_FLOAT = 1;
  6720. // Updatable statics so stick with vars here
  6721. Engine.Epsilon = 0.001;
  6722. Engine.CollisionsEpsilon = 0.001;
  6723. Engine.CodeRepository = "Babylon/";
  6724. Engine.ShadersRepository = "Babylon/Shaders/";
  6725. return Engine;
  6726. })();
  6727. BABYLON.Engine = Engine;
  6728. })(BABYLON || (BABYLON = {}));
  6729. //# sourceMappingURL=babylon.engine.js.map
  6730. var BABYLON;
  6731. (function (BABYLON) {
  6732. /**
  6733. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6734. */
  6735. var Node = (function () {
  6736. /**
  6737. * @constructor
  6738. * @param {string} name - the name and id to be given to this node
  6739. * @param {BABYLON.Scene} the scene this node will be added to
  6740. */
  6741. function Node(name, scene) {
  6742. this.state = "";
  6743. this.animations = new Array();
  6744. this._childrenFlag = -1;
  6745. this._isEnabled = true;
  6746. this._isReady = true;
  6747. this._currentRenderId = -1;
  6748. this._parentRenderId = -1;
  6749. this.name = name;
  6750. this.id = name;
  6751. this._scene = scene;
  6752. this._initCache();
  6753. }
  6754. Node.prototype.getScene = function () {
  6755. return this._scene;
  6756. };
  6757. Node.prototype.getEngine = function () {
  6758. return this._scene.getEngine();
  6759. };
  6760. // override it in derived class
  6761. Node.prototype.getWorldMatrix = function () {
  6762. return BABYLON.Matrix.Identity();
  6763. };
  6764. // override it in derived class if you add new variables to the cache
  6765. // and call the parent class method
  6766. Node.prototype._initCache = function () {
  6767. this._cache = {};
  6768. this._cache.parent = undefined;
  6769. };
  6770. Node.prototype.updateCache = function (force) {
  6771. if (!force && this.isSynchronized())
  6772. return;
  6773. this._cache.parent = this.parent;
  6774. this._updateCache();
  6775. };
  6776. // override it in derived class if you add new variables to the cache
  6777. // and call the parent class method if !ignoreParentClass
  6778. Node.prototype._updateCache = function (ignoreParentClass) {
  6779. };
  6780. // override it in derived class if you add new variables to the cache
  6781. Node.prototype._isSynchronized = function () {
  6782. return true;
  6783. };
  6784. Node.prototype._markSyncedWithParent = function () {
  6785. this._parentRenderId = this.parent._currentRenderId;
  6786. };
  6787. Node.prototype.isSynchronizedWithParent = function () {
  6788. if (!this.parent) {
  6789. return true;
  6790. }
  6791. if (this._parentRenderId !== this.parent._currentRenderId) {
  6792. return false;
  6793. }
  6794. return this.parent.isSynchronized();
  6795. };
  6796. Node.prototype.isSynchronized = function (updateCache) {
  6797. var check = this.hasNewParent();
  6798. check = check || !this.isSynchronizedWithParent();
  6799. check = check || !this._isSynchronized();
  6800. if (updateCache)
  6801. this.updateCache(true);
  6802. return !check;
  6803. };
  6804. Node.prototype.hasNewParent = function (update) {
  6805. if (this._cache.parent === this.parent)
  6806. return false;
  6807. if (update)
  6808. this._cache.parent = this.parent;
  6809. return true;
  6810. };
  6811. /**
  6812. * Is this node ready to be used/rendered
  6813. * @return {boolean} is it ready
  6814. */
  6815. Node.prototype.isReady = function () {
  6816. return this._isReady;
  6817. };
  6818. /**
  6819. * Is this node enabled.
  6820. * If the node has a parent and is enabled, the parent will be inspected as well.
  6821. * @return {boolean} whether this node (and its parent) is enabled.
  6822. * @see setEnabled
  6823. */
  6824. Node.prototype.isEnabled = function () {
  6825. if (!this._isEnabled) {
  6826. return false;
  6827. }
  6828. if (this.parent) {
  6829. return this.parent.isEnabled();
  6830. }
  6831. return true;
  6832. };
  6833. /**
  6834. * Set the enabled state of this node.
  6835. * @param {boolean} value - the new enabled state
  6836. * @see isEnabled
  6837. */
  6838. Node.prototype.setEnabled = function (value) {
  6839. this._isEnabled = value;
  6840. };
  6841. /**
  6842. * Is this node a descendant of the given node.
  6843. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6844. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6845. * @see parent
  6846. */
  6847. Node.prototype.isDescendantOf = function (ancestor) {
  6848. if (this.parent) {
  6849. if (this.parent === ancestor) {
  6850. return true;
  6851. }
  6852. return this.parent.isDescendantOf(ancestor);
  6853. }
  6854. return false;
  6855. };
  6856. Node.prototype._getDescendants = function (list, results) {
  6857. for (var index = 0; index < list.length; index++) {
  6858. var item = list[index];
  6859. if (item.isDescendantOf(this)) {
  6860. results.push(item);
  6861. }
  6862. }
  6863. };
  6864. /**
  6865. * Will return all nodes that have this node as parent.
  6866. * @return {BABYLON.Node[]} all children nodes of all types.
  6867. */
  6868. Node.prototype.getDescendants = function () {
  6869. var results = [];
  6870. this._getDescendants(this._scene.meshes, results);
  6871. this._getDescendants(this._scene.lights, results);
  6872. this._getDescendants(this._scene.cameras, results);
  6873. return results;
  6874. };
  6875. Node.prototype._setReady = function (state) {
  6876. if (state == this._isReady) {
  6877. return;
  6878. }
  6879. if (!state) {
  6880. this._isReady = false;
  6881. return;
  6882. }
  6883. this._isReady = true;
  6884. if (this.onReady) {
  6885. this.onReady(this);
  6886. }
  6887. };
  6888. return Node;
  6889. })();
  6890. BABYLON.Node = Node;
  6891. })(BABYLON || (BABYLON = {}));
  6892. //# sourceMappingURL=babylon.node.js.map
  6893. var BABYLON;
  6894. (function (BABYLON) {
  6895. var FilesInput = (function () {
  6896. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  6897. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  6898. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  6899. this._engine = p_engine;
  6900. this._canvas = p_canvas;
  6901. this._currentScene = p_scene;
  6902. this._sceneLoadedCallback = p_sceneLoadedCallback;
  6903. this._progressCallback = p_progressCallback;
  6904. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  6905. this._textureLoadingCallback = p_textureLoadingCallback;
  6906. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  6907. }
  6908. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  6909. var _this = this;
  6910. if (p_elementToMonitor) {
  6911. this._elementToMonitor = p_elementToMonitor;
  6912. this._elementToMonitor.addEventListener("dragenter", function (e) {
  6913. _this.drag(e);
  6914. }, false);
  6915. this._elementToMonitor.addEventListener("dragover", function (e) {
  6916. _this.drag(e);
  6917. }, false);
  6918. this._elementToMonitor.addEventListener("drop", function (e) {
  6919. _this.drop(e);
  6920. }, false);
  6921. }
  6922. };
  6923. FilesInput.prototype.renderFunction = function () {
  6924. if (this._additionnalRenderLoopLogicCallback) {
  6925. this._additionnalRenderLoopLogicCallback();
  6926. }
  6927. if (this._currentScene) {
  6928. if (this._textureLoadingCallback) {
  6929. var remaining = this._currentScene.getWaitingItemsCount();
  6930. if (remaining > 0) {
  6931. this._textureLoadingCallback(remaining);
  6932. }
  6933. }
  6934. this._currentScene.render();
  6935. }
  6936. };
  6937. FilesInput.prototype.drag = function (e) {
  6938. e.stopPropagation();
  6939. e.preventDefault();
  6940. };
  6941. FilesInput.prototype.drop = function (eventDrop) {
  6942. eventDrop.stopPropagation();
  6943. eventDrop.preventDefault();
  6944. this.loadFiles(eventDrop);
  6945. };
  6946. FilesInput.prototype.loadFiles = function (event) {
  6947. if (this._startingProcessingFilesCallback)
  6948. this._startingProcessingFilesCallback();
  6949. // Handling data transfer via drag'n'drop
  6950. if (event && event.dataTransfer && event.dataTransfer.files) {
  6951. this._filesToLoad = event.dataTransfer.files;
  6952. }
  6953. // Handling files from input files
  6954. if (event && event.target && event.target.files) {
  6955. this._filesToLoad = event.target.files;
  6956. }
  6957. if (this._filesToLoad && this._filesToLoad.length > 0) {
  6958. for (var i = 0; i < this._filesToLoad.length; i++) {
  6959. switch (this._filesToLoad[i].type) {
  6960. case "image/jpeg":
  6961. case "image/png":
  6962. case "image/bmp":
  6963. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  6964. break;
  6965. case "image/targa":
  6966. case "image/vnd.ms-dds":
  6967. case "audio/wav":
  6968. case "audio/x-wav":
  6969. case "audio/mp3":
  6970. case "audio/mpeg":
  6971. case "audio/mpeg3":
  6972. case "audio/x-mpeg-3":
  6973. case "audio/ogg":
  6974. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  6975. break;
  6976. default:
  6977. 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) {
  6978. this._sceneFileToLoad = this._filesToLoad[i];
  6979. }
  6980. break;
  6981. }
  6982. }
  6983. this.reload();
  6984. }
  6985. };
  6986. FilesInput.prototype.reload = function () {
  6987. var _this = this;
  6988. var that = this;
  6989. // If a ".babylon" file has been provided
  6990. if (this._sceneFileToLoad) {
  6991. if (this._currentScene) {
  6992. this._engine.stopRenderLoop();
  6993. this._currentScene.dispose();
  6994. }
  6995. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  6996. that._currentScene = newScene;
  6997. // Wait for textures and shaders to be ready
  6998. that._currentScene.executeWhenReady(function () {
  6999. // Attach camera to canvas inputs
  7000. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7001. that._currentScene.createDefaultCameraOrLight();
  7002. }
  7003. that._currentScene.activeCamera.attachControl(that._canvas);
  7004. if (that._sceneLoadedCallback) {
  7005. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7006. }
  7007. that._engine.runRenderLoop(function () {
  7008. that.renderFunction();
  7009. });
  7010. });
  7011. }, function (progress) {
  7012. if (_this._progressCallback) {
  7013. _this._progressCallback(progress);
  7014. }
  7015. });
  7016. }
  7017. else {
  7018. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7019. }
  7020. };
  7021. FilesInput.FilesTextures = new Array();
  7022. FilesInput.FilesToLoad = new Array();
  7023. return FilesInput;
  7024. })();
  7025. BABYLON.FilesInput = FilesInput;
  7026. })(BABYLON || (BABYLON = {}));
  7027. //# sourceMappingURL=babylon.filesInput.js.map
  7028. var BABYLON;
  7029. (function (BABYLON) {
  7030. var IntersectionInfo = (function () {
  7031. function IntersectionInfo(bu, bv, distance) {
  7032. this.bu = bu;
  7033. this.bv = bv;
  7034. this.distance = distance;
  7035. this.faceId = 0;
  7036. this.subMeshId = 0;
  7037. }
  7038. return IntersectionInfo;
  7039. })();
  7040. BABYLON.IntersectionInfo = IntersectionInfo;
  7041. var PickingInfo = (function () {
  7042. function PickingInfo() {
  7043. this.hit = false;
  7044. this.distance = 0;
  7045. this.pickedPoint = null;
  7046. this.pickedMesh = null;
  7047. this.bu = 0;
  7048. this.bv = 0;
  7049. this.faceId = -1;
  7050. this.subMeshId = 0;
  7051. }
  7052. // Methods
  7053. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  7054. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7055. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7056. return null;
  7057. }
  7058. var indices = this.pickedMesh.getIndices();
  7059. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7060. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7061. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7062. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7063. normal0 = normal0.scale(this.bu);
  7064. normal1 = normal1.scale(this.bv);
  7065. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7066. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7067. if (useWorldCoordinates) {
  7068. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7069. }
  7070. return result;
  7071. };
  7072. PickingInfo.prototype.getTextureCoordinates = function () {
  7073. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7074. return null;
  7075. }
  7076. var indices = this.pickedMesh.getIndices();
  7077. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7078. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7079. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7080. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7081. uv0 = uv0.scale(this.bu);
  7082. uv1 = uv1.scale(this.bv);
  7083. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  7084. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7085. };
  7086. return PickingInfo;
  7087. })();
  7088. BABYLON.PickingInfo = PickingInfo;
  7089. })(BABYLON || (BABYLON = {}));
  7090. //# sourceMappingURL=babylon.pickingInfo.js.map
  7091. var BABYLON;
  7092. (function (BABYLON) {
  7093. var BoundingSphere = (function () {
  7094. function BoundingSphere(minimum, maximum) {
  7095. this.minimum = minimum;
  7096. this.maximum = maximum;
  7097. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7098. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7099. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7100. this.radius = distance * 0.5;
  7101. this.centerWorld = BABYLON.Vector3.Zero();
  7102. this._update(BABYLON.Matrix.Identity());
  7103. }
  7104. // Methods
  7105. BoundingSphere.prototype._update = function (world) {
  7106. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7107. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7108. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7109. };
  7110. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7111. for (var i = 0; i < 6; i++) {
  7112. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7113. return false;
  7114. }
  7115. return true;
  7116. };
  7117. BoundingSphere.prototype.intersectsPoint = function (point) {
  7118. var x = this.centerWorld.x - point.x;
  7119. var y = this.centerWorld.y - point.y;
  7120. var z = this.centerWorld.z - point.z;
  7121. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7122. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7123. return false;
  7124. return true;
  7125. };
  7126. // Statics
  7127. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7128. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7129. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7130. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7131. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7132. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7133. return false;
  7134. return true;
  7135. };
  7136. return BoundingSphere;
  7137. })();
  7138. BABYLON.BoundingSphere = BoundingSphere;
  7139. })(BABYLON || (BABYLON = {}));
  7140. //# sourceMappingURL=babylon.boundingSphere.js.map
  7141. var BABYLON;
  7142. (function (BABYLON) {
  7143. var BoundingBox = (function () {
  7144. function BoundingBox(minimum, maximum) {
  7145. this.minimum = minimum;
  7146. this.maximum = maximum;
  7147. this.vectors = new Array();
  7148. this.vectorsWorld = new Array();
  7149. // Bounding vectors
  7150. this.vectors.push(this.minimum.clone());
  7151. this.vectors.push(this.maximum.clone());
  7152. this.vectors.push(this.minimum.clone());
  7153. this.vectors[2].x = this.maximum.x;
  7154. this.vectors.push(this.minimum.clone());
  7155. this.vectors[3].y = this.maximum.y;
  7156. this.vectors.push(this.minimum.clone());
  7157. this.vectors[4].z = this.maximum.z;
  7158. this.vectors.push(this.maximum.clone());
  7159. this.vectors[5].z = this.minimum.z;
  7160. this.vectors.push(this.maximum.clone());
  7161. this.vectors[6].x = this.minimum.x;
  7162. this.vectors.push(this.maximum.clone());
  7163. this.vectors[7].y = this.minimum.y;
  7164. // OBB
  7165. this.center = this.maximum.add(this.minimum).scale(0.5);
  7166. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7167. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7168. for (var index = 0; index < this.vectors.length; index++) {
  7169. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7170. }
  7171. this.minimumWorld = BABYLON.Vector3.Zero();
  7172. this.maximumWorld = BABYLON.Vector3.Zero();
  7173. this._update(BABYLON.Matrix.Identity());
  7174. }
  7175. // Methods
  7176. BoundingBox.prototype.getWorldMatrix = function () {
  7177. return this._worldMatrix;
  7178. };
  7179. BoundingBox.prototype._update = function (world) {
  7180. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7181. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7182. for (var index = 0; index < this.vectors.length; index++) {
  7183. var v = this.vectorsWorld[index];
  7184. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7185. if (v.x < this.minimumWorld.x)
  7186. this.minimumWorld.x = v.x;
  7187. if (v.y < this.minimumWorld.y)
  7188. this.minimumWorld.y = v.y;
  7189. if (v.z < this.minimumWorld.z)
  7190. this.minimumWorld.z = v.z;
  7191. if (v.x > this.maximumWorld.x)
  7192. this.maximumWorld.x = v.x;
  7193. if (v.y > this.maximumWorld.y)
  7194. this.maximumWorld.y = v.y;
  7195. if (v.z > this.maximumWorld.z)
  7196. this.maximumWorld.z = v.z;
  7197. }
  7198. // OBB
  7199. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7200. this.center.scaleInPlace(0.5);
  7201. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7202. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7203. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7204. this._worldMatrix = world;
  7205. };
  7206. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7207. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7208. };
  7209. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7210. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7211. };
  7212. BoundingBox.prototype.intersectsPoint = function (point) {
  7213. var delta = -BABYLON.Engine.Epsilon;
  7214. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7215. return false;
  7216. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7217. return false;
  7218. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7219. return false;
  7220. return true;
  7221. };
  7222. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7223. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7224. };
  7225. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7226. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7227. return false;
  7228. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7229. return false;
  7230. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7231. return false;
  7232. return true;
  7233. };
  7234. // Statics
  7235. BoundingBox.Intersects = function (box0, box1) {
  7236. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7237. return false;
  7238. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7239. return false;
  7240. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7241. return false;
  7242. return true;
  7243. };
  7244. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7245. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7246. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7247. return (num <= (sphereRadius * sphereRadius));
  7248. };
  7249. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7250. for (var p = 0; p < 6; p++) {
  7251. for (var i = 0; i < 8; i++) {
  7252. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7253. return false;
  7254. }
  7255. }
  7256. }
  7257. return true;
  7258. };
  7259. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7260. for (var p = 0; p < 6; p++) {
  7261. var inCount = 8;
  7262. for (var i = 0; i < 8; i++) {
  7263. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7264. --inCount;
  7265. }
  7266. else {
  7267. break;
  7268. }
  7269. }
  7270. if (inCount === 0)
  7271. return false;
  7272. }
  7273. return true;
  7274. };
  7275. return BoundingBox;
  7276. })();
  7277. BABYLON.BoundingBox = BoundingBox;
  7278. })(BABYLON || (BABYLON = {}));
  7279. //# sourceMappingURL=babylon.boundingBox.js.map
  7280. var BABYLON;
  7281. (function (BABYLON) {
  7282. var computeBoxExtents = function (axis, box) {
  7283. var p = BABYLON.Vector3.Dot(box.center, axis);
  7284. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7285. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7286. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7287. var r = r0 + r1 + r2;
  7288. return {
  7289. min: p - r,
  7290. max: p + r
  7291. };
  7292. };
  7293. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7294. var axisOverlap = function (axis, box0, box1) {
  7295. var result0 = computeBoxExtents(axis, box0);
  7296. var result1 = computeBoxExtents(axis, box1);
  7297. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7298. };
  7299. var BoundingInfo = (function () {
  7300. function BoundingInfo(minimum, maximum) {
  7301. this.minimum = minimum;
  7302. this.maximum = maximum;
  7303. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7304. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7305. }
  7306. // Methods
  7307. BoundingInfo.prototype._update = function (world) {
  7308. this.boundingBox._update(world);
  7309. this.boundingSphere._update(world);
  7310. };
  7311. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7312. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7313. return false;
  7314. return this.boundingBox.isInFrustum(frustumPlanes);
  7315. };
  7316. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7317. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7318. };
  7319. BoundingInfo.prototype._checkCollision = function (collider) {
  7320. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7321. };
  7322. BoundingInfo.prototype.intersectsPoint = function (point) {
  7323. if (!this.boundingSphere.centerWorld) {
  7324. return false;
  7325. }
  7326. if (!this.boundingSphere.intersectsPoint(point)) {
  7327. return false;
  7328. }
  7329. if (!this.boundingBox.intersectsPoint(point)) {
  7330. return false;
  7331. }
  7332. return true;
  7333. };
  7334. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7335. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7336. return false;
  7337. }
  7338. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7339. return false;
  7340. }
  7341. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7342. return false;
  7343. }
  7344. if (!precise) {
  7345. return true;
  7346. }
  7347. var box0 = this.boundingBox;
  7348. var box1 = boundingInfo.boundingBox;
  7349. if (!axisOverlap(box0.directions[0], box0, box1))
  7350. return false;
  7351. if (!axisOverlap(box0.directions[1], box0, box1))
  7352. return false;
  7353. if (!axisOverlap(box0.directions[2], box0, box1))
  7354. return false;
  7355. if (!axisOverlap(box1.directions[0], box0, box1))
  7356. return false;
  7357. if (!axisOverlap(box1.directions[1], box0, box1))
  7358. return false;
  7359. if (!axisOverlap(box1.directions[2], box0, box1))
  7360. return false;
  7361. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7362. return false;
  7363. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7364. return false;
  7365. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7366. return false;
  7367. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7368. return false;
  7369. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7370. return false;
  7371. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7372. return false;
  7373. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7374. return false;
  7375. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7376. return false;
  7377. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7378. return false;
  7379. return true;
  7380. };
  7381. return BoundingInfo;
  7382. })();
  7383. BABYLON.BoundingInfo = BoundingInfo;
  7384. })(BABYLON || (BABYLON = {}));
  7385. //# sourceMappingURL=babylon.boundingInfo.js.map
  7386. var __extends = this.__extends || function (d, b) {
  7387. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7388. function __() { this.constructor = d; }
  7389. __.prototype = b.prototype;
  7390. d.prototype = new __();
  7391. };
  7392. var BABYLON;
  7393. (function (BABYLON) {
  7394. var AbstractMesh = (function (_super) {
  7395. __extends(AbstractMesh, _super);
  7396. function AbstractMesh(name, scene) {
  7397. var _this = this;
  7398. _super.call(this, name, scene);
  7399. // Properties
  7400. this.definedFacingForward = true; // orientation for POV movement & rotation
  7401. this.position = new BABYLON.Vector3(0, 0, 0);
  7402. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7403. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7404. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7405. this.visibility = 1.0;
  7406. this.alphaIndex = Number.MAX_VALUE;
  7407. this.infiniteDistance = false;
  7408. this.isVisible = true;
  7409. this.isPickable = true;
  7410. this.showBoundingBox = false;
  7411. this.showSubMeshesBoundingBox = false;
  7412. this.onDispose = null;
  7413. this.checkCollisions = false;
  7414. this.isBlocker = false;
  7415. this.renderingGroupId = 0;
  7416. this.receiveShadows = false;
  7417. this.renderOutline = false;
  7418. this.outlineColor = BABYLON.Color3.Red();
  7419. this.outlineWidth = 0.02;
  7420. this.renderOverlay = false;
  7421. this.overlayColor = BABYLON.Color3.Red();
  7422. this.overlayAlpha = 0.5;
  7423. this.hasVertexAlpha = false;
  7424. this.useVertexColors = true;
  7425. this.applyFog = true;
  7426. this.useOctreeForRenderingSelection = true;
  7427. this.useOctreeForPicking = true;
  7428. this.useOctreeForCollisions = true;
  7429. this.layerMask = 0x0FFFFFFF;
  7430. this.alwaysSelectAsActiveMesh = false;
  7431. // Physics
  7432. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7433. // Collisions
  7434. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7435. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7436. this._collider = new BABYLON.Collider();
  7437. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7438. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7439. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7440. // Cache
  7441. this._localScaling = BABYLON.Matrix.Zero();
  7442. this._localRotation = BABYLON.Matrix.Zero();
  7443. this._localTranslation = BABYLON.Matrix.Zero();
  7444. this._localBillboard = BABYLON.Matrix.Zero();
  7445. this._localPivotScaling = BABYLON.Matrix.Zero();
  7446. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7447. this._localWorld = BABYLON.Matrix.Zero();
  7448. this._worldMatrix = BABYLON.Matrix.Zero();
  7449. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7450. this._absolutePosition = BABYLON.Vector3.Zero();
  7451. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7452. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7453. this._isDirty = false;
  7454. this._pivotMatrix = BABYLON.Matrix.Identity();
  7455. this._isDisposed = false;
  7456. this._renderId = 0;
  7457. this._intersectionsInProgress = new Array();
  7458. this._onAfterWorldMatrixUpdate = new Array();
  7459. this._isWorldMatrixFrozen = false;
  7460. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7461. if (collidedMesh === void 0) { collidedMesh = null; }
  7462. //TODO move this to the collision coordinator!
  7463. if (collisionId != null || collisionId != undefined)
  7464. newPosition.multiplyInPlace(_this._collider.radius);
  7465. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7466. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7467. _this.position.addInPlace(_this._diffPositionForCollisions);
  7468. }
  7469. };
  7470. scene.addMesh(this);
  7471. }
  7472. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7473. get: function () {
  7474. return AbstractMesh._BILLBOARDMODE_NONE;
  7475. },
  7476. enumerable: true,
  7477. configurable: true
  7478. });
  7479. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7480. get: function () {
  7481. return AbstractMesh._BILLBOARDMODE_X;
  7482. },
  7483. enumerable: true,
  7484. configurable: true
  7485. });
  7486. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7487. get: function () {
  7488. return AbstractMesh._BILLBOARDMODE_Y;
  7489. },
  7490. enumerable: true,
  7491. configurable: true
  7492. });
  7493. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7494. get: function () {
  7495. return AbstractMesh._BILLBOARDMODE_Z;
  7496. },
  7497. enumerable: true,
  7498. configurable: true
  7499. });
  7500. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7501. get: function () {
  7502. return AbstractMesh._BILLBOARDMODE_ALL;
  7503. },
  7504. enumerable: true,
  7505. configurable: true
  7506. });
  7507. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7508. // Methods
  7509. get: function () {
  7510. return false;
  7511. },
  7512. enumerable: true,
  7513. configurable: true
  7514. });
  7515. AbstractMesh.prototype.getLOD = function (camera) {
  7516. return this;
  7517. };
  7518. AbstractMesh.prototype.getTotalVertices = function () {
  7519. return 0;
  7520. };
  7521. AbstractMesh.prototype.getIndices = function () {
  7522. return null;
  7523. };
  7524. AbstractMesh.prototype.getVerticesData = function (kind) {
  7525. return null;
  7526. };
  7527. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7528. return false;
  7529. };
  7530. AbstractMesh.prototype.getBoundingInfo = function () {
  7531. if (this._masterMesh) {
  7532. return this._masterMesh.getBoundingInfo();
  7533. }
  7534. if (!this._boundingInfo) {
  7535. this._updateBoundingInfo();
  7536. }
  7537. return this._boundingInfo;
  7538. };
  7539. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7540. get: function () {
  7541. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7542. },
  7543. enumerable: true,
  7544. configurable: true
  7545. });
  7546. AbstractMesh.prototype._preActivate = function () {
  7547. };
  7548. AbstractMesh.prototype._activate = function (renderId) {
  7549. this._renderId = renderId;
  7550. };
  7551. AbstractMesh.prototype.getWorldMatrix = function () {
  7552. if (this._masterMesh) {
  7553. return this._masterMesh.getWorldMatrix();
  7554. }
  7555. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7556. this.computeWorldMatrix();
  7557. }
  7558. return this._worldMatrix;
  7559. };
  7560. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7561. get: function () {
  7562. return this._worldMatrix;
  7563. },
  7564. enumerable: true,
  7565. configurable: true
  7566. });
  7567. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7568. get: function () {
  7569. return this._absolutePosition;
  7570. },
  7571. enumerable: true,
  7572. configurable: true
  7573. });
  7574. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7575. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7576. this.computeWorldMatrix(true);
  7577. this._isWorldMatrixFrozen = true;
  7578. };
  7579. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7580. this._isWorldMatrixFrozen = false;
  7581. this.computeWorldMatrix(true);
  7582. };
  7583. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7584. get: function () {
  7585. return this._isWorldMatrixFrozen;
  7586. },
  7587. enumerable: true,
  7588. configurable: true
  7589. });
  7590. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7591. if (!this.rotationQuaternion) {
  7592. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7593. this.rotation = BABYLON.Vector3.Zero();
  7594. }
  7595. if (!space || space === 0 /* LOCAL */) {
  7596. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7597. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7598. }
  7599. else {
  7600. if (this.parent) {
  7601. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7602. invertParentWorldMatrix.invert();
  7603. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7604. }
  7605. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7606. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7607. }
  7608. };
  7609. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7610. var displacementVector = axis.scale(distance);
  7611. if (!space || space === 0 /* LOCAL */) {
  7612. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7613. this.setPositionWithLocalVector(tempV3);
  7614. }
  7615. else {
  7616. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7617. }
  7618. };
  7619. AbstractMesh.prototype.getAbsolutePosition = function () {
  7620. this.computeWorldMatrix();
  7621. return this._absolutePosition;
  7622. };
  7623. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7624. if (!absolutePosition) {
  7625. return;
  7626. }
  7627. var absolutePositionX;
  7628. var absolutePositionY;
  7629. var absolutePositionZ;
  7630. if (absolutePosition.x === undefined) {
  7631. if (arguments.length < 3) {
  7632. return;
  7633. }
  7634. absolutePositionX = arguments[0];
  7635. absolutePositionY = arguments[1];
  7636. absolutePositionZ = arguments[2];
  7637. }
  7638. else {
  7639. absolutePositionX = absolutePosition.x;
  7640. absolutePositionY = absolutePosition.y;
  7641. absolutePositionZ = absolutePosition.z;
  7642. }
  7643. if (this.parent) {
  7644. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7645. invertParentWorldMatrix.invert();
  7646. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7647. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7648. }
  7649. else {
  7650. this.position.x = absolutePositionX;
  7651. this.position.y = absolutePositionY;
  7652. this.position.z = absolutePositionZ;
  7653. }
  7654. };
  7655. // ================================== Point of View Movement =================================
  7656. /**
  7657. * Perform relative position change from the point of view of behind the front of the mesh.
  7658. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7659. * Supports definition of mesh facing forward or backward.
  7660. * @param {number} amountRight
  7661. * @param {number} amountUp
  7662. * @param {number} amountForward
  7663. */
  7664. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7665. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7666. };
  7667. /**
  7668. * Calculate relative position change from the point of view of behind the front of the mesh.
  7669. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7670. * Supports definition of mesh facing forward or backward.
  7671. * @param {number} amountRight
  7672. * @param {number} amountUp
  7673. * @param {number} amountForward
  7674. */
  7675. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7676. var rotMatrix = new BABYLON.Matrix();
  7677. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7678. rotQuaternion.toRotationMatrix(rotMatrix);
  7679. var translationDelta = BABYLON.Vector3.Zero();
  7680. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7681. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7682. return translationDelta;
  7683. };
  7684. // ================================== Point of View Rotation =================================
  7685. /**
  7686. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7687. * Supports definition of mesh facing forward or backward.
  7688. * @param {number} flipBack
  7689. * @param {number} twirlClockwise
  7690. * @param {number} tiltRight
  7691. */
  7692. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7693. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7694. };
  7695. /**
  7696. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7697. * Supports definition of mesh facing forward or backward.
  7698. * @param {number} flipBack
  7699. * @param {number} twirlClockwise
  7700. * @param {number} tiltRight
  7701. */
  7702. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7703. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7704. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7705. };
  7706. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7707. this._pivotMatrix = matrix;
  7708. this._cache.pivotMatrixUpdated = true;
  7709. };
  7710. AbstractMesh.prototype.getPivotMatrix = function () {
  7711. return this._pivotMatrix;
  7712. };
  7713. AbstractMesh.prototype._isSynchronized = function () {
  7714. if (this._isDirty) {
  7715. return false;
  7716. }
  7717. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7718. return false;
  7719. if (this._cache.pivotMatrixUpdated) {
  7720. return false;
  7721. }
  7722. if (this.infiniteDistance) {
  7723. return false;
  7724. }
  7725. if (!this._cache.position.equals(this.position))
  7726. return false;
  7727. if (this.rotationQuaternion) {
  7728. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7729. return false;
  7730. }
  7731. else {
  7732. if (!this._cache.rotation.equals(this.rotation))
  7733. return false;
  7734. }
  7735. if (!this._cache.scaling.equals(this.scaling))
  7736. return false;
  7737. return true;
  7738. };
  7739. AbstractMesh.prototype._initCache = function () {
  7740. _super.prototype._initCache.call(this);
  7741. this._cache.localMatrixUpdated = false;
  7742. this._cache.position = BABYLON.Vector3.Zero();
  7743. this._cache.scaling = BABYLON.Vector3.Zero();
  7744. this._cache.rotation = BABYLON.Vector3.Zero();
  7745. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7746. };
  7747. AbstractMesh.prototype.markAsDirty = function (property) {
  7748. if (property === "rotation") {
  7749. this.rotationQuaternion = null;
  7750. }
  7751. this._currentRenderId = Number.MAX_VALUE;
  7752. this._isDirty = true;
  7753. };
  7754. AbstractMesh.prototype._updateBoundingInfo = function () {
  7755. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7756. this._boundingInfo._update(this.worldMatrixFromCache);
  7757. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7758. };
  7759. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7760. if (!this.subMeshes) {
  7761. return;
  7762. }
  7763. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7764. var subMesh = this.subMeshes[subIndex];
  7765. subMesh.updateBoundingInfo(matrix);
  7766. }
  7767. };
  7768. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7769. if (this._isWorldMatrixFrozen) {
  7770. return this._worldMatrix;
  7771. }
  7772. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7773. return this._worldMatrix;
  7774. }
  7775. this._cache.position.copyFrom(this.position);
  7776. this._cache.scaling.copyFrom(this.scaling);
  7777. this._cache.pivotMatrixUpdated = false;
  7778. this._currentRenderId = this.getScene().getRenderId();
  7779. this._isDirty = false;
  7780. // Scaling
  7781. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7782. // Rotation
  7783. if (this.rotationQuaternion) {
  7784. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7785. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7786. }
  7787. else {
  7788. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7789. this._cache.rotation.copyFrom(this.rotation);
  7790. }
  7791. // Translation
  7792. if (this.infiniteDistance && !this.parent) {
  7793. var camera = this.getScene().activeCamera;
  7794. var cameraWorldMatrix = camera.getWorldMatrix();
  7795. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7796. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7797. }
  7798. else {
  7799. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7800. }
  7801. // Composing transformations
  7802. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7803. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7804. // Billboarding
  7805. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7806. var localPosition = this.position.clone();
  7807. var zero = this.getScene().activeCamera.globalPosition.clone();
  7808. if (this.parent && this.parent.position) {
  7809. localPosition.addInPlace(this.parent.position);
  7810. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7811. }
  7812. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  7813. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7814. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7815. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7816. zero.y = localPosition.y + 0.001;
  7817. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7818. zero.z = localPosition.z + 0.001;
  7819. }
  7820. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7821. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7822. this._localBillboard.invert();
  7823. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7824. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7825. }
  7826. // Local world
  7827. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7828. // Parent
  7829. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7830. this._markSyncedWithParent();
  7831. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7832. }
  7833. else {
  7834. this._worldMatrix.copyFrom(this._localWorld);
  7835. }
  7836. // Bounding info
  7837. this._updateBoundingInfo();
  7838. // Absolute position
  7839. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7840. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7841. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7842. }
  7843. return this._worldMatrix;
  7844. };
  7845. /**
  7846. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7847. * @param func: callback function to add
  7848. */
  7849. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7850. this._onAfterWorldMatrixUpdate.push(func);
  7851. };
  7852. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7853. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  7854. if (index > -1) {
  7855. this._onAfterWorldMatrixUpdate.splice(index, 1);
  7856. }
  7857. };
  7858. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7859. this.computeWorldMatrix();
  7860. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7861. };
  7862. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7863. this.computeWorldMatrix();
  7864. var invLocalWorldMatrix = this._localWorld.clone();
  7865. invLocalWorldMatrix.invert();
  7866. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7867. };
  7868. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7869. this.computeWorldMatrix();
  7870. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7871. };
  7872. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7873. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  7874. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  7875. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  7876. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  7877. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  7878. /// <returns>Mesh oriented towards targetMesh</returns>
  7879. yawCor = yawCor || 0; // default to zero if undefined
  7880. pitchCor = pitchCor || 0;
  7881. rollCor = rollCor || 0;
  7882. var dv = targetPoint.subtract(this.position);
  7883. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7884. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7885. var pitch = Math.atan2(dv.y, len);
  7886. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7887. };
  7888. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7889. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7890. return false;
  7891. }
  7892. return true;
  7893. };
  7894. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  7895. if (!camera) {
  7896. camera = this.getScene().activeCamera;
  7897. }
  7898. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  7899. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  7900. return false;
  7901. }
  7902. return true;
  7903. };
  7904. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7905. if (!this._boundingInfo || !mesh._boundingInfo) {
  7906. return false;
  7907. }
  7908. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7909. };
  7910. AbstractMesh.prototype.intersectsPoint = function (point) {
  7911. if (!this._boundingInfo) {
  7912. return false;
  7913. }
  7914. return this._boundingInfo.intersectsPoint(point);
  7915. };
  7916. // Physics
  7917. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7918. var physicsEngine = this.getScene().getPhysicsEngine();
  7919. if (!physicsEngine) {
  7920. return;
  7921. }
  7922. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7923. if (impostor.impostor) {
  7924. // Old API
  7925. options = impostor;
  7926. impostor = impostor.impostor;
  7927. }
  7928. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7929. physicsEngine._unregisterMesh(this);
  7930. return;
  7931. }
  7932. if (!options) {
  7933. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  7934. }
  7935. else {
  7936. if (!options.mass && options.mass !== 0)
  7937. options.mass = 0;
  7938. if (!options.friction && options.friction !== 0)
  7939. options.friction = 0.2;
  7940. if (!options.restitution && options.restitution !== 0)
  7941. options.restitution = 0.2;
  7942. }
  7943. this._physicImpostor = impostor;
  7944. this._physicsMass = options.mass;
  7945. this._physicsFriction = options.friction;
  7946. this._physicRestitution = options.restitution;
  7947. return physicsEngine._registerMesh(this, impostor, options);
  7948. };
  7949. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7950. if (!this._physicImpostor) {
  7951. return BABYLON.PhysicsEngine.NoImpostor;
  7952. }
  7953. return this._physicImpostor;
  7954. };
  7955. AbstractMesh.prototype.getPhysicsMass = function () {
  7956. if (!this._physicsMass) {
  7957. return 0;
  7958. }
  7959. return this._physicsMass;
  7960. };
  7961. AbstractMesh.prototype.getPhysicsFriction = function () {
  7962. if (!this._physicsFriction) {
  7963. return 0;
  7964. }
  7965. return this._physicsFriction;
  7966. };
  7967. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7968. if (!this._physicRestitution) {
  7969. return 0;
  7970. }
  7971. return this._physicRestitution;
  7972. };
  7973. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  7974. if (!camera) {
  7975. camera = this.getScene().activeCamera;
  7976. }
  7977. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  7978. };
  7979. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  7980. if (!camera) {
  7981. camera = this.getScene().activeCamera;
  7982. }
  7983. return this.absolutePosition.subtract(camera.position).length();
  7984. };
  7985. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  7986. if (!this._physicImpostor) {
  7987. return;
  7988. }
  7989. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  7990. };
  7991. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  7992. if (!this._physicImpostor) {
  7993. return;
  7994. }
  7995. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  7996. };
  7997. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  7998. if (!this._physicImpostor) {
  7999. return;
  8000. }
  8001. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8002. };
  8003. // Collisions
  8004. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8005. var globalPosition = this.getAbsolutePosition();
  8006. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8007. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8008. this._collider.radius = this.ellipsoid;
  8009. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8010. };
  8011. // Submeshes octree
  8012. /**
  8013. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8014. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8015. */
  8016. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8017. if (maxCapacity === void 0) { maxCapacity = 64; }
  8018. if (maxDepth === void 0) { maxDepth = 2; }
  8019. if (!this._submeshesOctree) {
  8020. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8021. }
  8022. this.computeWorldMatrix(true);
  8023. // Update octree
  8024. var bbox = this.getBoundingInfo().boundingBox;
  8025. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8026. return this._submeshesOctree;
  8027. };
  8028. // Collisions
  8029. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8030. this._generatePointsArray();
  8031. // Transformation
  8032. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8033. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8034. subMesh._lastColliderWorldVertices = [];
  8035. subMesh._trianglePlanes = [];
  8036. var start = subMesh.verticesStart;
  8037. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8038. for (var i = start; i < end; i++) {
  8039. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8040. }
  8041. }
  8042. // Collide
  8043. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8044. if (collider.collisionFound) {
  8045. collider.collidedMesh = this;
  8046. }
  8047. };
  8048. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8049. var subMeshes;
  8050. var len;
  8051. // Octrees
  8052. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8053. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8054. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8055. len = intersections.length;
  8056. subMeshes = intersections.data;
  8057. }
  8058. else {
  8059. subMeshes = this.subMeshes;
  8060. len = subMeshes.length;
  8061. }
  8062. for (var index = 0; index < len; index++) {
  8063. var subMesh = subMeshes[index];
  8064. // Bounding test
  8065. if (len > 1 && !subMesh._checkCollision(collider))
  8066. continue;
  8067. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8068. }
  8069. };
  8070. AbstractMesh.prototype._checkCollision = function (collider) {
  8071. // Bounding box test
  8072. if (!this._boundingInfo._checkCollision(collider))
  8073. return;
  8074. // Transformation matrix
  8075. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8076. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8077. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8078. };
  8079. // Picking
  8080. AbstractMesh.prototype._generatePointsArray = function () {
  8081. return false;
  8082. };
  8083. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8084. var pickingInfo = new BABYLON.PickingInfo();
  8085. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8086. return pickingInfo;
  8087. }
  8088. if (!this._generatePointsArray()) {
  8089. return pickingInfo;
  8090. }
  8091. var intersectInfo = null;
  8092. // Octrees
  8093. var subMeshes;
  8094. var len;
  8095. if (this._submeshesOctree && this.useOctreeForPicking) {
  8096. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8097. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8098. len = intersections.length;
  8099. subMeshes = intersections.data;
  8100. }
  8101. else {
  8102. subMeshes = this.subMeshes;
  8103. len = subMeshes.length;
  8104. }
  8105. for (var index = 0; index < len; index++) {
  8106. var subMesh = subMeshes[index];
  8107. // Bounding test
  8108. if (len > 1 && !subMesh.canIntersects(ray))
  8109. continue;
  8110. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8111. if (currentIntersectInfo) {
  8112. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8113. intersectInfo = currentIntersectInfo;
  8114. intersectInfo.subMeshId = index;
  8115. if (fastCheck) {
  8116. break;
  8117. }
  8118. }
  8119. }
  8120. }
  8121. if (intersectInfo) {
  8122. // Get picked point
  8123. var world = this.getWorldMatrix();
  8124. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8125. var direction = ray.direction.clone();
  8126. direction = direction.scale(intersectInfo.distance);
  8127. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8128. var pickedPoint = worldOrigin.add(worldDirection);
  8129. // Return result
  8130. pickingInfo.hit = true;
  8131. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8132. pickingInfo.pickedPoint = pickedPoint;
  8133. pickingInfo.pickedMesh = this;
  8134. pickingInfo.bu = intersectInfo.bu;
  8135. pickingInfo.bv = intersectInfo.bv;
  8136. pickingInfo.faceId = intersectInfo.faceId;
  8137. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8138. return pickingInfo;
  8139. }
  8140. return pickingInfo;
  8141. };
  8142. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8143. return null;
  8144. };
  8145. AbstractMesh.prototype.releaseSubMeshes = function () {
  8146. if (this.subMeshes) {
  8147. while (this.subMeshes.length) {
  8148. this.subMeshes[0].dispose();
  8149. }
  8150. }
  8151. else {
  8152. this.subMeshes = new Array();
  8153. }
  8154. };
  8155. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8156. var index;
  8157. // Physics
  8158. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8159. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8160. }
  8161. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8162. var other = this._intersectionsInProgress[index];
  8163. var pos = other._intersectionsInProgress.indexOf(this);
  8164. other._intersectionsInProgress.splice(pos, 1);
  8165. }
  8166. this._intersectionsInProgress = [];
  8167. // SubMeshes
  8168. this.releaseSubMeshes();
  8169. // Remove from scene
  8170. this.getScene().removeMesh(this);
  8171. if (!doNotRecurse) {
  8172. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8173. if (this.getScene().particleSystems[index].emitter === this) {
  8174. this.getScene().particleSystems[index].dispose();
  8175. index--;
  8176. }
  8177. }
  8178. // Children
  8179. var objects = this.getScene().meshes.slice(0);
  8180. for (index = 0; index < objects.length; index++) {
  8181. if (objects[index].parent === this) {
  8182. objects[index].dispose();
  8183. }
  8184. }
  8185. }
  8186. else {
  8187. for (index = 0; index < this.getScene().meshes.length; index++) {
  8188. var obj = this.getScene().meshes[index];
  8189. if (obj.parent === this) {
  8190. obj.parent = null;
  8191. obj.computeWorldMatrix(true);
  8192. }
  8193. }
  8194. }
  8195. this._onAfterWorldMatrixUpdate = [];
  8196. this._isDisposed = true;
  8197. // Callback
  8198. if (this.onDispose) {
  8199. this.onDispose();
  8200. }
  8201. };
  8202. // Statics
  8203. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8204. AbstractMesh._BILLBOARDMODE_X = 1;
  8205. AbstractMesh._BILLBOARDMODE_Y = 2;
  8206. AbstractMesh._BILLBOARDMODE_Z = 4;
  8207. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8208. return AbstractMesh;
  8209. })(BABYLON.Node);
  8210. BABYLON.AbstractMesh = AbstractMesh;
  8211. })(BABYLON || (BABYLON = {}));
  8212. //# sourceMappingURL=babylon.abstractMesh.js.map
  8213. var __extends = this.__extends || function (d, b) {
  8214. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8215. function __() { this.constructor = d; }
  8216. __.prototype = b.prototype;
  8217. d.prototype = new __();
  8218. };
  8219. var BABYLON;
  8220. (function (BABYLON) {
  8221. var Light = (function (_super) {
  8222. __extends(Light, _super);
  8223. function Light(name, scene) {
  8224. _super.call(this, name, scene);
  8225. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8226. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8227. this.intensity = 1.0;
  8228. this.range = Number.MAX_VALUE;
  8229. this.includeOnlyWithLayerMask = 0;
  8230. this.includedOnlyMeshes = new Array();
  8231. this.excludedMeshes = new Array();
  8232. this.excludeWithLayerMask = 0;
  8233. this._excludedMeshesIds = new Array();
  8234. this._includedOnlyMeshesIds = new Array();
  8235. scene.addLight(this);
  8236. }
  8237. Light.prototype.getShadowGenerator = function () {
  8238. return this._shadowGenerator;
  8239. };
  8240. Light.prototype.getAbsolutePosition = function () {
  8241. return BABYLON.Vector3.Zero();
  8242. };
  8243. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8244. };
  8245. Light.prototype._getWorldMatrix = function () {
  8246. return BABYLON.Matrix.Identity();
  8247. };
  8248. Light.prototype.canAffectMesh = function (mesh) {
  8249. if (!mesh) {
  8250. return true;
  8251. }
  8252. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8253. return false;
  8254. }
  8255. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8256. return false;
  8257. }
  8258. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8259. return false;
  8260. }
  8261. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8262. return false;
  8263. }
  8264. return true;
  8265. };
  8266. Light.prototype.getWorldMatrix = function () {
  8267. this._currentRenderId = this.getScene().getRenderId();
  8268. var worldMatrix = this._getWorldMatrix();
  8269. if (this.parent && this.parent.getWorldMatrix) {
  8270. if (!this._parentedWorldMatrix) {
  8271. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8272. }
  8273. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8274. this._markSyncedWithParent();
  8275. return this._parentedWorldMatrix;
  8276. }
  8277. return worldMatrix;
  8278. };
  8279. Light.prototype.dispose = function () {
  8280. if (this._shadowGenerator) {
  8281. this._shadowGenerator.dispose();
  8282. this._shadowGenerator = null;
  8283. }
  8284. // Remove from scene
  8285. this.getScene().removeLight(this);
  8286. };
  8287. return Light;
  8288. })(BABYLON.Node);
  8289. BABYLON.Light = Light;
  8290. })(BABYLON || (BABYLON = {}));
  8291. //# sourceMappingURL=babylon.light.js.map
  8292. var __extends = this.__extends || function (d, b) {
  8293. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8294. function __() { this.constructor = d; }
  8295. __.prototype = b.prototype;
  8296. d.prototype = new __();
  8297. };
  8298. var BABYLON;
  8299. (function (BABYLON) {
  8300. var PointLight = (function (_super) {
  8301. __extends(PointLight, _super);
  8302. function PointLight(name, position, scene) {
  8303. _super.call(this, name, scene);
  8304. this.position = position;
  8305. }
  8306. PointLight.prototype.getAbsolutePosition = function () {
  8307. return this._transformedPosition ? this._transformedPosition : this.position;
  8308. };
  8309. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8310. if (this.parent && this.parent.getWorldMatrix) {
  8311. if (!this._transformedPosition) {
  8312. this._transformedPosition = BABYLON.Vector3.Zero();
  8313. }
  8314. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8315. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8316. return;
  8317. }
  8318. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8319. };
  8320. PointLight.prototype.getShadowGenerator = function () {
  8321. return null;
  8322. };
  8323. PointLight.prototype._getWorldMatrix = function () {
  8324. if (!this._worldMatrix) {
  8325. this._worldMatrix = BABYLON.Matrix.Identity();
  8326. }
  8327. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8328. return this._worldMatrix;
  8329. };
  8330. return PointLight;
  8331. })(BABYLON.Light);
  8332. BABYLON.PointLight = PointLight;
  8333. })(BABYLON || (BABYLON = {}));
  8334. //# sourceMappingURL=babylon.pointLight.js.map
  8335. var __extends = this.__extends || function (d, b) {
  8336. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8337. function __() { this.constructor = d; }
  8338. __.prototype = b.prototype;
  8339. d.prototype = new __();
  8340. };
  8341. var BABYLON;
  8342. (function (BABYLON) {
  8343. var SpotLight = (function (_super) {
  8344. __extends(SpotLight, _super);
  8345. function SpotLight(name, position, direction, angle, exponent, scene) {
  8346. _super.call(this, name, scene);
  8347. this.position = position;
  8348. this.direction = direction;
  8349. this.angle = angle;
  8350. this.exponent = exponent;
  8351. }
  8352. SpotLight.prototype.getAbsolutePosition = function () {
  8353. return this.transformedPosition ? this.transformedPosition : this.position;
  8354. };
  8355. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8356. var activeCamera = this.getScene().activeCamera;
  8357. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8358. };
  8359. SpotLight.prototype.supportsVSM = function () {
  8360. return true;
  8361. };
  8362. SpotLight.prototype.needRefreshPerFrame = function () {
  8363. return false;
  8364. };
  8365. SpotLight.prototype.setDirectionToTarget = function (target) {
  8366. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8367. return this.direction;
  8368. };
  8369. SpotLight.prototype.computeTransformedPosition = function () {
  8370. if (this.parent && this.parent.getWorldMatrix) {
  8371. if (!this.transformedPosition) {
  8372. this.transformedPosition = BABYLON.Vector3.Zero();
  8373. }
  8374. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8375. return true;
  8376. }
  8377. return false;
  8378. };
  8379. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8380. var normalizeDirection;
  8381. if (this.parent && this.parent.getWorldMatrix) {
  8382. if (!this._transformedDirection) {
  8383. this._transformedDirection = BABYLON.Vector3.Zero();
  8384. }
  8385. this.computeTransformedPosition();
  8386. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8387. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8388. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8389. }
  8390. else {
  8391. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8392. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8393. }
  8394. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8395. };
  8396. SpotLight.prototype._getWorldMatrix = function () {
  8397. if (!this._worldMatrix) {
  8398. this._worldMatrix = BABYLON.Matrix.Identity();
  8399. }
  8400. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8401. return this._worldMatrix;
  8402. };
  8403. return SpotLight;
  8404. })(BABYLON.Light);
  8405. BABYLON.SpotLight = SpotLight;
  8406. })(BABYLON || (BABYLON = {}));
  8407. //# sourceMappingURL=babylon.spotLight.js.map
  8408. var __extends = this.__extends || function (d, b) {
  8409. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8410. function __() { this.constructor = d; }
  8411. __.prototype = b.prototype;
  8412. d.prototype = new __();
  8413. };
  8414. var BABYLON;
  8415. (function (BABYLON) {
  8416. var HemisphericLight = (function (_super) {
  8417. __extends(HemisphericLight, _super);
  8418. function HemisphericLight(name, direction, scene) {
  8419. _super.call(this, name, scene);
  8420. this.direction = direction;
  8421. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8422. }
  8423. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8424. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8425. return this.direction;
  8426. };
  8427. HemisphericLight.prototype.getShadowGenerator = function () {
  8428. return null;
  8429. };
  8430. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8431. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8432. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8433. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8434. };
  8435. HemisphericLight.prototype._getWorldMatrix = function () {
  8436. if (!this._worldMatrix) {
  8437. this._worldMatrix = BABYLON.Matrix.Identity();
  8438. }
  8439. return this._worldMatrix;
  8440. };
  8441. return HemisphericLight;
  8442. })(BABYLON.Light);
  8443. BABYLON.HemisphericLight = HemisphericLight;
  8444. })(BABYLON || (BABYLON = {}));
  8445. //# sourceMappingURL=babylon.hemisphericLight.js.map
  8446. var __extends = this.__extends || function (d, b) {
  8447. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8448. function __() { this.constructor = d; }
  8449. __.prototype = b.prototype;
  8450. d.prototype = new __();
  8451. };
  8452. var BABYLON;
  8453. (function (BABYLON) {
  8454. var DirectionalLight = (function (_super) {
  8455. __extends(DirectionalLight, _super);
  8456. function DirectionalLight(name, direction, scene) {
  8457. _super.call(this, name, scene);
  8458. this.direction = direction;
  8459. this.shadowOrthoScale = 0.5;
  8460. this.position = direction.scale(-1);
  8461. }
  8462. DirectionalLight.prototype.getAbsolutePosition = function () {
  8463. return this.transformedPosition ? this.transformedPosition : this.position;
  8464. };
  8465. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8466. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8467. return this.direction;
  8468. };
  8469. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8470. var orthoLeft = Number.MAX_VALUE;
  8471. var orthoRight = Number.MIN_VALUE;
  8472. var orthoTop = Number.MIN_VALUE;
  8473. var orthoBottom = Number.MAX_VALUE;
  8474. var tempVector3 = BABYLON.Vector3.Zero();
  8475. var activeCamera = this.getScene().activeCamera;
  8476. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8477. var mesh = renderList[meshIndex];
  8478. if (!mesh) {
  8479. continue;
  8480. }
  8481. var boundingInfo = mesh.getBoundingInfo();
  8482. if (!boundingInfo) {
  8483. continue;
  8484. }
  8485. var boundingBox = boundingInfo.boundingBox;
  8486. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8487. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8488. if (tempVector3.x < orthoLeft)
  8489. orthoLeft = tempVector3.x;
  8490. if (tempVector3.y < orthoBottom)
  8491. orthoBottom = tempVector3.y;
  8492. if (tempVector3.x > orthoRight)
  8493. orthoRight = tempVector3.x;
  8494. if (tempVector3.y > orthoTop)
  8495. orthoTop = tempVector3.y;
  8496. }
  8497. }
  8498. var xOffset = orthoRight - orthoLeft;
  8499. var yOffset = orthoTop - orthoBottom;
  8500. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8501. };
  8502. DirectionalLight.prototype.supportsVSM = function () {
  8503. return true;
  8504. };
  8505. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8506. return true;
  8507. };
  8508. DirectionalLight.prototype.computeTransformedPosition = function () {
  8509. if (this.parent && this.parent.getWorldMatrix) {
  8510. if (!this.transformedPosition) {
  8511. this.transformedPosition = BABYLON.Vector3.Zero();
  8512. }
  8513. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8514. return true;
  8515. }
  8516. return false;
  8517. };
  8518. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8519. if (this.parent && this.parent.getWorldMatrix) {
  8520. if (!this._transformedDirection) {
  8521. this._transformedDirection = BABYLON.Vector3.Zero();
  8522. }
  8523. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8524. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8525. return;
  8526. }
  8527. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8528. };
  8529. DirectionalLight.prototype._getWorldMatrix = function () {
  8530. if (!this._worldMatrix) {
  8531. this._worldMatrix = BABYLON.Matrix.Identity();
  8532. }
  8533. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8534. return this._worldMatrix;
  8535. };
  8536. return DirectionalLight;
  8537. })(BABYLON.Light);
  8538. BABYLON.DirectionalLight = DirectionalLight;
  8539. })(BABYLON || (BABYLON = {}));
  8540. //# sourceMappingURL=babylon.directionalLight.js.map
  8541. var BABYLON;
  8542. (function (BABYLON) {
  8543. var ShadowGenerator = (function () {
  8544. function ShadowGenerator(mapSize, light) {
  8545. var _this = this;
  8546. // Members
  8547. this._filter = ShadowGenerator.FILTER_NONE;
  8548. this.blurScale = 2;
  8549. this._blurBoxOffset = 0;
  8550. this._bias = 0.00005;
  8551. this._darkness = 0;
  8552. this._transparencyShadow = false;
  8553. this._viewMatrix = BABYLON.Matrix.Zero();
  8554. this._projectionMatrix = BABYLON.Matrix.Zero();
  8555. this._transformMatrix = BABYLON.Matrix.Zero();
  8556. this._worldViewProjection = BABYLON.Matrix.Zero();
  8557. this._light = light;
  8558. this._scene = light.getScene();
  8559. this._mapSize = mapSize;
  8560. light._shadowGenerator = this;
  8561. // Render target
  8562. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8563. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8564. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8565. this._shadowMap.anisotropicFilteringLevel = 1;
  8566. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8567. this._shadowMap.renderParticles = false;
  8568. this._shadowMap.onAfterUnbind = function () {
  8569. if (!_this.useBlurVarianceShadowMap) {
  8570. return;
  8571. }
  8572. if (!_this._shadowMap2) {
  8573. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8574. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8575. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8576. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8577. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8578. _this._downSamplePostprocess.onApply = function (effect) {
  8579. effect.setTexture("textureSampler", _this._shadowMap);
  8580. };
  8581. _this.blurBoxOffset = 1;
  8582. }
  8583. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8584. };
  8585. // Custom render function
  8586. var renderSubMesh = function (subMesh) {
  8587. var mesh = subMesh.getRenderingMesh();
  8588. var scene = _this._scene;
  8589. var engine = scene.getEngine();
  8590. // Culling
  8591. engine.setState(subMesh.getMaterial().backFaceCulling);
  8592. // Managing instances
  8593. var batch = mesh._getInstancesRenderList(subMesh._id);
  8594. if (batch.mustReturn) {
  8595. return;
  8596. }
  8597. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8598. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8599. engine.enableEffect(_this._effect);
  8600. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8601. var material = subMesh.getMaterial();
  8602. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8603. // Alpha test
  8604. if (material && material.needAlphaTesting()) {
  8605. var alphaTexture = material.getAlphaTestTexture();
  8606. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8607. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8608. }
  8609. // Bones
  8610. if (mesh.useBones) {
  8611. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8612. }
  8613. // Draw
  8614. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8615. }
  8616. else {
  8617. // Need to reset refresh rate of the shadowMap
  8618. _this._shadowMap.resetRefreshCounter();
  8619. }
  8620. };
  8621. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8622. var index;
  8623. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8624. renderSubMesh(opaqueSubMeshes.data[index]);
  8625. }
  8626. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8627. renderSubMesh(alphaTestSubMeshes.data[index]);
  8628. }
  8629. if (_this._transparencyShadow) {
  8630. for (index = 0; index < transparentSubMeshes.length; index++) {
  8631. renderSubMesh(transparentSubMeshes.data[index]);
  8632. }
  8633. }
  8634. };
  8635. this._shadowMap.onClear = function (engine) {
  8636. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8637. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8638. }
  8639. else {
  8640. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8641. }
  8642. };
  8643. }
  8644. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8645. // Static
  8646. get: function () {
  8647. return ShadowGenerator._FILTER_NONE;
  8648. },
  8649. enumerable: true,
  8650. configurable: true
  8651. });
  8652. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8653. get: function () {
  8654. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8655. },
  8656. enumerable: true,
  8657. configurable: true
  8658. });
  8659. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8660. get: function () {
  8661. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8662. },
  8663. enumerable: true,
  8664. configurable: true
  8665. });
  8666. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8667. get: function () {
  8668. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8669. },
  8670. enumerable: true,
  8671. configurable: true
  8672. });
  8673. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8674. get: function () {
  8675. return this._bias;
  8676. },
  8677. set: function (bias) {
  8678. this._bias = bias;
  8679. },
  8680. enumerable: true,
  8681. configurable: true
  8682. });
  8683. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8684. get: function () {
  8685. return this._blurBoxOffset;
  8686. },
  8687. set: function (value) {
  8688. var _this = this;
  8689. if (this._blurBoxOffset === value) {
  8690. return;
  8691. }
  8692. this._blurBoxOffset = value;
  8693. if (this._boxBlurPostprocess) {
  8694. this._boxBlurPostprocess.dispose();
  8695. }
  8696. 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);
  8697. this._boxBlurPostprocess.onApply = function (effect) {
  8698. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8699. };
  8700. },
  8701. enumerable: true,
  8702. configurable: true
  8703. });
  8704. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8705. get: function () {
  8706. return this._filter;
  8707. },
  8708. set: function (value) {
  8709. if (this._filter === value) {
  8710. return;
  8711. }
  8712. this._filter = value;
  8713. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8714. this._shadowMap.anisotropicFilteringLevel = 16;
  8715. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8716. }
  8717. else {
  8718. this._shadowMap.anisotropicFilteringLevel = 1;
  8719. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8720. }
  8721. },
  8722. enumerable: true,
  8723. configurable: true
  8724. });
  8725. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8726. get: function () {
  8727. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8728. },
  8729. set: function (value) {
  8730. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8731. },
  8732. enumerable: true,
  8733. configurable: true
  8734. });
  8735. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8736. get: function () {
  8737. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8738. },
  8739. set: function (value) {
  8740. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8741. },
  8742. enumerable: true,
  8743. configurable: true
  8744. });
  8745. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8746. get: function () {
  8747. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8748. },
  8749. set: function (value) {
  8750. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8751. },
  8752. enumerable: true,
  8753. configurable: true
  8754. });
  8755. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8756. var defines = [];
  8757. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8758. defines.push("#define VSM");
  8759. }
  8760. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8761. var mesh = subMesh.getMesh();
  8762. var material = subMesh.getMaterial();
  8763. // Alpha test
  8764. if (material && material.needAlphaTesting()) {
  8765. defines.push("#define ALPHATEST");
  8766. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8767. attribs.push(BABYLON.VertexBuffer.UVKind);
  8768. defines.push("#define UV1");
  8769. }
  8770. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8771. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8772. defines.push("#define UV2");
  8773. }
  8774. }
  8775. // Bones
  8776. if (mesh.useBones) {
  8777. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8778. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8779. defines.push("#define BONES");
  8780. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8781. }
  8782. // Instances
  8783. if (useInstances) {
  8784. defines.push("#define INSTANCES");
  8785. attribs.push("world0");
  8786. attribs.push("world1");
  8787. attribs.push("world2");
  8788. attribs.push("world3");
  8789. }
  8790. // Get correct effect
  8791. var join = defines.join("\n");
  8792. if (this._cachedDefines !== join) {
  8793. this._cachedDefines = join;
  8794. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8795. }
  8796. return this._effect.isReady();
  8797. };
  8798. ShadowGenerator.prototype.getShadowMap = function () {
  8799. return this._shadowMap;
  8800. };
  8801. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8802. if (this._shadowMap2) {
  8803. return this._shadowMap2;
  8804. }
  8805. return this._shadowMap;
  8806. };
  8807. ShadowGenerator.prototype.getLight = function () {
  8808. return this._light;
  8809. };
  8810. // Methods
  8811. ShadowGenerator.prototype.getTransformMatrix = function () {
  8812. var scene = this._scene;
  8813. if (this._currentRenderID === scene.getRenderId()) {
  8814. return this._transformMatrix;
  8815. }
  8816. this._currentRenderID = scene.getRenderId();
  8817. var lightPosition = this._light.position;
  8818. var lightDirection = this._light.direction;
  8819. if (this._light.computeTransformedPosition()) {
  8820. lightPosition = this._light.transformedPosition;
  8821. }
  8822. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  8823. this._cachedPosition = lightPosition.clone();
  8824. this._cachedDirection = lightDirection.clone();
  8825. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8826. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8827. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8828. }
  8829. return this._transformMatrix;
  8830. };
  8831. ShadowGenerator.prototype.getDarkness = function () {
  8832. return this._darkness;
  8833. };
  8834. ShadowGenerator.prototype.setDarkness = function (darkness) {
  8835. if (darkness >= 1.0)
  8836. this._darkness = 1.0;
  8837. else if (darkness <= 0.0)
  8838. this._darkness = 0.0;
  8839. else
  8840. this._darkness = darkness;
  8841. };
  8842. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  8843. this._transparencyShadow = hasShadow;
  8844. };
  8845. ShadowGenerator.prototype._packHalf = function (depth) {
  8846. var scale = depth * 255.0;
  8847. var fract = scale - Math.floor(scale);
  8848. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  8849. };
  8850. ShadowGenerator.prototype.dispose = function () {
  8851. this._shadowMap.dispose();
  8852. if (this._shadowMap2) {
  8853. this._shadowMap2.dispose();
  8854. }
  8855. if (this._downSamplePostprocess) {
  8856. this._downSamplePostprocess.dispose();
  8857. }
  8858. if (this._boxBlurPostprocess) {
  8859. this._boxBlurPostprocess.dispose();
  8860. }
  8861. };
  8862. ShadowGenerator._FILTER_NONE = 0;
  8863. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  8864. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  8865. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  8866. return ShadowGenerator;
  8867. })();
  8868. BABYLON.ShadowGenerator = ShadowGenerator;
  8869. })(BABYLON || (BABYLON = {}));
  8870. //# sourceMappingURL=babylon.shadowGenerator.js.map
  8871. var BABYLON;
  8872. (function (BABYLON) {
  8873. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  8874. if (boxMin.x > sphereCenter.x + sphereRadius)
  8875. return false;
  8876. if (sphereCenter.x - sphereRadius > boxMax.x)
  8877. return false;
  8878. if (boxMin.y > sphereCenter.y + sphereRadius)
  8879. return false;
  8880. if (sphereCenter.y - sphereRadius > boxMax.y)
  8881. return false;
  8882. if (boxMin.z > sphereCenter.z + sphereRadius)
  8883. return false;
  8884. if (sphereCenter.z - sphereRadius > boxMax.z)
  8885. return false;
  8886. return true;
  8887. };
  8888. var getLowestRoot = function (a, b, c, maxR) {
  8889. var determinant = b * b - 4.0 * a * c;
  8890. var result = { root: 0, found: false };
  8891. if (determinant < 0)
  8892. return result;
  8893. var sqrtD = Math.sqrt(determinant);
  8894. var r1 = (-b - sqrtD) / (2.0 * a);
  8895. var r2 = (-b + sqrtD) / (2.0 * a);
  8896. if (r1 > r2) {
  8897. var temp = r2;
  8898. r2 = r1;
  8899. r1 = temp;
  8900. }
  8901. if (r1 > 0 && r1 < maxR) {
  8902. result.root = r1;
  8903. result.found = true;
  8904. return result;
  8905. }
  8906. if (r2 > 0 && r2 < maxR) {
  8907. result.root = r2;
  8908. result.found = true;
  8909. return result;
  8910. }
  8911. return result;
  8912. };
  8913. var Collider = (function () {
  8914. function Collider() {
  8915. this.radius = new BABYLON.Vector3(1, 1, 1);
  8916. this.retry = 0;
  8917. this.basePointWorld = BABYLON.Vector3.Zero();
  8918. this.velocityWorld = BABYLON.Vector3.Zero();
  8919. this.normalizedVelocity = BABYLON.Vector3.Zero();
  8920. this._collisionPoint = BABYLON.Vector3.Zero();
  8921. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  8922. this._tempVector = BABYLON.Vector3.Zero();
  8923. this._tempVector2 = BABYLON.Vector3.Zero();
  8924. this._tempVector3 = BABYLON.Vector3.Zero();
  8925. this._tempVector4 = BABYLON.Vector3.Zero();
  8926. this._edge = BABYLON.Vector3.Zero();
  8927. this._baseToVertex = BABYLON.Vector3.Zero();
  8928. this._destinationPoint = BABYLON.Vector3.Zero();
  8929. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  8930. this._displacementVector = BABYLON.Vector3.Zero();
  8931. }
  8932. // Methods
  8933. Collider.prototype._initialize = function (source, dir, e) {
  8934. this.velocity = dir;
  8935. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  8936. this.basePoint = source;
  8937. source.multiplyToRef(this.radius, this.basePointWorld);
  8938. dir.multiplyToRef(this.radius, this.velocityWorld);
  8939. this.velocityWorldLength = this.velocityWorld.length();
  8940. this.epsilon = e;
  8941. this.collisionFound = false;
  8942. };
  8943. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  8944. pa.subtractToRef(point, this._tempVector);
  8945. pb.subtractToRef(point, this._tempVector2);
  8946. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  8947. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8948. if (d < 0)
  8949. return false;
  8950. pc.subtractToRef(point, this._tempVector3);
  8951. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  8952. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8953. if (d < 0)
  8954. return false;
  8955. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  8956. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8957. return d >= 0;
  8958. };
  8959. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  8960. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  8961. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  8962. if (distance > this.velocityWorldLength + max + sphereRadius) {
  8963. return false;
  8964. }
  8965. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  8966. return false;
  8967. return true;
  8968. };
  8969. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  8970. var t0;
  8971. var embeddedInPlane = false;
  8972. //defensive programming, actually not needed.
  8973. if (!trianglePlaneArray) {
  8974. trianglePlaneArray = [];
  8975. }
  8976. if (!trianglePlaneArray[faceIndex]) {
  8977. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  8978. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  8979. }
  8980. var trianglePlane = trianglePlaneArray[faceIndex];
  8981. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  8982. return;
  8983. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  8984. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  8985. if (normalDotVelocity == 0) {
  8986. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  8987. return;
  8988. embeddedInPlane = true;
  8989. t0 = 0;
  8990. }
  8991. else {
  8992. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  8993. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  8994. if (t0 > t1) {
  8995. var temp = t1;
  8996. t1 = t0;
  8997. t0 = temp;
  8998. }
  8999. if (t0 > 1.0 || t1 < 0.0)
  9000. return;
  9001. if (t0 < 0)
  9002. t0 = 0;
  9003. if (t0 > 1.0)
  9004. t0 = 1.0;
  9005. }
  9006. this._collisionPoint.copyFromFloats(0, 0, 0);
  9007. var found = false;
  9008. var t = 1.0;
  9009. if (!embeddedInPlane) {
  9010. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9011. this.velocity.scaleToRef(t0, this._tempVector);
  9012. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9013. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9014. found = true;
  9015. t = t0;
  9016. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9017. }
  9018. }
  9019. if (!found) {
  9020. var velocitySquaredLength = this.velocity.lengthSquared();
  9021. var a = velocitySquaredLength;
  9022. this.basePoint.subtractToRef(p1, this._tempVector);
  9023. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9024. var c = this._tempVector.lengthSquared() - 1.0;
  9025. var lowestRoot = getLowestRoot(a, b, c, t);
  9026. if (lowestRoot.found) {
  9027. t = lowestRoot.root;
  9028. found = true;
  9029. this._collisionPoint.copyFrom(p1);
  9030. }
  9031. this.basePoint.subtractToRef(p2, this._tempVector);
  9032. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9033. c = this._tempVector.lengthSquared() - 1.0;
  9034. lowestRoot = getLowestRoot(a, b, c, t);
  9035. if (lowestRoot.found) {
  9036. t = lowestRoot.root;
  9037. found = true;
  9038. this._collisionPoint.copyFrom(p2);
  9039. }
  9040. this.basePoint.subtractToRef(p3, this._tempVector);
  9041. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9042. c = this._tempVector.lengthSquared() - 1.0;
  9043. lowestRoot = getLowestRoot(a, b, c, t);
  9044. if (lowestRoot.found) {
  9045. t = lowestRoot.root;
  9046. found = true;
  9047. this._collisionPoint.copyFrom(p3);
  9048. }
  9049. p2.subtractToRef(p1, this._edge);
  9050. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9051. var edgeSquaredLength = this._edge.lengthSquared();
  9052. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9053. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9054. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9055. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9056. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9057. lowestRoot = getLowestRoot(a, b, c, t);
  9058. if (lowestRoot.found) {
  9059. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9060. if (f >= 0.0 && f <= 1.0) {
  9061. t = lowestRoot.root;
  9062. found = true;
  9063. this._edge.scaleInPlace(f);
  9064. p1.addToRef(this._edge, this._collisionPoint);
  9065. }
  9066. }
  9067. p3.subtractToRef(p2, this._edge);
  9068. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9069. edgeSquaredLength = this._edge.lengthSquared();
  9070. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9071. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9072. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9073. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9074. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9075. lowestRoot = getLowestRoot(a, b, c, t);
  9076. if (lowestRoot.found) {
  9077. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9078. if (f >= 0.0 && f <= 1.0) {
  9079. t = lowestRoot.root;
  9080. found = true;
  9081. this._edge.scaleInPlace(f);
  9082. p2.addToRef(this._edge, this._collisionPoint);
  9083. }
  9084. }
  9085. p1.subtractToRef(p3, this._edge);
  9086. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9087. edgeSquaredLength = this._edge.lengthSquared();
  9088. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9089. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9090. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9091. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9092. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9093. lowestRoot = getLowestRoot(a, b, c, t);
  9094. if (lowestRoot.found) {
  9095. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9096. if (f >= 0.0 && f <= 1.0) {
  9097. t = lowestRoot.root;
  9098. found = true;
  9099. this._edge.scaleInPlace(f);
  9100. p3.addToRef(this._edge, this._collisionPoint);
  9101. }
  9102. }
  9103. }
  9104. if (found) {
  9105. var distToCollision = t * this.velocity.length();
  9106. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9107. if (!this.intersectionPoint) {
  9108. this.intersectionPoint = this._collisionPoint.clone();
  9109. }
  9110. else {
  9111. this.intersectionPoint.copyFrom(this._collisionPoint);
  9112. }
  9113. this.nearestDistance = distToCollision;
  9114. this.collisionFound = true;
  9115. }
  9116. }
  9117. };
  9118. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9119. for (var i = indexStart; i < indexEnd; i += 3) {
  9120. var p1 = pts[indices[i] - decal];
  9121. var p2 = pts[indices[i + 1] - decal];
  9122. var p3 = pts[indices[i + 2] - decal];
  9123. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9124. }
  9125. };
  9126. Collider.prototype._getResponse = function (pos, vel) {
  9127. pos.addToRef(vel, this._destinationPoint);
  9128. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9129. this.basePoint.addToRef(vel, pos);
  9130. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9131. this._slidePlaneNormal.normalize();
  9132. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9133. pos.addInPlace(this._displacementVector);
  9134. this.intersectionPoint.addInPlace(this._displacementVector);
  9135. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9136. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9137. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9138. };
  9139. return Collider;
  9140. })();
  9141. BABYLON.Collider = Collider;
  9142. })(BABYLON || (BABYLON = {}));
  9143. //# sourceMappingURL=babylon.collider.js.map
  9144. var BABYLON;
  9145. (function (BABYLON) {
  9146. //WebWorker code will be inserted to this variable.
  9147. BABYLON.CollisionWorker = "";
  9148. (function (WorkerTaskType) {
  9149. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9150. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9151. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9152. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9153. var WorkerTaskType = BABYLON.WorkerTaskType;
  9154. (function (WorkerReplyType) {
  9155. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9156. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9157. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9158. var WorkerReplyType = BABYLON.WorkerReplyType;
  9159. var CollisionCoordinatorWorker = (function () {
  9160. function CollisionCoordinatorWorker() {
  9161. var _this = this;
  9162. this._scaledPosition = BABYLON.Vector3.Zero();
  9163. this._scaledVelocity = BABYLON.Vector3.Zero();
  9164. this.onMeshUpdated = function (mesh) {
  9165. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9166. };
  9167. this.onGeometryUpdated = function (geometry) {
  9168. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9169. };
  9170. this._afterRender = function () {
  9171. if (!_this._init)
  9172. return;
  9173. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9174. return;
  9175. }
  9176. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9177. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9178. if (_this._runningUpdated > 4) {
  9179. return;
  9180. }
  9181. ++_this._runningUpdated;
  9182. var payload = {
  9183. updatedMeshes: _this._addUpdateMeshesList,
  9184. updatedGeometries: _this._addUpdateGeometriesList,
  9185. removedGeometries: _this._toRemoveGeometryArray,
  9186. removedMeshes: _this._toRemoveMeshesArray
  9187. };
  9188. var message = {
  9189. payload: payload,
  9190. taskType: 1 /* UPDATE */
  9191. };
  9192. var serializable = [];
  9193. for (var id in payload.updatedGeometries) {
  9194. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9195. //prepare transferables
  9196. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9197. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9198. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9199. }
  9200. }
  9201. _this._worker.postMessage(message, serializable);
  9202. _this._addUpdateMeshesList = {};
  9203. _this._addUpdateGeometriesList = {};
  9204. _this._toRemoveGeometryArray = [];
  9205. _this._toRemoveMeshesArray = [];
  9206. };
  9207. this._onMessageFromWorker = function (e) {
  9208. var returnData = e.data;
  9209. if (returnData.error != 0 /* SUCCESS */) {
  9210. //TODO what errors can be returned from the worker?
  9211. BABYLON.Tools.Warn("error returned from worker!");
  9212. return;
  9213. }
  9214. switch (returnData.taskType) {
  9215. case 0 /* INIT */:
  9216. _this._init = true;
  9217. //Update the worked with ALL of the scene's current state
  9218. _this._scene.meshes.forEach(function (mesh) {
  9219. _this.onMeshAdded(mesh);
  9220. });
  9221. _this._scene.getGeometries().forEach(function (geometry) {
  9222. _this.onGeometryAdded(geometry);
  9223. });
  9224. break;
  9225. case 1 /* UPDATE */:
  9226. _this._runningUpdated--;
  9227. break;
  9228. case 2 /* COLLIDE */:
  9229. _this._runningCollisionTask = false;
  9230. var returnPayload = returnData.payload;
  9231. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9232. return;
  9233. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9234. //cleanup
  9235. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9236. break;
  9237. }
  9238. };
  9239. this._collisionsCallbackArray = [];
  9240. this._init = false;
  9241. this._runningUpdated = 0;
  9242. this._runningCollisionTask = false;
  9243. this._addUpdateMeshesList = {};
  9244. this._addUpdateGeometriesList = {};
  9245. this._toRemoveGeometryArray = [];
  9246. this._toRemoveMeshesArray = [];
  9247. }
  9248. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9249. if (!this._init)
  9250. return;
  9251. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9252. return;
  9253. position.divideToRef(collider.radius, this._scaledPosition);
  9254. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9255. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9256. var payload = {
  9257. collider: {
  9258. position: this._scaledPosition.asArray(),
  9259. velocity: this._scaledVelocity.asArray(),
  9260. radius: collider.radius.asArray()
  9261. },
  9262. collisionId: collisionIndex,
  9263. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9264. maximumRetry: maximumRetry
  9265. };
  9266. var message = {
  9267. payload: payload,
  9268. taskType: 2 /* COLLIDE */
  9269. };
  9270. this._worker.postMessage(message);
  9271. };
  9272. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9273. this._scene = scene;
  9274. this._scene.registerAfterRender(this._afterRender);
  9275. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9276. this._worker = new Worker(workerUrl);
  9277. this._worker.onmessage = this._onMessageFromWorker;
  9278. var message = {
  9279. payload: {},
  9280. taskType: 0 /* INIT */
  9281. };
  9282. this._worker.postMessage(message);
  9283. };
  9284. CollisionCoordinatorWorker.prototype.destroy = function () {
  9285. this._scene.unregisterAfterRender(this._afterRender);
  9286. this._worker.terminate();
  9287. };
  9288. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9289. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9290. this.onMeshUpdated(mesh);
  9291. };
  9292. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9293. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9294. };
  9295. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9296. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9297. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9298. this.onGeometryUpdated(geometry);
  9299. };
  9300. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9301. this._toRemoveGeometryArray.push(geometry.id);
  9302. };
  9303. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9304. var submeshes = [];
  9305. if (mesh.subMeshes) {
  9306. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9307. return {
  9308. position: idx,
  9309. verticesStart: sm.verticesStart,
  9310. verticesCount: sm.verticesCount,
  9311. indexStart: sm.indexStart,
  9312. indexCount: sm.indexCount,
  9313. hasMaterial: !!sm.getMaterial(),
  9314. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9315. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9316. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9317. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9318. };
  9319. });
  9320. }
  9321. var geometryId = mesh.geometry ? mesh.geometry.id : null;
  9322. return {
  9323. uniqueId: mesh.uniqueId,
  9324. id: mesh.id,
  9325. name: mesh.name,
  9326. geometryId: geometryId,
  9327. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9328. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9329. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9330. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9331. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9332. subMeshes: submeshes,
  9333. checkCollisions: mesh.checkCollisions
  9334. };
  9335. };
  9336. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9337. return {
  9338. id: geometry.id,
  9339. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9340. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9341. indices: new Int32Array(geometry.getIndices() || []),
  9342. };
  9343. };
  9344. return CollisionCoordinatorWorker;
  9345. })();
  9346. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9347. var CollisionCoordinatorLegacy = (function () {
  9348. function CollisionCoordinatorLegacy() {
  9349. this._scaledPosition = BABYLON.Vector3.Zero();
  9350. this._scaledVelocity = BABYLON.Vector3.Zero();
  9351. this._finalPosition = BABYLON.Vector3.Zero();
  9352. }
  9353. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9354. position.divideToRef(collider.radius, this._scaledPosition);
  9355. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9356. collider.retry = 0;
  9357. collider.initialVelocity = this._scaledVelocity;
  9358. collider.initialPosition = this._scaledPosition;
  9359. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9360. this._finalPosition.multiplyInPlace(collider.radius);
  9361. //run the callback
  9362. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9363. };
  9364. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9365. this._scene = scene;
  9366. };
  9367. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9368. //Legacy need no destruction method.
  9369. };
  9370. //No update in legacy mode
  9371. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) {
  9372. };
  9373. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) {
  9374. };
  9375. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) {
  9376. };
  9377. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) {
  9378. };
  9379. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) {
  9380. };
  9381. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) {
  9382. };
  9383. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9384. if (excludedMesh === void 0) { excludedMesh = null; }
  9385. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9386. if (collider.retry >= maximumRetry) {
  9387. finalPosition.copyFrom(position);
  9388. return;
  9389. }
  9390. collider._initialize(position, velocity, closeDistance);
  9391. for (var index = 0; index < this._scene.meshes.length; index++) {
  9392. var mesh = this._scene.meshes[index];
  9393. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9394. mesh._checkCollision(collider);
  9395. }
  9396. }
  9397. if (!collider.collisionFound) {
  9398. position.addToRef(velocity, finalPosition);
  9399. return;
  9400. }
  9401. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9402. collider._getResponse(position, velocity);
  9403. }
  9404. if (velocity.length() <= closeDistance) {
  9405. finalPosition.copyFrom(position);
  9406. return;
  9407. }
  9408. collider.retry++;
  9409. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9410. };
  9411. return CollisionCoordinatorLegacy;
  9412. })();
  9413. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9414. })(BABYLON || (BABYLON = {}));
  9415. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  9416. var __extends = this.__extends || function (d, b) {
  9417. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9418. function __() { this.constructor = d; }
  9419. __.prototype = b.prototype;
  9420. d.prototype = new __();
  9421. };
  9422. var BABYLON;
  9423. (function (BABYLON) {
  9424. var Camera = (function (_super) {
  9425. __extends(Camera, _super);
  9426. function Camera(name, position, scene) {
  9427. _super.call(this, name, scene);
  9428. this.position = position;
  9429. // Members
  9430. this.upVector = BABYLON.Vector3.Up();
  9431. this.orthoLeft = null;
  9432. this.orthoRight = null;
  9433. this.orthoBottom = null;
  9434. this.orthoTop = null;
  9435. this.fov = 0.8;
  9436. this.minZ = 1.0;
  9437. this.maxZ = 10000.0;
  9438. this.inertia = 0.9;
  9439. this.mode = Camera.PERSPECTIVE_CAMERA;
  9440. this.isIntermediate = false;
  9441. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9442. this.subCameras = [];
  9443. this.layerMask = 0xFFFFFFFF;
  9444. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9445. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9446. this._projectionMatrix = new BABYLON.Matrix();
  9447. this._postProcesses = new Array();
  9448. this._postProcessesTakenIndices = [];
  9449. this._activeMeshes = new BABYLON.SmartArray(256);
  9450. this._globalPosition = BABYLON.Vector3.Zero();
  9451. scene.addCamera(this);
  9452. if (!scene.activeCamera) {
  9453. scene.activeCamera = this;
  9454. }
  9455. }
  9456. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9457. get: function () {
  9458. return Camera._PERSPECTIVE_CAMERA;
  9459. },
  9460. enumerable: true,
  9461. configurable: true
  9462. });
  9463. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9464. get: function () {
  9465. return Camera._ORTHOGRAPHIC_CAMERA;
  9466. },
  9467. enumerable: true,
  9468. configurable: true
  9469. });
  9470. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9471. get: function () {
  9472. return Camera._FOVMODE_VERTICAL_FIXED;
  9473. },
  9474. enumerable: true,
  9475. configurable: true
  9476. });
  9477. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9478. get: function () {
  9479. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9480. },
  9481. enumerable: true,
  9482. configurable: true
  9483. });
  9484. Object.defineProperty(Camera.prototype, "globalPosition", {
  9485. get: function () {
  9486. return this._globalPosition;
  9487. },
  9488. enumerable: true,
  9489. configurable: true
  9490. });
  9491. Camera.prototype.getActiveMeshes = function () {
  9492. return this._activeMeshes;
  9493. };
  9494. Camera.prototype.isActiveMesh = function (mesh) {
  9495. return (this._activeMeshes.indexOf(mesh) !== -1);
  9496. };
  9497. //Cache
  9498. Camera.prototype._initCache = function () {
  9499. _super.prototype._initCache.call(this);
  9500. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9501. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9502. this._cache.mode = undefined;
  9503. this._cache.minZ = undefined;
  9504. this._cache.maxZ = undefined;
  9505. this._cache.fov = undefined;
  9506. this._cache.aspectRatio = undefined;
  9507. this._cache.orthoLeft = undefined;
  9508. this._cache.orthoRight = undefined;
  9509. this._cache.orthoBottom = undefined;
  9510. this._cache.orthoTop = undefined;
  9511. this._cache.renderWidth = undefined;
  9512. this._cache.renderHeight = undefined;
  9513. };
  9514. Camera.prototype._updateCache = function (ignoreParentClass) {
  9515. if (!ignoreParentClass) {
  9516. _super.prototype._updateCache.call(this);
  9517. }
  9518. var engine = this.getEngine();
  9519. this._cache.position.copyFrom(this.position);
  9520. this._cache.upVector.copyFrom(this.upVector);
  9521. this._cache.mode = this.mode;
  9522. this._cache.minZ = this.minZ;
  9523. this._cache.maxZ = this.maxZ;
  9524. this._cache.fov = this.fov;
  9525. this._cache.aspectRatio = engine.getAspectRatio(this);
  9526. this._cache.orthoLeft = this.orthoLeft;
  9527. this._cache.orthoRight = this.orthoRight;
  9528. this._cache.orthoBottom = this.orthoBottom;
  9529. this._cache.orthoTop = this.orthoTop;
  9530. this._cache.renderWidth = engine.getRenderWidth();
  9531. this._cache.renderHeight = engine.getRenderHeight();
  9532. };
  9533. Camera.prototype._updateFromScene = function () {
  9534. this.updateCache();
  9535. this._update();
  9536. };
  9537. // Synchronized
  9538. Camera.prototype._isSynchronized = function () {
  9539. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9540. };
  9541. Camera.prototype._isSynchronizedViewMatrix = function () {
  9542. if (!_super.prototype._isSynchronized.call(this))
  9543. return false;
  9544. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  9545. };
  9546. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9547. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  9548. if (!check) {
  9549. return false;
  9550. }
  9551. var engine = this.getEngine();
  9552. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9553. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  9554. }
  9555. else {
  9556. 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();
  9557. }
  9558. return check;
  9559. };
  9560. // Controls
  9561. Camera.prototype.attachControl = function (element) {
  9562. };
  9563. Camera.prototype.detachControl = function (element) {
  9564. };
  9565. Camera.prototype._update = function () {
  9566. };
  9567. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9568. if (insertAt === void 0) { insertAt = null; }
  9569. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9570. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9571. return 0;
  9572. }
  9573. if (insertAt == null || insertAt < 0) {
  9574. this._postProcesses.push(postProcess);
  9575. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9576. return this._postProcesses.length - 1;
  9577. }
  9578. var add = 0;
  9579. if (this._postProcesses[insertAt]) {
  9580. var start = this._postProcesses.length - 1;
  9581. for (var i = start; i >= insertAt + 1; --i) {
  9582. this._postProcesses[i + 1] = this._postProcesses[i];
  9583. }
  9584. add = 1;
  9585. }
  9586. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9587. if (this._postProcessesTakenIndices[i] < insertAt) {
  9588. continue;
  9589. }
  9590. start = this._postProcessesTakenIndices.length - 1;
  9591. for (var j = start; j >= i; --j) {
  9592. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9593. }
  9594. this._postProcessesTakenIndices[i] = insertAt;
  9595. break;
  9596. }
  9597. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  9598. this._postProcessesTakenIndices.push(insertAt);
  9599. }
  9600. var result = insertAt + add;
  9601. this._postProcesses[result] = postProcess;
  9602. return result;
  9603. };
  9604. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9605. if (atIndices === void 0) { atIndices = null; }
  9606. var result = [];
  9607. if (!atIndices) {
  9608. var length = this._postProcesses.length;
  9609. for (var i = 0; i < length; i++) {
  9610. if (this._postProcesses[i] !== postProcess) {
  9611. continue;
  9612. }
  9613. delete this._postProcesses[i];
  9614. var index = this._postProcessesTakenIndices.indexOf(i);
  9615. this._postProcessesTakenIndices.splice(index, 1);
  9616. }
  9617. }
  9618. else {
  9619. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9620. for (i = 0; i < atIndices.length; i++) {
  9621. var foundPostProcess = this._postProcesses[atIndices[i]];
  9622. if (foundPostProcess !== postProcess) {
  9623. result.push(i);
  9624. continue;
  9625. }
  9626. delete this._postProcesses[atIndices[i]];
  9627. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9628. this._postProcessesTakenIndices.splice(index, 1);
  9629. }
  9630. }
  9631. return result;
  9632. };
  9633. Camera.prototype.getWorldMatrix = function () {
  9634. if (!this._worldMatrix) {
  9635. this._worldMatrix = BABYLON.Matrix.Identity();
  9636. }
  9637. var viewMatrix = this.getViewMatrix();
  9638. viewMatrix.invertToRef(this._worldMatrix);
  9639. return this._worldMatrix;
  9640. };
  9641. Camera.prototype._getViewMatrix = function () {
  9642. return BABYLON.Matrix.Identity();
  9643. };
  9644. Camera.prototype.getViewMatrix = function (force) {
  9645. this._computedViewMatrix = this._computeViewMatrix(force);
  9646. if (!force && this._isSynchronizedViewMatrix()) {
  9647. return this._computedViewMatrix;
  9648. }
  9649. if (!this.parent || !this.parent.getWorldMatrix) {
  9650. this._globalPosition.copyFrom(this.position);
  9651. }
  9652. else {
  9653. if (!this._worldMatrix) {
  9654. this._worldMatrix = BABYLON.Matrix.Identity();
  9655. }
  9656. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9657. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9658. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9659. this._computedViewMatrix.invert();
  9660. this._markSyncedWithParent();
  9661. }
  9662. this._currentRenderId = this.getScene().getRenderId();
  9663. return this._computedViewMatrix;
  9664. };
  9665. Camera.prototype._computeViewMatrix = function (force) {
  9666. if (!force && this._isSynchronizedViewMatrix()) {
  9667. return this._computedViewMatrix;
  9668. }
  9669. this._computedViewMatrix = this._getViewMatrix();
  9670. this._currentRenderId = this.getScene().getRenderId();
  9671. return this._computedViewMatrix;
  9672. };
  9673. Camera.prototype.getProjectionMatrix = function (force) {
  9674. if (!force && this._isSynchronizedProjectionMatrix()) {
  9675. return this._projectionMatrix;
  9676. }
  9677. var engine = this.getEngine();
  9678. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9679. if (this.minZ <= 0) {
  9680. this.minZ = 0.1;
  9681. }
  9682. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9683. return this._projectionMatrix;
  9684. }
  9685. var halfWidth = engine.getRenderWidth() / 2.0;
  9686. var halfHeight = engine.getRenderHeight() / 2.0;
  9687. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9688. return this._projectionMatrix;
  9689. };
  9690. Camera.prototype.dispose = function () {
  9691. // Remove from scene
  9692. this.getScene().removeCamera(this);
  9693. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9694. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9695. }
  9696. };
  9697. // Statics
  9698. Camera._PERSPECTIVE_CAMERA = 0;
  9699. Camera._ORTHOGRAPHIC_CAMERA = 1;
  9700. Camera._FOVMODE_VERTICAL_FIXED = 0;
  9701. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  9702. return Camera;
  9703. })(BABYLON.Node);
  9704. BABYLON.Camera = Camera;
  9705. })(BABYLON || (BABYLON = {}));
  9706. //# sourceMappingURL=babylon.camera.js.map
  9707. var __extends = this.__extends || function (d, b) {
  9708. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9709. function __() { this.constructor = d; }
  9710. __.prototype = b.prototype;
  9711. d.prototype = new __();
  9712. };
  9713. var BABYLON;
  9714. (function (BABYLON) {
  9715. var TargetCamera = (function (_super) {
  9716. __extends(TargetCamera, _super);
  9717. function TargetCamera(name, position, scene) {
  9718. _super.call(this, name, position, scene);
  9719. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  9720. this.cameraRotation = new BABYLON.Vector2(0, 0);
  9721. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9722. this.speed = 2.0;
  9723. this.noRotationConstraint = false;
  9724. this.lockedTarget = null;
  9725. this._currentTarget = BABYLON.Vector3.Zero();
  9726. this._viewMatrix = BABYLON.Matrix.Zero();
  9727. this._camMatrix = BABYLON.Matrix.Zero();
  9728. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  9729. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  9730. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  9731. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  9732. this._lookAtTemp = BABYLON.Matrix.Zero();
  9733. this._tempMatrix = BABYLON.Matrix.Zero();
  9734. }
  9735. TargetCamera.prototype._getLockedTargetPosition = function () {
  9736. if (!this.lockedTarget) {
  9737. return null;
  9738. }
  9739. return this.lockedTarget.position || this.lockedTarget;
  9740. };
  9741. // Cache
  9742. TargetCamera.prototype._initCache = function () {
  9743. _super.prototype._initCache.call(this);
  9744. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9745. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9746. };
  9747. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  9748. if (!ignoreParentClass) {
  9749. _super.prototype._updateCache.call(this);
  9750. }
  9751. var lockedTargetPosition = this._getLockedTargetPosition();
  9752. if (!lockedTargetPosition) {
  9753. this._cache.lockedTarget = null;
  9754. }
  9755. else {
  9756. if (!this._cache.lockedTarget) {
  9757. this._cache.lockedTarget = lockedTargetPosition.clone();
  9758. }
  9759. else {
  9760. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  9761. }
  9762. }
  9763. this._cache.rotation.copyFrom(this.rotation);
  9764. };
  9765. // Synchronized
  9766. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  9767. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  9768. return false;
  9769. }
  9770. var lockedTargetPosition = this._getLockedTargetPosition();
  9771. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  9772. };
  9773. // Methods
  9774. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  9775. var engine = this.getEngine();
  9776. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  9777. };
  9778. // Target
  9779. TargetCamera.prototype.setTarget = function (target) {
  9780. this.upVector.normalize();
  9781. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  9782. this._camMatrix.invert();
  9783. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  9784. var vDir = target.subtract(this.position);
  9785. if (vDir.x >= 0.0) {
  9786. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  9787. }
  9788. else {
  9789. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  9790. }
  9791. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  9792. if (isNaN(this.rotation.x)) {
  9793. this.rotation.x = 0;
  9794. }
  9795. if (isNaN(this.rotation.y)) {
  9796. this.rotation.y = 0;
  9797. }
  9798. if (isNaN(this.rotation.z)) {
  9799. this.rotation.z = 0;
  9800. }
  9801. };
  9802. TargetCamera.prototype.getTarget = function () {
  9803. return this._currentTarget;
  9804. };
  9805. TargetCamera.prototype._decideIfNeedsToMove = function () {
  9806. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  9807. };
  9808. TargetCamera.prototype._updatePosition = function () {
  9809. this.position.addInPlace(this.cameraDirection);
  9810. };
  9811. TargetCamera.prototype._update = function () {
  9812. var needToMove = this._decideIfNeedsToMove();
  9813. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  9814. // Move
  9815. if (needToMove) {
  9816. this._updatePosition();
  9817. }
  9818. // Rotate
  9819. if (needToRotate) {
  9820. this.rotation.x += this.cameraRotation.x;
  9821. this.rotation.y += this.cameraRotation.y;
  9822. if (!this.noRotationConstraint) {
  9823. var limit = (Math.PI / 2) * 0.95;
  9824. if (this.rotation.x > limit)
  9825. this.rotation.x = limit;
  9826. if (this.rotation.x < -limit)
  9827. this.rotation.x = -limit;
  9828. }
  9829. }
  9830. // Inertia
  9831. if (needToMove) {
  9832. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  9833. this.cameraDirection.x = 0;
  9834. }
  9835. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  9836. this.cameraDirection.y = 0;
  9837. }
  9838. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  9839. this.cameraDirection.z = 0;
  9840. }
  9841. this.cameraDirection.scaleInPlace(this.inertia);
  9842. }
  9843. if (needToRotate) {
  9844. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  9845. this.cameraRotation.x = 0;
  9846. }
  9847. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  9848. this.cameraRotation.y = 0;
  9849. }
  9850. this.cameraRotation.scaleInPlace(this.inertia);
  9851. }
  9852. };
  9853. TargetCamera.prototype._getViewMatrix = function () {
  9854. if (!this.lockedTarget) {
  9855. // Compute
  9856. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  9857. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  9858. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  9859. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  9860. this._lookAtTemp.invert();
  9861. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  9862. }
  9863. else {
  9864. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  9865. }
  9866. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  9867. // Computing target and final matrix
  9868. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  9869. }
  9870. else {
  9871. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  9872. }
  9873. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  9874. return this._viewMatrix;
  9875. };
  9876. return TargetCamera;
  9877. })(BABYLON.Camera);
  9878. BABYLON.TargetCamera = TargetCamera;
  9879. })(BABYLON || (BABYLON = {}));
  9880. //# sourceMappingURL=babylon.targetCamera.js.map
  9881. var __extends = this.__extends || function (d, b) {
  9882. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9883. function __() { this.constructor = d; }
  9884. __.prototype = b.prototype;
  9885. d.prototype = new __();
  9886. };
  9887. var BABYLON;
  9888. (function (BABYLON) {
  9889. var FreeCamera = (function (_super) {
  9890. __extends(FreeCamera, _super);
  9891. function FreeCamera(name, position, scene) {
  9892. var _this = this;
  9893. _super.call(this, name, position, scene);
  9894. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9895. this.keysUp = [38];
  9896. this.keysDown = [40];
  9897. this.keysLeft = [37];
  9898. this.keysRight = [39];
  9899. this.checkCollisions = false;
  9900. this.applyGravity = false;
  9901. this.angularSensibility = 2000.0;
  9902. this._keys = [];
  9903. this._collider = new BABYLON.Collider();
  9904. this._needMoveForGravity = false;
  9905. this._oldPosition = BABYLON.Vector3.Zero();
  9906. this._diffPosition = BABYLON.Vector3.Zero();
  9907. this._newPosition = BABYLON.Vector3.Zero();
  9908. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9909. if (collidedMesh === void 0) { collidedMesh = null; }
  9910. //TODO move this to the collision coordinator!
  9911. if (_this.getScene().workerCollisions)
  9912. newPosition.multiplyInPlace(_this._collider.radius);
  9913. var updatePosition = function (newPos) {
  9914. _this._newPosition.copyFrom(newPos);
  9915. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  9916. var oldPosition = _this.position.clone();
  9917. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  9918. _this.position.addInPlace(_this._diffPosition);
  9919. if (_this.onCollide && collidedMesh) {
  9920. _this.onCollide(collidedMesh);
  9921. }
  9922. }
  9923. };
  9924. updatePosition(newPosition);
  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) {
  10044. var globalPosition;
  10045. if (this.parent) {
  10046. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10047. }
  10048. else {
  10049. globalPosition = this.position;
  10050. }
  10051. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10052. this._collider.radius = this.ellipsoid;
  10053. //add gravity to the velocity to prevent the dual-collision checking
  10054. if (this.applyGravity) {
  10055. velocity.addInPlace(this.getScene().gravity);
  10056. }
  10057. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10058. };
  10059. FreeCamera.prototype._checkInputs = function () {
  10060. if (!this._localDirection) {
  10061. this._localDirection = BABYLON.Vector3.Zero();
  10062. this._transformedDirection = BABYLON.Vector3.Zero();
  10063. }
  10064. for (var index = 0; index < this._keys.length; index++) {
  10065. var keyCode = this._keys[index];
  10066. var speed = this._computeLocalCameraSpeed();
  10067. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10068. this._localDirection.copyFromFloats(-speed, 0, 0);
  10069. }
  10070. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10071. this._localDirection.copyFromFloats(0, 0, speed);
  10072. }
  10073. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10074. this._localDirection.copyFromFloats(speed, 0, 0);
  10075. }
  10076. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10077. this._localDirection.copyFromFloats(0, 0, -speed);
  10078. }
  10079. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10080. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10081. this.cameraDirection.addInPlace(this._transformedDirection);
  10082. }
  10083. };
  10084. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10085. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10086. };
  10087. FreeCamera.prototype._updatePosition = function () {
  10088. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10089. this._collideWithWorld(this.cameraDirection);
  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. enabled = (enabled && !!Worker);
  11130. this._workerCollisions = enabled;
  11131. if (this.collisionCoordinator) {
  11132. this.collisionCoordinator.destroy();
  11133. }
  11134. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  11135. this.collisionCoordinator.init(this);
  11136. },
  11137. enumerable: true,
  11138. configurable: true
  11139. });
  11140. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  11141. /**
  11142. * The mesh that is currently under the pointer.
  11143. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  11144. */
  11145. get: function () {
  11146. return this._meshUnderPointer;
  11147. },
  11148. enumerable: true,
  11149. configurable: true
  11150. });
  11151. Object.defineProperty(Scene.prototype, "pointerX", {
  11152. /**
  11153. * Current on-screen X position of the pointer
  11154. * @return {number} X position of the pointer
  11155. */
  11156. get: function () {
  11157. return this._pointerX;
  11158. },
  11159. enumerable: true,
  11160. configurable: true
  11161. });
  11162. Object.defineProperty(Scene.prototype, "pointerY", {
  11163. /**
  11164. * Current on-screen Y position of the pointer
  11165. * @return {number} Y position of the pointer
  11166. */
  11167. get: function () {
  11168. return this._pointerY;
  11169. },
  11170. enumerable: true,
  11171. configurable: true
  11172. });
  11173. Scene.prototype.getCachedMaterial = function () {
  11174. return this._cachedMaterial;
  11175. };
  11176. Scene.prototype.getBoundingBoxRenderer = function () {
  11177. return this._boundingBoxRenderer;
  11178. };
  11179. Scene.prototype.getOutlineRenderer = function () {
  11180. return this._outlineRenderer;
  11181. };
  11182. Scene.prototype.getEngine = function () {
  11183. return this._engine;
  11184. };
  11185. Scene.prototype.getTotalVertices = function () {
  11186. return this._totalVertices;
  11187. };
  11188. Scene.prototype.getActiveIndices = function () {
  11189. return this._activeIndices;
  11190. };
  11191. Scene.prototype.getActiveParticles = function () {
  11192. return this._activeParticles;
  11193. };
  11194. Scene.prototype.getActiveBones = function () {
  11195. return this._activeBones;
  11196. };
  11197. // Stats
  11198. Scene.prototype.getLastFrameDuration = function () {
  11199. return this._lastFrameDuration;
  11200. };
  11201. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  11202. return this._evaluateActiveMeshesDuration;
  11203. };
  11204. Scene.prototype.getActiveMeshes = function () {
  11205. return this._activeMeshes;
  11206. };
  11207. Scene.prototype.getRenderTargetsDuration = function () {
  11208. return this._renderTargetsDuration;
  11209. };
  11210. Scene.prototype.getRenderDuration = function () {
  11211. return this._renderDuration;
  11212. };
  11213. Scene.prototype.getParticlesDuration = function () {
  11214. return this._particlesDuration;
  11215. };
  11216. Scene.prototype.getSpritesDuration = function () {
  11217. return this._spritesDuration;
  11218. };
  11219. Scene.prototype.getAnimationRatio = function () {
  11220. return this._animationRatio;
  11221. };
  11222. Scene.prototype.getRenderId = function () {
  11223. return this._renderId;
  11224. };
  11225. Scene.prototype.incrementRenderId = function () {
  11226. this._renderId++;
  11227. };
  11228. Scene.prototype._updatePointerPosition = function (evt) {
  11229. var canvasRect = this._engine.getRenderingCanvasClientRect();
  11230. this._pointerX = evt.clientX - canvasRect.left;
  11231. this._pointerY = evt.clientY - canvasRect.top;
  11232. if (this.cameraToUseForPointers) {
  11233. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  11234. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  11235. }
  11236. };
  11237. // Pointers handling
  11238. Scene.prototype.attachControl = function () {
  11239. var _this = this;
  11240. this._onPointerMove = function (evt) {
  11241. var canvas = _this._engine.getRenderingCanvas();
  11242. _this._updatePointerPosition(evt);
  11243. 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);
  11244. if (pickResult.hit) {
  11245. _this._meshUnderPointer = pickResult.pickedMesh;
  11246. _this.setPointerOverMesh(pickResult.pickedMesh);
  11247. canvas.style.cursor = "pointer";
  11248. }
  11249. else {
  11250. _this.setPointerOverMesh(null);
  11251. canvas.style.cursor = "";
  11252. _this._meshUnderPointer = null;
  11253. }
  11254. };
  11255. this._onPointerDown = function (evt) {
  11256. var predicate = null;
  11257. if (!_this.onPointerDown) {
  11258. predicate = function (mesh) {
  11259. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  11260. };
  11261. }
  11262. _this._updatePointerPosition(evt);
  11263. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11264. if (pickResult.hit) {
  11265. if (pickResult.pickedMesh.actionManager) {
  11266. switch (evt.button) {
  11267. case 0:
  11268. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11269. break;
  11270. case 1:
  11271. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11272. break;
  11273. case 2:
  11274. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11275. break;
  11276. }
  11277. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11278. }
  11279. }
  11280. if (_this.onPointerDown) {
  11281. _this.onPointerDown(evt, pickResult);
  11282. }
  11283. };
  11284. this._onPointerUp = function (evt) {
  11285. var predicate = null;
  11286. if (!_this.onPointerUp) {
  11287. predicate = function (mesh) {
  11288. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  11289. };
  11290. }
  11291. _this._updatePointerPosition(evt);
  11292. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11293. if (pickResult.hit) {
  11294. if (pickResult.pickedMesh.actionManager) {
  11295. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11296. }
  11297. }
  11298. if (_this.onPointerUp) {
  11299. _this.onPointerUp(evt, pickResult);
  11300. }
  11301. };
  11302. this._onKeyDown = function (evt) {
  11303. if (_this.actionManager) {
  11304. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11305. }
  11306. };
  11307. this._onKeyUp = function (evt) {
  11308. if (_this.actionManager) {
  11309. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11310. }
  11311. };
  11312. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11313. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11314. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11315. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11316. BABYLON.Tools.RegisterTopRootEvents([
  11317. { name: "keydown", handler: this._onKeyDown },
  11318. { name: "keyup", handler: this._onKeyUp }
  11319. ]);
  11320. };
  11321. Scene.prototype.detachControl = function () {
  11322. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11323. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  11324. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  11325. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  11326. BABYLON.Tools.UnregisterTopRootEvents([
  11327. { name: "keydown", handler: this._onKeyDown },
  11328. { name: "keyup", handler: this._onKeyUp }
  11329. ]);
  11330. };
  11331. // Ready
  11332. Scene.prototype.isReady = function () {
  11333. if (this._pendingData.length > 0) {
  11334. return false;
  11335. }
  11336. for (var index = 0; index < this._geometries.length; index++) {
  11337. var geometry = this._geometries[index];
  11338. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11339. return false;
  11340. }
  11341. }
  11342. for (index = 0; index < this.meshes.length; index++) {
  11343. var mesh = this.meshes[index];
  11344. if (!mesh.isReady()) {
  11345. return false;
  11346. }
  11347. var mat = mesh.material;
  11348. if (mat) {
  11349. if (!mat.isReady(mesh)) {
  11350. return false;
  11351. }
  11352. }
  11353. }
  11354. return true;
  11355. };
  11356. Scene.prototype.resetCachedMaterial = function () {
  11357. this._cachedMaterial = null;
  11358. };
  11359. Scene.prototype.registerBeforeRender = function (func) {
  11360. this._onBeforeRenderCallbacks.push(func);
  11361. };
  11362. Scene.prototype.unregisterBeforeRender = function (func) {
  11363. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11364. if (index > -1) {
  11365. this._onBeforeRenderCallbacks.splice(index, 1);
  11366. }
  11367. };
  11368. Scene.prototype.registerAfterRender = function (func) {
  11369. this._onAfterRenderCallbacks.push(func);
  11370. };
  11371. Scene.prototype.unregisterAfterRender = function (func) {
  11372. var index = this._onAfterRenderCallbacks.indexOf(func);
  11373. if (index > -1) {
  11374. this._onAfterRenderCallbacks.splice(index, 1);
  11375. }
  11376. };
  11377. Scene.prototype._addPendingData = function (data) {
  11378. this._pendingData.push(data);
  11379. };
  11380. Scene.prototype._removePendingData = function (data) {
  11381. var index = this._pendingData.indexOf(data);
  11382. if (index !== -1) {
  11383. this._pendingData.splice(index, 1);
  11384. }
  11385. };
  11386. Scene.prototype.getWaitingItemsCount = function () {
  11387. return this._pendingData.length;
  11388. };
  11389. /**
  11390. * Registers a function to be executed when the scene is ready.
  11391. * @param {Function} func - the function to be executed.
  11392. */
  11393. Scene.prototype.executeWhenReady = function (func) {
  11394. var _this = this;
  11395. this._onReadyCallbacks.push(func);
  11396. if (this._executeWhenReadyTimeoutId !== -1) {
  11397. return;
  11398. }
  11399. this._executeWhenReadyTimeoutId = setTimeout(function () {
  11400. _this._checkIsReady();
  11401. }, 150);
  11402. };
  11403. Scene.prototype._checkIsReady = function () {
  11404. var _this = this;
  11405. if (this.isReady()) {
  11406. this._onReadyCallbacks.forEach(function (func) {
  11407. func();
  11408. });
  11409. this._onReadyCallbacks = [];
  11410. this._executeWhenReadyTimeoutId = -1;
  11411. return;
  11412. }
  11413. this._executeWhenReadyTimeoutId = setTimeout(function () {
  11414. _this._checkIsReady();
  11415. }, 150);
  11416. };
  11417. // Animations
  11418. /**
  11419. * Will start the animation sequence of a given target
  11420. * @param target - the target
  11421. * @param {number} from - from which frame should animation start
  11422. * @param {number} to - till which frame should animation run.
  11423. * @param {boolean} [loop] - should the animation loop
  11424. * @param {number} [speedRatio] - the speed in which to run the animation
  11425. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  11426. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  11427. * @return {BABYLON.Animatable} the animatable object created for this animation
  11428. * @see BABYLON.Animatable
  11429. * @see http://doc.babylonjs.com/page.php?p=22081
  11430. */
  11431. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  11432. if (speedRatio === undefined) {
  11433. speedRatio = 1.0;
  11434. }
  11435. this.stopAnimation(target);
  11436. if (!animatable) {
  11437. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  11438. }
  11439. // Local animations
  11440. if (target.animations) {
  11441. animatable.appendAnimations(target, target.animations);
  11442. }
  11443. // Children animations
  11444. if (target.getAnimatables) {
  11445. var animatables = target.getAnimatables();
  11446. for (var index = 0; index < animatables.length; index++) {
  11447. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  11448. }
  11449. }
  11450. return animatable;
  11451. };
  11452. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  11453. if (speedRatio === undefined) {
  11454. speedRatio = 1.0;
  11455. }
  11456. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  11457. return animatable;
  11458. };
  11459. Scene.prototype.getAnimatableByTarget = function (target) {
  11460. for (var index = 0; index < this._activeAnimatables.length; index++) {
  11461. if (this._activeAnimatables[index].target === target) {
  11462. return this._activeAnimatables[index];
  11463. }
  11464. }
  11465. return null;
  11466. };
  11467. /**
  11468. * Will stop the animation of the given target
  11469. * @param target - the target
  11470. * @see beginAnimation
  11471. */
  11472. Scene.prototype.stopAnimation = function (target) {
  11473. var animatable = this.getAnimatableByTarget(target);
  11474. if (animatable) {
  11475. animatable.stop();
  11476. }
  11477. };
  11478. Scene.prototype._animate = function () {
  11479. if (!this.animationsEnabled) {
  11480. return;
  11481. }
  11482. if (!this._animationStartDate) {
  11483. this._animationStartDate = BABYLON.Tools.Now;
  11484. }
  11485. // Getting time
  11486. var now = BABYLON.Tools.Now;
  11487. var delay = now - this._animationStartDate;
  11488. for (var index = 0; index < this._activeAnimatables.length; index++) {
  11489. this._activeAnimatables[index]._animate(delay);
  11490. }
  11491. };
  11492. // Matrix
  11493. Scene.prototype.getViewMatrix = function () {
  11494. return this._viewMatrix;
  11495. };
  11496. Scene.prototype.getProjectionMatrix = function () {
  11497. return this._projectionMatrix;
  11498. };
  11499. Scene.prototype.getTransformMatrix = function () {
  11500. return this._transformMatrix;
  11501. };
  11502. Scene.prototype.setTransformMatrix = function (view, projection) {
  11503. this._viewMatrix = view;
  11504. this._projectionMatrix = projection;
  11505. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11506. };
  11507. // Methods
  11508. Scene.prototype.addMesh = function (newMesh) {
  11509. newMesh.uniqueId = this._uniqueIdCounter++;
  11510. var position = this.meshes.push(newMesh);
  11511. //notify the collision coordinator
  11512. this.collisionCoordinator.onMeshAdded(newMesh);
  11513. if (this.onNewMeshAdded) {
  11514. this.onNewMeshAdded(newMesh, position, this);
  11515. }
  11516. };
  11517. Scene.prototype.removeMesh = function (toRemove) {
  11518. var index = this.meshes.indexOf(toRemove);
  11519. if (index !== -1) {
  11520. // Remove from the scene if mesh found
  11521. this.meshes.splice(index, 1);
  11522. }
  11523. //notify the collision coordinator
  11524. this.collisionCoordinator.onMeshRemoved(toRemove);
  11525. if (this.onMeshRemoved) {
  11526. this.onMeshRemoved(toRemove);
  11527. }
  11528. return index;
  11529. };
  11530. Scene.prototype.removeLight = function (toRemove) {
  11531. var index = this.lights.indexOf(toRemove);
  11532. if (index !== -1) {
  11533. // Remove from the scene if mesh found
  11534. this.lights.splice(index, 1);
  11535. }
  11536. if (this.onLightRemoved) {
  11537. this.onLightRemoved(toRemove);
  11538. }
  11539. return index;
  11540. };
  11541. Scene.prototype.removeCamera = function (toRemove) {
  11542. var index = this.cameras.indexOf(toRemove);
  11543. if (index !== -1) {
  11544. // Remove from the scene if mesh found
  11545. this.cameras.splice(index, 1);
  11546. }
  11547. // Remove from activeCameras
  11548. var index2 = this.activeCameras.indexOf(toRemove);
  11549. if (index2 !== -1) {
  11550. // Remove from the scene if mesh found
  11551. this.activeCameras.splice(index2, 1);
  11552. }
  11553. // Reset the activeCamera
  11554. if (this.activeCamera === toRemove) {
  11555. if (this.cameras.length > 0) {
  11556. this.activeCamera = this.cameras[0];
  11557. }
  11558. else {
  11559. this.activeCamera = null;
  11560. }
  11561. }
  11562. if (this.onCameraRemoved) {
  11563. this.onCameraRemoved(toRemove);
  11564. }
  11565. return index;
  11566. };
  11567. Scene.prototype.addLight = function (newLight) {
  11568. newLight.uniqueId = this._uniqueIdCounter++;
  11569. var position = this.lights.push(newLight);
  11570. if (this.onNewLightAdded) {
  11571. this.onNewLightAdded(newLight, position, this);
  11572. }
  11573. };
  11574. Scene.prototype.addCamera = function (newCamera) {
  11575. newCamera.uniqueId = this._uniqueIdCounter++;
  11576. var position = this.cameras.push(newCamera);
  11577. if (this.onNewCameraAdded) {
  11578. this.onNewCameraAdded(newCamera, position, this);
  11579. }
  11580. };
  11581. /**
  11582. * sets the active camera of the scene using its ID
  11583. * @param {string} id - the camera's ID
  11584. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  11585. * @see activeCamera
  11586. */
  11587. Scene.prototype.setActiveCameraByID = function (id) {
  11588. var camera = this.getCameraByID(id);
  11589. if (camera) {
  11590. this.activeCamera = camera;
  11591. return camera;
  11592. }
  11593. return null;
  11594. };
  11595. /**
  11596. * sets the active camera of the scene using its name
  11597. * @param {string} name - the camera's name
  11598. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  11599. * @see activeCamera
  11600. */
  11601. Scene.prototype.setActiveCameraByName = function (name) {
  11602. var camera = this.getCameraByName(name);
  11603. if (camera) {
  11604. this.activeCamera = camera;
  11605. return camera;
  11606. }
  11607. return null;
  11608. };
  11609. /**
  11610. * get a material using its id
  11611. * @param {string} the material's ID
  11612. * @return {BABYLON.Material|null} the material or null if none found.
  11613. */
  11614. Scene.prototype.getMaterialByID = function (id) {
  11615. for (var index = 0; index < this.materials.length; index++) {
  11616. if (this.materials[index].id === id) {
  11617. return this.materials[index];
  11618. }
  11619. }
  11620. return null;
  11621. };
  11622. /**
  11623. * get a material using its name
  11624. * @param {string} the material's name
  11625. * @return {BABYLON.Material|null} the material or null if none found.
  11626. */
  11627. Scene.prototype.getMaterialByName = function (name) {
  11628. for (var index = 0; index < this.materials.length; index++) {
  11629. if (this.materials[index].name === name) {
  11630. return this.materials[index];
  11631. }
  11632. }
  11633. return null;
  11634. };
  11635. Scene.prototype.getCameraByID = function (id) {
  11636. for (var index = 0; index < this.cameras.length; index++) {
  11637. if (this.cameras[index].id === id) {
  11638. return this.cameras[index];
  11639. }
  11640. }
  11641. return null;
  11642. };
  11643. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  11644. for (var index = 0; index < this.cameras.length; index++) {
  11645. if (this.cameras[index].uniqueId === uniqueId) {
  11646. return this.cameras[index];
  11647. }
  11648. }
  11649. return null;
  11650. };
  11651. /**
  11652. * get a camera using its name
  11653. * @param {string} the camera's name
  11654. * @return {BABYLON.Camera|null} the camera or null if none found.
  11655. */
  11656. Scene.prototype.getCameraByName = function (name) {
  11657. for (var index = 0; index < this.cameras.length; index++) {
  11658. if (this.cameras[index].name === name) {
  11659. return this.cameras[index];
  11660. }
  11661. }
  11662. return null;
  11663. };
  11664. /**
  11665. * get a light node using its name
  11666. * @param {string} the light's name
  11667. * @return {BABYLON.Light|null} the light or null if none found.
  11668. */
  11669. Scene.prototype.getLightByName = function (name) {
  11670. for (var index = 0; index < this.lights.length; index++) {
  11671. if (this.lights[index].name === name) {
  11672. return this.lights[index];
  11673. }
  11674. }
  11675. return null;
  11676. };
  11677. /**
  11678. * get a light node using its ID
  11679. * @param {string} the light's id
  11680. * @return {BABYLON.Light|null} the light or null if none found.
  11681. */
  11682. Scene.prototype.getLightByID = function (id) {
  11683. for (var index = 0; index < this.lights.length; index++) {
  11684. if (this.lights[index].id === id) {
  11685. return this.lights[index];
  11686. }
  11687. }
  11688. return null;
  11689. };
  11690. /**
  11691. * get a light node using its scene-generated unique ID
  11692. * @param {number} the light's unique id
  11693. * @return {BABYLON.Light|null} the light or null if none found.
  11694. */
  11695. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  11696. for (var index = 0; index < this.lights.length; index++) {
  11697. if (this.lights[index].uniqueId === uniqueId) {
  11698. return this.lights[index];
  11699. }
  11700. }
  11701. return null;
  11702. };
  11703. /**
  11704. * get a geometry using its ID
  11705. * @param {string} the geometry's id
  11706. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  11707. */
  11708. Scene.prototype.getGeometryByID = function (id) {
  11709. for (var index = 0; index < this._geometries.length; index++) {
  11710. if (this._geometries[index].id === id) {
  11711. return this._geometries[index];
  11712. }
  11713. }
  11714. return null;
  11715. };
  11716. /**
  11717. * add a new geometry to this scene.
  11718. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  11719. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  11720. * @return {boolean} was the geometry added or not
  11721. */
  11722. Scene.prototype.pushGeometry = function (geometry, force) {
  11723. if (!force && this.getGeometryByID(geometry.id)) {
  11724. return false;
  11725. }
  11726. this._geometries.push(geometry);
  11727. //notify the collision coordinator
  11728. this.collisionCoordinator.onGeometryAdded(geometry);
  11729. if (this.onGeometryAdded) {
  11730. this.onGeometryAdded(geometry);
  11731. }
  11732. return true;
  11733. };
  11734. /**
  11735. * Removes an existing geometry
  11736. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  11737. * @return {boolean} was the geometry removed or not
  11738. */
  11739. Scene.prototype.removeGeometry = function (geometry) {
  11740. var index = this._geometries.indexOf(geometry);
  11741. if (index > -1) {
  11742. this._geometries.splice(index, 1);
  11743. //notify the collision coordinator
  11744. this.collisionCoordinator.onGeometryDeleted(geometry);
  11745. if (this.onGeometryRemoved) {
  11746. this.onGeometryRemoved(geometry);
  11747. }
  11748. return true;
  11749. }
  11750. return false;
  11751. };
  11752. Scene.prototype.getGeometries = function () {
  11753. return this._geometries;
  11754. };
  11755. /**
  11756. * Get the first added mesh found of a given ID
  11757. * @param {string} id - the id to search for
  11758. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  11759. */
  11760. Scene.prototype.getMeshByID = function (id) {
  11761. for (var index = 0; index < this.meshes.length; index++) {
  11762. if (this.meshes[index].id === id) {
  11763. return this.meshes[index];
  11764. }
  11765. }
  11766. return null;
  11767. };
  11768. /**
  11769. * Get a mesh with its auto-generated unique id
  11770. * @param {number} uniqueId - the unique id to search for
  11771. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  11772. */
  11773. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  11774. for (var index = 0; index < this.meshes.length; index++) {
  11775. if (this.meshes[index].uniqueId === uniqueId) {
  11776. return this.meshes[index];
  11777. }
  11778. }
  11779. return null;
  11780. };
  11781. /**
  11782. * Get a the last added mesh found of a given ID
  11783. * @param {string} id - the id to search for
  11784. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  11785. */
  11786. Scene.prototype.getLastMeshByID = function (id) {
  11787. for (var index = this.meshes.length - 1; index >= 0; index--) {
  11788. if (this.meshes[index].id === id) {
  11789. return this.meshes[index];
  11790. }
  11791. }
  11792. return null;
  11793. };
  11794. /**
  11795. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  11796. * @param {string} id - the id to search for
  11797. * @return {BABYLON.Node|null} the node found or null if not found at all.
  11798. */
  11799. Scene.prototype.getLastEntryByID = function (id) {
  11800. for (var index = this.meshes.length - 1; index >= 0; index--) {
  11801. if (this.meshes[index].id === id) {
  11802. return this.meshes[index];
  11803. }
  11804. }
  11805. for (index = this.cameras.length - 1; index >= 0; index--) {
  11806. if (this.cameras[index].id === id) {
  11807. return this.cameras[index];
  11808. }
  11809. }
  11810. for (index = this.lights.length - 1; index >= 0; index--) {
  11811. if (this.lights[index].id === id) {
  11812. return this.lights[index];
  11813. }
  11814. }
  11815. return null;
  11816. };
  11817. Scene.prototype.getNodeByName = function (name) {
  11818. var mesh = this.getMeshByName(name);
  11819. if (mesh) {
  11820. return mesh;
  11821. }
  11822. var light = this.getLightByName(name);
  11823. if (light) {
  11824. return light;
  11825. }
  11826. return this.getCameraByName(name);
  11827. };
  11828. Scene.prototype.getMeshByName = function (name) {
  11829. for (var index = 0; index < this.meshes.length; index++) {
  11830. if (this.meshes[index].name === name) {
  11831. return this.meshes[index];
  11832. }
  11833. }
  11834. return null;
  11835. };
  11836. Scene.prototype.getSoundByName = function (name) {
  11837. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  11838. if (this.mainSoundTrack.soundCollection[index].name === name) {
  11839. return this.mainSoundTrack.soundCollection[index];
  11840. }
  11841. }
  11842. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  11843. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  11844. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  11845. return this.soundTracks[sdIndex].soundCollection[index];
  11846. }
  11847. }
  11848. }
  11849. return null;
  11850. };
  11851. Scene.prototype.getLastSkeletonByID = function (id) {
  11852. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  11853. if (this.skeletons[index].id === id) {
  11854. return this.skeletons[index];
  11855. }
  11856. }
  11857. return null;
  11858. };
  11859. Scene.prototype.getSkeletonById = function (id) {
  11860. for (var index = 0; index < this.skeletons.length; index++) {
  11861. if (this.skeletons[index].id === id) {
  11862. return this.skeletons[index];
  11863. }
  11864. }
  11865. return null;
  11866. };
  11867. Scene.prototype.getSkeletonByName = function (name) {
  11868. for (var index = 0; index < this.skeletons.length; index++) {
  11869. if (this.skeletons[index].name === name) {
  11870. return this.skeletons[index];
  11871. }
  11872. }
  11873. return null;
  11874. };
  11875. Scene.prototype.isActiveMesh = function (mesh) {
  11876. return (this._activeMeshes.indexOf(mesh) !== -1);
  11877. };
  11878. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  11879. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  11880. var material = subMesh.getMaterial();
  11881. if (mesh.showSubMeshesBoundingBox) {
  11882. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  11883. }
  11884. if (material) {
  11885. // Render targets
  11886. if (material.getRenderTargetTextures) {
  11887. if (this._processedMaterials.indexOf(material) === -1) {
  11888. this._processedMaterials.push(material);
  11889. this._renderTargets.concat(material.getRenderTargetTextures());
  11890. }
  11891. }
  11892. // Dispatch
  11893. this._activeIndices += subMesh.indexCount;
  11894. this._renderingManager.dispatch(subMesh);
  11895. }
  11896. }
  11897. };
  11898. Scene.prototype._evaluateActiveMeshes = function () {
  11899. this.activeCamera._activeMeshes.reset();
  11900. this._activeMeshes.reset();
  11901. this._renderingManager.reset();
  11902. this._processedMaterials.reset();
  11903. this._activeParticleSystems.reset();
  11904. this._activeSkeletons.reset();
  11905. this._boundingBoxRenderer.reset();
  11906. if (!this._frustumPlanes) {
  11907. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  11908. }
  11909. else {
  11910. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  11911. }
  11912. // Meshes
  11913. var meshes;
  11914. var len;
  11915. if (this._selectionOctree) {
  11916. var selection = this._selectionOctree.select(this._frustumPlanes);
  11917. meshes = selection.data;
  11918. len = selection.length;
  11919. }
  11920. else {
  11921. len = this.meshes.length;
  11922. meshes = this.meshes;
  11923. }
  11924. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  11925. var mesh = meshes[meshIndex];
  11926. if (mesh.isBlocked) {
  11927. continue;
  11928. }
  11929. this._totalVertices += mesh.getTotalVertices();
  11930. if (!mesh.isReady() || !mesh.isEnabled()) {
  11931. continue;
  11932. }
  11933. mesh.computeWorldMatrix();
  11934. // Intersections
  11935. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  11936. this._meshesForIntersections.pushNoDuplicate(mesh);
  11937. }
  11938. // Switch to current LOD
  11939. var meshLOD = mesh.getLOD(this.activeCamera);
  11940. if (!meshLOD) {
  11941. continue;
  11942. }
  11943. mesh._preActivate();
  11944. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  11945. this._activeMeshes.push(mesh);
  11946. this.activeCamera._activeMeshes.push(mesh);
  11947. mesh._activate(this._renderId);
  11948. this._activeMesh(meshLOD);
  11949. }
  11950. }
  11951. // Particle systems
  11952. var beforeParticlesDate = BABYLON.Tools.Now;
  11953. if (this.particlesEnabled) {
  11954. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  11955. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  11956. var particleSystem = this.particleSystems[particleIndex];
  11957. if (!particleSystem.isStarted()) {
  11958. continue;
  11959. }
  11960. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  11961. this._activeParticleSystems.push(particleSystem);
  11962. particleSystem.animate();
  11963. }
  11964. }
  11965. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  11966. }
  11967. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11968. };
  11969. Scene.prototype._activeMesh = function (mesh) {
  11970. if (mesh.skeleton && this.skeletonsEnabled) {
  11971. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  11972. }
  11973. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  11974. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  11975. }
  11976. if (mesh && mesh.subMeshes) {
  11977. // Submeshes Octrees
  11978. var len;
  11979. var subMeshes;
  11980. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  11981. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  11982. len = intersections.length;
  11983. subMeshes = intersections.data;
  11984. }
  11985. else {
  11986. subMeshes = mesh.subMeshes;
  11987. len = subMeshes.length;
  11988. }
  11989. for (var subIndex = 0; subIndex < len; subIndex++) {
  11990. var subMesh = subMeshes[subIndex];
  11991. this._evaluateSubMesh(subMesh, mesh);
  11992. }
  11993. }
  11994. };
  11995. Scene.prototype.updateTransformMatrix = function (force) {
  11996. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  11997. };
  11998. Scene.prototype._renderForCamera = function (camera) {
  11999. var engine = this._engine;
  12000. this.activeCamera = camera;
  12001. if (!this.activeCamera)
  12002. throw new Error("Active camera not set");
  12003. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12004. // Viewport
  12005. engine.setViewport(this.activeCamera.viewport);
  12006. // Camera
  12007. this._renderId++;
  12008. this.updateTransformMatrix();
  12009. if (this.beforeCameraRender) {
  12010. this.beforeCameraRender(this.activeCamera);
  12011. }
  12012. // Meshes
  12013. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  12014. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  12015. this._evaluateActiveMeshes();
  12016. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  12017. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  12018. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  12019. var skeleton = this._activeSkeletons.data[skeletonIndex];
  12020. skeleton.prepare();
  12021. }
  12022. // Render targets
  12023. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12024. if (this.renderTargetsEnabled) {
  12025. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12026. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  12027. var renderTarget = this._renderTargets.data[renderIndex];
  12028. if (renderTarget._shouldRender()) {
  12029. this._renderId++;
  12030. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  12031. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  12032. }
  12033. }
  12034. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12035. this._renderId++;
  12036. }
  12037. if (this._renderTargets.length > 0) {
  12038. engine.restoreDefaultFramebuffer();
  12039. }
  12040. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12041. // Prepare Frame
  12042. this.postProcessManager._prepareFrame();
  12043. var beforeRenderDate = BABYLON.Tools.Now;
  12044. // Backgrounds
  12045. if (this.layers.length) {
  12046. engine.setDepthBuffer(false);
  12047. var layerIndex;
  12048. var layer;
  12049. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12050. layer = this.layers[layerIndex];
  12051. if (layer.isBackground) {
  12052. layer.render();
  12053. }
  12054. }
  12055. engine.setDepthBuffer(true);
  12056. }
  12057. // Render
  12058. BABYLON.Tools.StartPerformanceCounter("Main render");
  12059. this._renderingManager.render(null, null, true, true);
  12060. BABYLON.Tools.EndPerformanceCounter("Main render");
  12061. // Bounding boxes
  12062. this._boundingBoxRenderer.render();
  12063. // Lens flares
  12064. if (this.lensFlaresEnabled) {
  12065. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12066. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  12067. this.lensFlareSystems[lensFlareSystemIndex].render();
  12068. }
  12069. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12070. }
  12071. // Foregrounds
  12072. if (this.layers.length) {
  12073. engine.setDepthBuffer(false);
  12074. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12075. layer = this.layers[layerIndex];
  12076. if (!layer.isBackground) {
  12077. layer.render();
  12078. }
  12079. }
  12080. engine.setDepthBuffer(true);
  12081. }
  12082. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  12083. // Finalize frame
  12084. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  12085. // Update camera
  12086. this.activeCamera._updateFromScene();
  12087. // Reset some special arrays
  12088. this._renderTargets.reset();
  12089. if (this.afterCameraRender) {
  12090. this.afterCameraRender(this.activeCamera);
  12091. }
  12092. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12093. };
  12094. Scene.prototype._processSubCameras = function (camera) {
  12095. if (camera.subCameras.length === 0) {
  12096. this._renderForCamera(camera);
  12097. return;
  12098. }
  12099. for (var index = 0; index < camera.subCameras.length; index++) {
  12100. this._renderForCamera(camera.subCameras[index]);
  12101. }
  12102. this.activeCamera = camera;
  12103. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  12104. // Update camera
  12105. this.activeCamera._updateFromScene();
  12106. };
  12107. Scene.prototype._checkIntersections = function () {
  12108. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  12109. var sourceMesh = this._meshesForIntersections.data[index];
  12110. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  12111. var action = sourceMesh.actionManager.actions[actionIndex];
  12112. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12113. var parameters = action.getTriggerParameter();
  12114. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  12115. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  12116. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  12117. if (areIntersecting && currentIntersectionInProgress === -1) {
  12118. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  12119. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  12120. sourceMesh._intersectionsInProgress.push(otherMesh);
  12121. }
  12122. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12123. sourceMesh._intersectionsInProgress.push(otherMesh);
  12124. }
  12125. }
  12126. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  12127. //They intersected, and now they don't.
  12128. //is this trigger an exit trigger? execute an event.
  12129. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12130. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  12131. }
  12132. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  12133. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12134. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  12135. }
  12136. }
  12137. }
  12138. }
  12139. }
  12140. };
  12141. Scene.prototype.render = function () {
  12142. var startDate = BABYLON.Tools.Now;
  12143. this._particlesDuration = 0;
  12144. this._spritesDuration = 0;
  12145. this._activeParticles = 0;
  12146. this._renderDuration = 0;
  12147. this._renderTargetsDuration = 0;
  12148. this._evaluateActiveMeshesDuration = 0;
  12149. this._totalVertices = 0;
  12150. this._activeIndices = 0;
  12151. this._activeBones = 0;
  12152. this.getEngine().resetDrawCalls();
  12153. this._meshesForIntersections.reset();
  12154. this.resetCachedMaterial();
  12155. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  12156. // Actions
  12157. if (this.actionManager) {
  12158. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  12159. }
  12160. //Simplification Queue
  12161. if (!this.simplificationQueue.running) {
  12162. this.simplificationQueue.executeNext();
  12163. }
  12164. // Before render
  12165. if (this.beforeRender) {
  12166. this.beforeRender();
  12167. }
  12168. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  12169. this._onBeforeRenderCallbacks[callbackIndex]();
  12170. }
  12171. // Animations
  12172. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  12173. this._animationRatio = deltaTime * (60.0 / 1000.0);
  12174. this._animate();
  12175. // Physics
  12176. if (this._physicsEngine) {
  12177. BABYLON.Tools.StartPerformanceCounter("Physics");
  12178. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  12179. BABYLON.Tools.EndPerformanceCounter("Physics");
  12180. }
  12181. // Customs render targets
  12182. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12183. var engine = this.getEngine();
  12184. var currentActiveCamera = this.activeCamera;
  12185. if (this.renderTargetsEnabled) {
  12186. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12187. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  12188. var renderTarget = this.customRenderTargets[customIndex];
  12189. if (renderTarget._shouldRender()) {
  12190. this._renderId++;
  12191. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  12192. if (!this.activeCamera)
  12193. throw new Error("Active camera not set");
  12194. // Viewport
  12195. engine.setViewport(this.activeCamera.viewport);
  12196. // Camera
  12197. this.updateTransformMatrix();
  12198. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  12199. }
  12200. }
  12201. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12202. this._renderId++;
  12203. }
  12204. if (this.customRenderTargets.length > 0) {
  12205. engine.restoreDefaultFramebuffer();
  12206. }
  12207. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12208. this.activeCamera = currentActiveCamera;
  12209. // Procedural textures
  12210. if (this.proceduralTexturesEnabled) {
  12211. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12212. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  12213. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  12214. if (proceduralTexture._shouldRender()) {
  12215. proceduralTexture.render();
  12216. }
  12217. }
  12218. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12219. }
  12220. // Clear
  12221. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  12222. // Shadows
  12223. if (this.shadowsEnabled) {
  12224. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  12225. var light = this.lights[lightIndex];
  12226. var shadowGenerator = light.getShadowGenerator();
  12227. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  12228. this._renderTargets.push(shadowGenerator.getShadowMap());
  12229. }
  12230. }
  12231. }
  12232. // Depth renderer
  12233. if (this._depthRenderer) {
  12234. this._renderTargets.push(this._depthRenderer.getDepthMap());
  12235. }
  12236. // RenderPipeline
  12237. this.postProcessRenderPipelineManager.update();
  12238. // Multi-cameras?
  12239. if (this.activeCameras.length > 0) {
  12240. var currentRenderId = this._renderId;
  12241. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  12242. this._renderId = currentRenderId;
  12243. this._processSubCameras(this.activeCameras[cameraIndex]);
  12244. }
  12245. }
  12246. else {
  12247. if (!this.activeCamera) {
  12248. throw new Error("No camera defined");
  12249. }
  12250. this._processSubCameras(this.activeCamera);
  12251. }
  12252. // Intersection checks
  12253. this._checkIntersections();
  12254. // Update the audio listener attached to the camera
  12255. this._updateAudioParameters();
  12256. // After render
  12257. if (this.afterRender) {
  12258. this.afterRender();
  12259. }
  12260. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  12261. this._onAfterRenderCallbacks[callbackIndex]();
  12262. }
  12263. for (var index = 0; index < this._toBeDisposed.length; index++) {
  12264. this._toBeDisposed.data[index].dispose();
  12265. this._toBeDisposed[index] = null;
  12266. }
  12267. this._toBeDisposed.reset();
  12268. if (this.dumpNextRenderTargets) {
  12269. this.dumpNextRenderTargets = false;
  12270. }
  12271. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  12272. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  12273. };
  12274. Scene.prototype._updateAudioParameters = function () {
  12275. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  12276. return;
  12277. }
  12278. var listeningCamera;
  12279. var audioEngine = BABYLON.Engine.audioEngine;
  12280. if (this.activeCameras.length > 0) {
  12281. listeningCamera = this.activeCameras[0];
  12282. }
  12283. else {
  12284. listeningCamera = this.activeCamera;
  12285. }
  12286. if (listeningCamera && audioEngine.canUseWebAudio) {
  12287. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  12288. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  12289. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  12290. cameraDirection.normalize();
  12291. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  12292. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12293. var sound = this.mainSoundTrack.soundCollection[i];
  12294. if (sound.useCustomAttenuation) {
  12295. sound.updateDistanceFromListener();
  12296. }
  12297. }
  12298. for (i = 0; i < this.soundTracks.length; i++) {
  12299. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12300. sound = this.soundTracks[i].soundCollection[j];
  12301. if (sound.useCustomAttenuation) {
  12302. sound.updateDistanceFromListener();
  12303. }
  12304. }
  12305. }
  12306. }
  12307. };
  12308. Object.defineProperty(Scene.prototype, "audioEnabled", {
  12309. // Audio
  12310. get: function () {
  12311. return this._audioEnabled;
  12312. },
  12313. set: function (value) {
  12314. this._audioEnabled = value;
  12315. if (this._audioEnabled) {
  12316. this._enableAudio();
  12317. }
  12318. else {
  12319. this._disableAudio();
  12320. }
  12321. },
  12322. enumerable: true,
  12323. configurable: true
  12324. });
  12325. Scene.prototype._disableAudio = function () {
  12326. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12327. this.mainSoundTrack.soundCollection[i].pause();
  12328. }
  12329. for (i = 0; i < this.soundTracks.length; i++) {
  12330. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12331. this.soundTracks[i].soundCollection[j].pause();
  12332. }
  12333. }
  12334. };
  12335. Scene.prototype._enableAudio = function () {
  12336. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12337. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  12338. this.mainSoundTrack.soundCollection[i].play();
  12339. }
  12340. }
  12341. for (i = 0; i < this.soundTracks.length; i++) {
  12342. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12343. if (this.soundTracks[i].soundCollection[j].isPaused) {
  12344. this.soundTracks[i].soundCollection[j].play();
  12345. }
  12346. }
  12347. }
  12348. };
  12349. Object.defineProperty(Scene.prototype, "headphone", {
  12350. get: function () {
  12351. return this._headphone;
  12352. },
  12353. set: function (value) {
  12354. this._headphone = value;
  12355. if (this._headphone) {
  12356. this._switchAudioModeForHeadphones();
  12357. }
  12358. else {
  12359. this._switchAudioModeForNormalSpeakers();
  12360. }
  12361. },
  12362. enumerable: true,
  12363. configurable: true
  12364. });
  12365. Scene.prototype._switchAudioModeForHeadphones = function () {
  12366. this.mainSoundTrack.switchPanningModelToHRTF();
  12367. for (var i = 0; i < this.soundTracks.length; i++) {
  12368. this.soundTracks[i].switchPanningModelToHRTF();
  12369. }
  12370. };
  12371. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  12372. this.mainSoundTrack.switchPanningModelToEqualPower();
  12373. for (var i = 0; i < this.soundTracks.length; i++) {
  12374. this.soundTracks[i].switchPanningModelToEqualPower();
  12375. }
  12376. };
  12377. Scene.prototype.enableDepthRenderer = function () {
  12378. if (this._depthRenderer) {
  12379. return this._depthRenderer;
  12380. }
  12381. this._depthRenderer = new BABYLON.DepthRenderer(this);
  12382. return this._depthRenderer;
  12383. };
  12384. Scene.prototype.disableDepthRenderer = function () {
  12385. if (!this._depthRenderer) {
  12386. return;
  12387. }
  12388. this._depthRenderer.dispose();
  12389. this._depthRenderer = null;
  12390. };
  12391. Scene.prototype.dispose = function () {
  12392. this.beforeRender = null;
  12393. this.afterRender = null;
  12394. this.skeletons = [];
  12395. this._boundingBoxRenderer.dispose();
  12396. if (this._depthRenderer) {
  12397. this._depthRenderer.dispose();
  12398. }
  12399. // Debug layer
  12400. this.debugLayer.hide();
  12401. // Events
  12402. if (this.onDispose) {
  12403. this.onDispose();
  12404. }
  12405. this._onBeforeRenderCallbacks = [];
  12406. this._onAfterRenderCallbacks = [];
  12407. this.detachControl();
  12408. // Release sounds & sounds tracks
  12409. this.disposeSounds();
  12410. // Detach cameras
  12411. var canvas = this._engine.getRenderingCanvas();
  12412. var index;
  12413. for (index = 0; index < this.cameras.length; index++) {
  12414. this.cameras[index].detachControl(canvas);
  12415. }
  12416. while (this.lights.length) {
  12417. this.lights[0].dispose();
  12418. }
  12419. while (this.meshes.length) {
  12420. this.meshes[0].dispose(true);
  12421. }
  12422. while (this.cameras.length) {
  12423. this.cameras[0].dispose();
  12424. }
  12425. while (this.materials.length) {
  12426. this.materials[0].dispose();
  12427. }
  12428. while (this.particleSystems.length) {
  12429. this.particleSystems[0].dispose();
  12430. }
  12431. while (this.spriteManagers.length) {
  12432. this.spriteManagers[0].dispose();
  12433. }
  12434. while (this.layers.length) {
  12435. this.layers[0].dispose();
  12436. }
  12437. while (this.textures.length) {
  12438. this.textures[0].dispose();
  12439. }
  12440. // Post-processes
  12441. this.postProcessManager.dispose();
  12442. // Physics
  12443. if (this._physicsEngine) {
  12444. this.disablePhysicsEngine();
  12445. }
  12446. // Remove from engine
  12447. index = this._engine.scenes.indexOf(this);
  12448. if (index > -1) {
  12449. this._engine.scenes.splice(index, 1);
  12450. }
  12451. this._engine.wipeCaches();
  12452. };
  12453. // Release sounds & sounds tracks
  12454. Scene.prototype.disposeSounds = function () {
  12455. this.mainSoundTrack.dispose();
  12456. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  12457. this.soundTracks[scIndex].dispose();
  12458. }
  12459. };
  12460. // Octrees
  12461. Scene.prototype.getWorldExtends = function () {
  12462. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12463. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  12464. for (var index = 0; index < this.meshes.length; index++) {
  12465. var mesh = this.meshes[index];
  12466. mesh.computeWorldMatrix(true);
  12467. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  12468. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  12469. BABYLON.Tools.CheckExtends(minBox, min, max);
  12470. BABYLON.Tools.CheckExtends(maxBox, min, max);
  12471. }
  12472. return {
  12473. min: min,
  12474. max: max
  12475. };
  12476. };
  12477. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  12478. if (maxCapacity === void 0) { maxCapacity = 64; }
  12479. if (maxDepth === void 0) { maxDepth = 2; }
  12480. if (!this._selectionOctree) {
  12481. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  12482. }
  12483. var worldExtends = this.getWorldExtends();
  12484. // Update octree
  12485. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  12486. return this._selectionOctree;
  12487. };
  12488. // Picking
  12489. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  12490. var engine = this._engine;
  12491. if (!camera) {
  12492. if (!this.activeCamera)
  12493. throw new Error("Active camera not set");
  12494. camera = this.activeCamera;
  12495. }
  12496. var cameraViewport = camera.viewport;
  12497. var viewport = cameraViewport.toGlobal(engine);
  12498. // Moving coordinates to local viewport world
  12499. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  12500. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  12501. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  12502. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  12503. };
  12504. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  12505. var pickingInfo = null;
  12506. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  12507. var mesh = this.meshes[meshIndex];
  12508. if (predicate) {
  12509. if (!predicate(mesh)) {
  12510. continue;
  12511. }
  12512. }
  12513. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  12514. continue;
  12515. }
  12516. var world = mesh.getWorldMatrix();
  12517. var ray = rayFunction(world);
  12518. var result = mesh.intersects(ray, fastCheck);
  12519. if (!result || !result.hit)
  12520. continue;
  12521. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  12522. continue;
  12523. pickingInfo = result;
  12524. if (fastCheck) {
  12525. break;
  12526. }
  12527. }
  12528. return pickingInfo || new BABYLON.PickingInfo();
  12529. };
  12530. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  12531. var _this = this;
  12532. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  12533. /// <param name="x">X position on screen</param>
  12534. /// <param name="y">Y position on screen</param>
  12535. /// <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>
  12536. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  12537. /// <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>
  12538. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  12539. };
  12540. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  12541. var _this = this;
  12542. return this._internalPick(function (world) {
  12543. if (!_this._pickWithRayInverseMatrix) {
  12544. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  12545. }
  12546. world.invertToRef(_this._pickWithRayInverseMatrix);
  12547. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  12548. }, predicate, fastCheck);
  12549. };
  12550. Scene.prototype.setPointerOverMesh = function (mesh) {
  12551. if (this._pointerOverMesh === mesh) {
  12552. return;
  12553. }
  12554. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  12555. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  12556. }
  12557. this._pointerOverMesh = mesh;
  12558. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  12559. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  12560. }
  12561. };
  12562. Scene.prototype.getPointerOverMesh = function () {
  12563. return this._pointerOverMesh;
  12564. };
  12565. // Physics
  12566. Scene.prototype.getPhysicsEngine = function () {
  12567. return this._physicsEngine;
  12568. };
  12569. Scene.prototype.enablePhysics = function (gravity, plugin) {
  12570. if (this._physicsEngine) {
  12571. return true;
  12572. }
  12573. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  12574. if (!this._physicsEngine.isSupported()) {
  12575. this._physicsEngine = null;
  12576. return false;
  12577. }
  12578. this._physicsEngine._initialize(gravity);
  12579. return true;
  12580. };
  12581. Scene.prototype.disablePhysicsEngine = function () {
  12582. if (!this._physicsEngine) {
  12583. return;
  12584. }
  12585. this._physicsEngine.dispose();
  12586. this._physicsEngine = undefined;
  12587. };
  12588. Scene.prototype.isPhysicsEnabled = function () {
  12589. return this._physicsEngine !== undefined;
  12590. };
  12591. Scene.prototype.setGravity = function (gravity) {
  12592. if (!this._physicsEngine) {
  12593. return;
  12594. }
  12595. this._physicsEngine._setGravity(gravity);
  12596. };
  12597. Scene.prototype.createCompoundImpostor = function (parts, options) {
  12598. if (parts.parts) {
  12599. options = parts;
  12600. parts = parts.parts;
  12601. }
  12602. if (!this._physicsEngine) {
  12603. return null;
  12604. }
  12605. for (var index = 0; index < parts.length; index++) {
  12606. var mesh = parts[index].mesh;
  12607. mesh._physicImpostor = parts[index].impostor;
  12608. mesh._physicsMass = options.mass / parts.length;
  12609. mesh._physicsFriction = options.friction;
  12610. mesh._physicRestitution = options.restitution;
  12611. }
  12612. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  12613. };
  12614. Scene.prototype.deleteCompoundImpostor = function (compound) {
  12615. for (var index = 0; index < compound.parts.length; index++) {
  12616. var mesh = compound.parts[index].mesh;
  12617. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  12618. this._physicsEngine._unregisterMesh(mesh);
  12619. }
  12620. };
  12621. // Misc.
  12622. Scene.prototype.createDefaultCameraOrLight = function () {
  12623. // Light
  12624. if (this.lights.length === 0) {
  12625. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  12626. }
  12627. // Camera
  12628. if (!this.activeCamera) {
  12629. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  12630. // Compute position
  12631. var worldExtends = this.getWorldExtends();
  12632. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  12633. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  12634. camera.setTarget(worldCenter);
  12635. this.activeCamera = camera;
  12636. }
  12637. };
  12638. // Tags
  12639. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  12640. if (tagsQuery === undefined) {
  12641. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  12642. return list;
  12643. }
  12644. var listByTags = [];
  12645. forEach = forEach || (function (item) {
  12646. return;
  12647. });
  12648. for (var i in list) {
  12649. var item = list[i];
  12650. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  12651. listByTags.push(item);
  12652. forEach(item);
  12653. }
  12654. }
  12655. return listByTags;
  12656. };
  12657. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  12658. return this._getByTags(this.meshes, tagsQuery, forEach);
  12659. };
  12660. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  12661. return this._getByTags(this.cameras, tagsQuery, forEach);
  12662. };
  12663. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  12664. return this._getByTags(this.lights, tagsQuery, forEach);
  12665. };
  12666. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  12667. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  12668. };
  12669. // Statics
  12670. Scene._FOGMODE_NONE = 0;
  12671. Scene._FOGMODE_EXP = 1;
  12672. Scene._FOGMODE_EXP2 = 2;
  12673. Scene._FOGMODE_LINEAR = 3;
  12674. Scene.MinDeltaTime = 1.0;
  12675. Scene.MaxDeltaTime = 1000.0;
  12676. return Scene;
  12677. })();
  12678. BABYLON.Scene = Scene;
  12679. })(BABYLON || (BABYLON = {}));
  12680. //# sourceMappingURL=babylon.scene.js.map
  12681. var BABYLON;
  12682. (function (BABYLON) {
  12683. var VertexBuffer = (function () {
  12684. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  12685. if (engine instanceof BABYLON.Mesh) {
  12686. this._engine = engine.getScene().getEngine();
  12687. }
  12688. else {
  12689. this._engine = engine;
  12690. }
  12691. this._updatable = updatable;
  12692. this._data = data;
  12693. if (!postponeInternalCreation) {
  12694. this.create();
  12695. }
  12696. this._kind = kind;
  12697. if (stride) {
  12698. this._strideSize = stride;
  12699. return;
  12700. }
  12701. switch (kind) {
  12702. case VertexBuffer.PositionKind:
  12703. this._strideSize = 3;
  12704. break;
  12705. case VertexBuffer.NormalKind:
  12706. this._strideSize = 3;
  12707. break;
  12708. case VertexBuffer.UVKind:
  12709. this._strideSize = 2;
  12710. break;
  12711. case VertexBuffer.UV2Kind:
  12712. this._strideSize = 2;
  12713. break;
  12714. case VertexBuffer.ColorKind:
  12715. this._strideSize = 4;
  12716. break;
  12717. case VertexBuffer.MatricesIndicesKind:
  12718. this._strideSize = 4;
  12719. break;
  12720. case VertexBuffer.MatricesWeightsKind:
  12721. this._strideSize = 4;
  12722. break;
  12723. }
  12724. }
  12725. // Properties
  12726. VertexBuffer.prototype.isUpdatable = function () {
  12727. return this._updatable;
  12728. };
  12729. VertexBuffer.prototype.getData = function () {
  12730. return this._data;
  12731. };
  12732. VertexBuffer.prototype.getBuffer = function () {
  12733. return this._buffer;
  12734. };
  12735. VertexBuffer.prototype.getStrideSize = function () {
  12736. return this._strideSize;
  12737. };
  12738. // Methods
  12739. VertexBuffer.prototype.create = function (data) {
  12740. if (!data && this._buffer) {
  12741. return; // nothing to do
  12742. }
  12743. data = data || this._data;
  12744. if (!this._buffer) {
  12745. if (this._updatable) {
  12746. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  12747. }
  12748. else {
  12749. this._buffer = this._engine.createVertexBuffer(data);
  12750. }
  12751. }
  12752. if (this._updatable) {
  12753. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  12754. this._data = data;
  12755. }
  12756. };
  12757. VertexBuffer.prototype.update = function (data) {
  12758. this.create(data);
  12759. };
  12760. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  12761. if (!this._buffer) {
  12762. return;
  12763. }
  12764. if (this._updatable) {
  12765. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  12766. this._data = null;
  12767. }
  12768. };
  12769. VertexBuffer.prototype.dispose = function () {
  12770. if (!this._buffer) {
  12771. return;
  12772. }
  12773. if (this._engine._releaseBuffer(this._buffer)) {
  12774. this._buffer = null;
  12775. }
  12776. };
  12777. Object.defineProperty(VertexBuffer, "PositionKind", {
  12778. get: function () {
  12779. return VertexBuffer._PositionKind;
  12780. },
  12781. enumerable: true,
  12782. configurable: true
  12783. });
  12784. Object.defineProperty(VertexBuffer, "NormalKind", {
  12785. get: function () {
  12786. return VertexBuffer._NormalKind;
  12787. },
  12788. enumerable: true,
  12789. configurable: true
  12790. });
  12791. Object.defineProperty(VertexBuffer, "UVKind", {
  12792. get: function () {
  12793. return VertexBuffer._UVKind;
  12794. },
  12795. enumerable: true,
  12796. configurable: true
  12797. });
  12798. Object.defineProperty(VertexBuffer, "UV2Kind", {
  12799. get: function () {
  12800. return VertexBuffer._UV2Kind;
  12801. },
  12802. enumerable: true,
  12803. configurable: true
  12804. });
  12805. Object.defineProperty(VertexBuffer, "ColorKind", {
  12806. get: function () {
  12807. return VertexBuffer._ColorKind;
  12808. },
  12809. enumerable: true,
  12810. configurable: true
  12811. });
  12812. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  12813. get: function () {
  12814. return VertexBuffer._MatricesIndicesKind;
  12815. },
  12816. enumerable: true,
  12817. configurable: true
  12818. });
  12819. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  12820. get: function () {
  12821. return VertexBuffer._MatricesWeightsKind;
  12822. },
  12823. enumerable: true,
  12824. configurable: true
  12825. });
  12826. // Enums
  12827. VertexBuffer._PositionKind = "position";
  12828. VertexBuffer._NormalKind = "normal";
  12829. VertexBuffer._UVKind = "uv";
  12830. VertexBuffer._UV2Kind = "uv2";
  12831. VertexBuffer._ColorKind = "color";
  12832. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  12833. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  12834. return VertexBuffer;
  12835. })();
  12836. BABYLON.VertexBuffer = VertexBuffer;
  12837. })(BABYLON || (BABYLON = {}));
  12838. //# sourceMappingURL=babylon.vertexBuffer.js.map
  12839. var __extends = this.__extends || function (d, b) {
  12840. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12841. function __() { this.constructor = d; }
  12842. __.prototype = b.prototype;
  12843. d.prototype = new __();
  12844. };
  12845. var BABYLON;
  12846. (function (BABYLON) {
  12847. /**
  12848. * Creates an instance based on a source mesh.
  12849. */
  12850. var InstancedMesh = (function (_super) {
  12851. __extends(InstancedMesh, _super);
  12852. function InstancedMesh(name, source) {
  12853. _super.call(this, name, source.getScene());
  12854. source.instances.push(this);
  12855. this._sourceMesh = source;
  12856. this.position.copyFrom(source.position);
  12857. this.rotation.copyFrom(source.rotation);
  12858. this.scaling.copyFrom(source.scaling);
  12859. if (source.rotationQuaternion) {
  12860. this.rotationQuaternion = source.rotationQuaternion.clone();
  12861. }
  12862. this.infiniteDistance = source.infiniteDistance;
  12863. this.setPivotMatrix(source.getPivotMatrix());
  12864. this.refreshBoundingInfo();
  12865. this._syncSubMeshes();
  12866. }
  12867. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  12868. // Methods
  12869. get: function () {
  12870. return this._sourceMesh.receiveShadows;
  12871. },
  12872. enumerable: true,
  12873. configurable: true
  12874. });
  12875. Object.defineProperty(InstancedMesh.prototype, "material", {
  12876. get: function () {
  12877. return this._sourceMesh.material;
  12878. },
  12879. enumerable: true,
  12880. configurable: true
  12881. });
  12882. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  12883. get: function () {
  12884. return this._sourceMesh.visibility;
  12885. },
  12886. enumerable: true,
  12887. configurable: true
  12888. });
  12889. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  12890. get: function () {
  12891. return this._sourceMesh.skeleton;
  12892. },
  12893. enumerable: true,
  12894. configurable: true
  12895. });
  12896. InstancedMesh.prototype.getTotalVertices = function () {
  12897. return this._sourceMesh.getTotalVertices();
  12898. };
  12899. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  12900. get: function () {
  12901. return this._sourceMesh;
  12902. },
  12903. enumerable: true,
  12904. configurable: true
  12905. });
  12906. InstancedMesh.prototype.getVerticesData = function (kind) {
  12907. return this._sourceMesh.getVerticesData(kind);
  12908. };
  12909. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  12910. return this._sourceMesh.isVerticesDataPresent(kind);
  12911. };
  12912. InstancedMesh.prototype.getIndices = function () {
  12913. return this._sourceMesh.getIndices();
  12914. };
  12915. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  12916. get: function () {
  12917. return this._sourceMesh._positions;
  12918. },
  12919. enumerable: true,
  12920. configurable: true
  12921. });
  12922. InstancedMesh.prototype.refreshBoundingInfo = function () {
  12923. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12924. if (data) {
  12925. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  12926. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12927. }
  12928. this._updateBoundingInfo();
  12929. };
  12930. InstancedMesh.prototype._preActivate = function () {
  12931. if (this._currentLOD) {
  12932. this._currentLOD._preActivate();
  12933. }
  12934. };
  12935. InstancedMesh.prototype._activate = function (renderId) {
  12936. if (this._currentLOD) {
  12937. this._currentLOD._registerInstanceForRenderId(this, renderId);
  12938. }
  12939. };
  12940. InstancedMesh.prototype.getLOD = function (camera) {
  12941. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  12942. if (this._currentLOD === this.sourceMesh) {
  12943. return this;
  12944. }
  12945. return this._currentLOD;
  12946. };
  12947. InstancedMesh.prototype._syncSubMeshes = function () {
  12948. this.releaseSubMeshes();
  12949. if (this._sourceMesh.subMeshes) {
  12950. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  12951. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  12952. }
  12953. }
  12954. };
  12955. InstancedMesh.prototype._generatePointsArray = function () {
  12956. return this._sourceMesh._generatePointsArray();
  12957. };
  12958. // Clone
  12959. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12960. var result = this._sourceMesh.createInstance(name);
  12961. // Deep copy
  12962. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  12963. // Bounding info
  12964. this.refreshBoundingInfo();
  12965. // Parent
  12966. if (newParent) {
  12967. result.parent = newParent;
  12968. }
  12969. if (!doNotCloneChildren) {
  12970. for (var index = 0; index < this.getScene().meshes.length; index++) {
  12971. var mesh = this.getScene().meshes[index];
  12972. if (mesh.parent === this) {
  12973. mesh.clone(mesh.name, result);
  12974. }
  12975. }
  12976. }
  12977. result.computeWorldMatrix(true);
  12978. return result;
  12979. };
  12980. // Dispoe
  12981. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  12982. // Remove from mesh
  12983. var index = this._sourceMesh.instances.indexOf(this);
  12984. this._sourceMesh.instances.splice(index, 1);
  12985. _super.prototype.dispose.call(this, doNotRecurse);
  12986. };
  12987. return InstancedMesh;
  12988. })(BABYLON.AbstractMesh);
  12989. BABYLON.InstancedMesh = InstancedMesh;
  12990. })(BABYLON || (BABYLON = {}));
  12991. //# sourceMappingURL=babylon.instancedMesh.js.map
  12992. var __extends = this.__extends || function (d, b) {
  12993. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12994. function __() { this.constructor = d; }
  12995. __.prototype = b.prototype;
  12996. d.prototype = new __();
  12997. };
  12998. var BABYLON;
  12999. (function (BABYLON) {
  13000. var _InstancesBatch = (function () {
  13001. function _InstancesBatch() {
  13002. this.mustReturn = false;
  13003. this.visibleInstances = new Array();
  13004. this.renderSelf = new Array();
  13005. }
  13006. return _InstancesBatch;
  13007. })();
  13008. BABYLON._InstancesBatch = _InstancesBatch;
  13009. var Mesh = (function (_super) {
  13010. __extends(Mesh, _super);
  13011. /**
  13012. * @constructor
  13013. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  13014. * @param {Scene} scene - The scene to add this mesh to.
  13015. * @param {Node} parent - The parent of this mesh, if it has one
  13016. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  13017. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  13018. * When false, achieved by calling a clone(), also passing False.
  13019. * This will make creation of children, recursive.
  13020. */
  13021. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  13022. if (parent === void 0) { parent = null; }
  13023. _super.call(this, name, scene);
  13024. // Members
  13025. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  13026. this.instances = new Array();
  13027. this._LODLevels = new Array();
  13028. this._onBeforeRenderCallbacks = new Array();
  13029. this._onAfterRenderCallbacks = new Array();
  13030. this._visibleInstances = {};
  13031. this._renderIdForInstances = new Array();
  13032. this._batchCache = new _InstancesBatch();
  13033. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  13034. this._sideOrientation = Mesh._DEFAULTSIDE;
  13035. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  13036. if (source) {
  13037. // Geometry
  13038. if (source._geometry) {
  13039. source._geometry.applyToMesh(this);
  13040. }
  13041. // Deep copy
  13042. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  13043. // Material
  13044. this.material = source.material;
  13045. if (!doNotCloneChildren) {
  13046. for (var index = 0; index < scene.meshes.length; index++) {
  13047. var mesh = scene.meshes[index];
  13048. if (mesh.parent === source) {
  13049. // doNotCloneChildren is always going to be False
  13050. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  13051. }
  13052. }
  13053. }
  13054. for (index = 0; index < scene.particleSystems.length; index++) {
  13055. var system = scene.particleSystems[index];
  13056. if (system.emitter === source) {
  13057. system.clone(system.name, this);
  13058. }
  13059. }
  13060. this.computeWorldMatrix(true);
  13061. }
  13062. // Parent
  13063. if (parent !== null) {
  13064. this.parent = parent;
  13065. }
  13066. }
  13067. Object.defineProperty(Mesh, "FRONTSIDE", {
  13068. get: function () {
  13069. return Mesh._FRONTSIDE;
  13070. },
  13071. enumerable: true,
  13072. configurable: true
  13073. });
  13074. Object.defineProperty(Mesh, "BACKSIDE", {
  13075. get: function () {
  13076. return Mesh._BACKSIDE;
  13077. },
  13078. enumerable: true,
  13079. configurable: true
  13080. });
  13081. Object.defineProperty(Mesh, "DOUBLESIDE", {
  13082. get: function () {
  13083. return Mesh._DOUBLESIDE;
  13084. },
  13085. enumerable: true,
  13086. configurable: true
  13087. });
  13088. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  13089. get: function () {
  13090. return Mesh._DEFAULTSIDE;
  13091. },
  13092. enumerable: true,
  13093. configurable: true
  13094. });
  13095. Object.defineProperty(Mesh, "NO_CAP", {
  13096. get: function () {
  13097. return Mesh._NO_CAP;
  13098. },
  13099. enumerable: true,
  13100. configurable: true
  13101. });
  13102. Object.defineProperty(Mesh, "CAP_START", {
  13103. get: function () {
  13104. return Mesh._CAP_START;
  13105. },
  13106. enumerable: true,
  13107. configurable: true
  13108. });
  13109. Object.defineProperty(Mesh, "CAP_END", {
  13110. get: function () {
  13111. return Mesh._CAP_END;
  13112. },
  13113. enumerable: true,
  13114. configurable: true
  13115. });
  13116. Object.defineProperty(Mesh, "CAP_ALL", {
  13117. get: function () {
  13118. return Mesh._CAP_ALL;
  13119. },
  13120. enumerable: true,
  13121. configurable: true
  13122. });
  13123. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  13124. // Methods
  13125. get: function () {
  13126. return this._LODLevels.length > 0;
  13127. },
  13128. enumerable: true,
  13129. configurable: true
  13130. });
  13131. Mesh.prototype._sortLODLevels = function () {
  13132. this._LODLevels.sort(function (a, b) {
  13133. if (a.distance < b.distance) {
  13134. return 1;
  13135. }
  13136. if (a.distance > b.distance) {
  13137. return -1;
  13138. }
  13139. return 0;
  13140. });
  13141. };
  13142. /**
  13143. * Add a mesh as LOD level triggered at the given distance.
  13144. * @param {number} distance - the distance from the center of the object to show this level
  13145. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  13146. * @return {BABYLON.Mesh} this mesh (for chaining)
  13147. */
  13148. Mesh.prototype.addLODLevel = function (distance, mesh) {
  13149. if (mesh && mesh._masterMesh) {
  13150. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  13151. return this;
  13152. }
  13153. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  13154. this._LODLevels.push(level);
  13155. if (mesh) {
  13156. mesh._masterMesh = this;
  13157. }
  13158. this._sortLODLevels();
  13159. return this;
  13160. };
  13161. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  13162. for (var index = 0; index < this._LODLevels.length; index++) {
  13163. var level = this._LODLevels[index];
  13164. if (level.distance === distance) {
  13165. return level.mesh;
  13166. }
  13167. }
  13168. return null;
  13169. };
  13170. /**
  13171. * Remove a mesh from the LOD array
  13172. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  13173. * @return {BABYLON.Mesh} this mesh (for chaining)
  13174. */
  13175. Mesh.prototype.removeLODLevel = function (mesh) {
  13176. for (var index = 0; index < this._LODLevels.length; index++) {
  13177. if (this._LODLevels[index].mesh === mesh) {
  13178. this._LODLevels.splice(index, 1);
  13179. if (mesh) {
  13180. mesh._masterMesh = null;
  13181. }
  13182. }
  13183. }
  13184. this._sortLODLevels();
  13185. return this;
  13186. };
  13187. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  13188. if (!this._LODLevels || this._LODLevels.length === 0) {
  13189. return this;
  13190. }
  13191. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  13192. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  13193. if (this.onLODLevelSelection) {
  13194. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  13195. }
  13196. return this;
  13197. }
  13198. for (var index = 0; index < this._LODLevels.length; index++) {
  13199. var level = this._LODLevels[index];
  13200. if (level.distance < distanceToCamera) {
  13201. if (level.mesh) {
  13202. level.mesh._preActivate();
  13203. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13204. }
  13205. if (this.onLODLevelSelection) {
  13206. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  13207. }
  13208. return level.mesh;
  13209. }
  13210. }
  13211. if (this.onLODLevelSelection) {
  13212. this.onLODLevelSelection(distanceToCamera, this, this);
  13213. }
  13214. return this;
  13215. };
  13216. Object.defineProperty(Mesh.prototype, "geometry", {
  13217. get: function () {
  13218. return this._geometry;
  13219. },
  13220. enumerable: true,
  13221. configurable: true
  13222. });
  13223. Mesh.prototype.getTotalVertices = function () {
  13224. if (!this._geometry) {
  13225. return 0;
  13226. }
  13227. return this._geometry.getTotalVertices();
  13228. };
  13229. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  13230. if (!this._geometry) {
  13231. return null;
  13232. }
  13233. return this._geometry.getVerticesData(kind, copyWhenShared);
  13234. };
  13235. Mesh.prototype.getVertexBuffer = function (kind) {
  13236. if (!this._geometry) {
  13237. return undefined;
  13238. }
  13239. return this._geometry.getVertexBuffer(kind);
  13240. };
  13241. Mesh.prototype.isVerticesDataPresent = function (kind) {
  13242. if (!this._geometry) {
  13243. if (this._delayInfo) {
  13244. return this._delayInfo.indexOf(kind) !== -1;
  13245. }
  13246. return false;
  13247. }
  13248. return this._geometry.isVerticesDataPresent(kind);
  13249. };
  13250. Mesh.prototype.getVerticesDataKinds = function () {
  13251. if (!this._geometry) {
  13252. var result = [];
  13253. if (this._delayInfo) {
  13254. for (var kind in this._delayInfo) {
  13255. result.push(kind);
  13256. }
  13257. }
  13258. return result;
  13259. }
  13260. return this._geometry.getVerticesDataKinds();
  13261. };
  13262. Mesh.prototype.getTotalIndices = function () {
  13263. if (!this._geometry) {
  13264. return 0;
  13265. }
  13266. return this._geometry.getTotalIndices();
  13267. };
  13268. Mesh.prototype.getIndices = function (copyWhenShared) {
  13269. if (!this._geometry) {
  13270. return [];
  13271. }
  13272. return this._geometry.getIndices(copyWhenShared);
  13273. };
  13274. Object.defineProperty(Mesh.prototype, "isBlocked", {
  13275. get: function () {
  13276. return this._masterMesh !== null && this._masterMesh !== undefined;
  13277. },
  13278. enumerable: true,
  13279. configurable: true
  13280. });
  13281. Mesh.prototype.isReady = function () {
  13282. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13283. return false;
  13284. }
  13285. return _super.prototype.isReady.call(this);
  13286. };
  13287. Mesh.prototype.isDisposed = function () {
  13288. return this._isDisposed;
  13289. };
  13290. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  13291. get: function () {
  13292. return this._sideOrientation;
  13293. },
  13294. set: function (sideO) {
  13295. this._sideOrientation = sideO;
  13296. },
  13297. enumerable: true,
  13298. configurable: true
  13299. });
  13300. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  13301. get: function () {
  13302. return this._areNormalsFrozen;
  13303. },
  13304. enumerable: true,
  13305. configurable: true
  13306. });
  13307. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  13308. Mesh.prototype.freezeNormals = function () {
  13309. this._areNormalsFrozen = true;
  13310. };
  13311. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  13312. Mesh.prototype.unfreezeNormals = function () {
  13313. this._areNormalsFrozen = false;
  13314. };
  13315. // Methods
  13316. Mesh.prototype._preActivate = function () {
  13317. var sceneRenderId = this.getScene().getRenderId();
  13318. if (this._preActivateId === sceneRenderId) {
  13319. return;
  13320. }
  13321. this._preActivateId = sceneRenderId;
  13322. this._visibleInstances = null;
  13323. };
  13324. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  13325. if (!this._visibleInstances) {
  13326. this._visibleInstances = {};
  13327. this._visibleInstances.defaultRenderId = renderId;
  13328. this._visibleInstances.selfDefaultRenderId = this._renderId;
  13329. }
  13330. if (!this._visibleInstances[renderId]) {
  13331. this._visibleInstances[renderId] = new Array();
  13332. }
  13333. this._visibleInstances[renderId].push(instance);
  13334. };
  13335. Mesh.prototype.refreshBoundingInfo = function () {
  13336. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13337. if (data) {
  13338. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  13339. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  13340. }
  13341. if (this.subMeshes) {
  13342. for (var index = 0; index < this.subMeshes.length; index++) {
  13343. this.subMeshes[index].refreshBoundingInfo();
  13344. }
  13345. }
  13346. this._updateBoundingInfo();
  13347. };
  13348. Mesh.prototype._createGlobalSubMesh = function () {
  13349. var totalVertices = this.getTotalVertices();
  13350. if (!totalVertices || !this.getIndices()) {
  13351. return null;
  13352. }
  13353. this.releaseSubMeshes();
  13354. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  13355. };
  13356. Mesh.prototype.subdivide = function (count) {
  13357. if (count < 1) {
  13358. return;
  13359. }
  13360. var totalIndices = this.getTotalIndices();
  13361. var subdivisionSize = (totalIndices / count) | 0;
  13362. var offset = 0;
  13363. while (subdivisionSize % 3 !== 0) {
  13364. subdivisionSize++;
  13365. }
  13366. this.releaseSubMeshes();
  13367. for (var index = 0; index < count; index++) {
  13368. if (offset >= totalIndices) {
  13369. break;
  13370. }
  13371. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  13372. offset += subdivisionSize;
  13373. }
  13374. this.synchronizeInstances();
  13375. };
  13376. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13377. if (kind instanceof Array) {
  13378. var temp = data;
  13379. data = kind;
  13380. kind = temp;
  13381. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  13382. }
  13383. if (!this._geometry) {
  13384. var vertexData = new BABYLON.VertexData();
  13385. vertexData.set(data, kind);
  13386. var scene = this.getScene();
  13387. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  13388. }
  13389. else {
  13390. this._geometry.setVerticesData(kind, data, updatable, stride);
  13391. }
  13392. };
  13393. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13394. if (!this._geometry) {
  13395. return;
  13396. }
  13397. if (!makeItUnique) {
  13398. this._geometry.updateVerticesData(kind, data, updateExtends);
  13399. }
  13400. else {
  13401. this.makeGeometryUnique();
  13402. this.updateVerticesData(kind, data, updateExtends, false);
  13403. }
  13404. };
  13405. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  13406. if (!this._geometry) {
  13407. return;
  13408. }
  13409. if (!makeItUnique) {
  13410. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  13411. }
  13412. else {
  13413. this.makeGeometryUnique();
  13414. this.updateVerticesDataDirectly(kind, data, offset, false);
  13415. }
  13416. };
  13417. // Mesh positions update function :
  13418. // updates the mesh positions according to the positionFunction returned values.
  13419. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  13420. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  13421. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  13422. if (computeNormals === void 0) { computeNormals = true; }
  13423. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13424. positionFunction(positions);
  13425. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  13426. if (computeNormals) {
  13427. var indices = this.getIndices();
  13428. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13429. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  13430. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  13431. }
  13432. };
  13433. Mesh.prototype.makeGeometryUnique = function () {
  13434. if (!this._geometry) {
  13435. return;
  13436. }
  13437. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  13438. geometry.applyToMesh(this);
  13439. };
  13440. Mesh.prototype.setIndices = function (indices, totalVertices) {
  13441. if (!this._geometry) {
  13442. var vertexData = new BABYLON.VertexData();
  13443. vertexData.indices = indices;
  13444. var scene = this.getScene();
  13445. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  13446. }
  13447. else {
  13448. this._geometry.setIndices(indices, totalVertices);
  13449. }
  13450. };
  13451. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  13452. var engine = this.getScene().getEngine();
  13453. // Wireframe
  13454. var indexToBind;
  13455. switch (fillMode) {
  13456. case BABYLON.Material.PointFillMode:
  13457. indexToBind = null;
  13458. break;
  13459. case BABYLON.Material.WireFrameFillMode:
  13460. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  13461. break;
  13462. default:
  13463. case BABYLON.Material.TriangleFillMode:
  13464. indexToBind = this._geometry.getIndexBuffer();
  13465. break;
  13466. }
  13467. // VBOs
  13468. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  13469. };
  13470. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  13471. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  13472. return;
  13473. }
  13474. var engine = this.getScene().getEngine();
  13475. switch (fillMode) {
  13476. case BABYLON.Material.PointFillMode:
  13477. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  13478. break;
  13479. case BABYLON.Material.WireFrameFillMode:
  13480. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  13481. break;
  13482. default:
  13483. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  13484. }
  13485. };
  13486. Mesh.prototype.registerBeforeRender = function (func) {
  13487. this._onBeforeRenderCallbacks.push(func);
  13488. };
  13489. Mesh.prototype.unregisterBeforeRender = function (func) {
  13490. var index = this._onBeforeRenderCallbacks.indexOf(func);
  13491. if (index > -1) {
  13492. this._onBeforeRenderCallbacks.splice(index, 1);
  13493. }
  13494. };
  13495. Mesh.prototype.registerAfterRender = function (func) {
  13496. this._onAfterRenderCallbacks.push(func);
  13497. };
  13498. Mesh.prototype.unregisterAfterRender = function (func) {
  13499. var index = this._onAfterRenderCallbacks.indexOf(func);
  13500. if (index > -1) {
  13501. this._onAfterRenderCallbacks.splice(index, 1);
  13502. }
  13503. };
  13504. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  13505. var scene = this.getScene();
  13506. this._batchCache.mustReturn = false;
  13507. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  13508. this._batchCache.visibleInstances[subMeshId] = null;
  13509. if (this._visibleInstances) {
  13510. var currentRenderId = scene.getRenderId();
  13511. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  13512. var selfRenderId = this._renderId;
  13513. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  13514. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  13515. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  13516. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  13517. }
  13518. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  13519. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  13520. this._batchCache.mustReturn = true;
  13521. return this._batchCache;
  13522. }
  13523. if (currentRenderId !== selfRenderId) {
  13524. this._batchCache.renderSelf[subMeshId] = false;
  13525. }
  13526. }
  13527. this._renderIdForInstances[subMeshId] = currentRenderId;
  13528. }
  13529. return this._batchCache;
  13530. };
  13531. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  13532. var visibleInstances = batch.visibleInstances[subMesh._id];
  13533. var matricesCount = visibleInstances.length + 1;
  13534. var bufferSize = matricesCount * 16 * 4;
  13535. while (this._instancesBufferSize < bufferSize) {
  13536. this._instancesBufferSize *= 2;
  13537. }
  13538. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  13539. if (this._worldMatricesInstancesBuffer) {
  13540. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  13541. }
  13542. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  13543. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  13544. }
  13545. var offset = 0;
  13546. var instancesCount = 0;
  13547. var world = this.getWorldMatrix();
  13548. if (batch.renderSelf[subMesh._id]) {
  13549. world.copyToArray(this._worldMatricesInstancesArray, offset);
  13550. offset += 16;
  13551. instancesCount++;
  13552. }
  13553. if (visibleInstances) {
  13554. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  13555. var instance = visibleInstances[instanceIndex];
  13556. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  13557. offset += 16;
  13558. instancesCount++;
  13559. }
  13560. }
  13561. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  13562. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  13563. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  13564. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  13565. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  13566. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  13567. this._draw(subMesh, fillMode, instancesCount);
  13568. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  13569. };
  13570. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  13571. var scene = this.getScene();
  13572. var engine = scene.getEngine();
  13573. if (hardwareInstancedRendering) {
  13574. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  13575. }
  13576. else {
  13577. if (batch.renderSelf[subMesh._id]) {
  13578. // Draw
  13579. if (onBeforeDraw) {
  13580. onBeforeDraw(false, this.getWorldMatrix());
  13581. }
  13582. this._draw(subMesh, fillMode);
  13583. }
  13584. if (batch.visibleInstances[subMesh._id]) {
  13585. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  13586. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  13587. // World
  13588. var world = instance.getWorldMatrix();
  13589. if (onBeforeDraw) {
  13590. onBeforeDraw(true, world);
  13591. }
  13592. // Draw
  13593. this._draw(subMesh, fillMode);
  13594. }
  13595. }
  13596. }
  13597. };
  13598. Mesh.prototype.render = function (subMesh) {
  13599. var scene = this.getScene();
  13600. // Managing instances
  13601. var batch = this._getInstancesRenderList(subMesh._id);
  13602. if (batch.mustReturn) {
  13603. return;
  13604. }
  13605. // Checking geometry state
  13606. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  13607. return;
  13608. }
  13609. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13610. this._onBeforeRenderCallbacks[callbackIndex](this);
  13611. }
  13612. var engine = scene.getEngine();
  13613. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  13614. // Material
  13615. var effectiveMaterial = subMesh.getMaterial();
  13616. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  13617. return;
  13618. }
  13619. // Outline - step 1
  13620. var savedDepthWrite = engine.getDepthWrite();
  13621. if (this.renderOutline) {
  13622. engine.setDepthWrite(false);
  13623. scene.getOutlineRenderer().render(subMesh, batch);
  13624. engine.setDepthWrite(savedDepthWrite);
  13625. }
  13626. effectiveMaterial._preBind();
  13627. var effect = effectiveMaterial.getEffect();
  13628. // Bind
  13629. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  13630. this._bind(subMesh, effect, fillMode);
  13631. var world = this.getWorldMatrix();
  13632. effectiveMaterial.bind(world, this);
  13633. // Draw
  13634. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  13635. if (isInstance) {
  13636. effectiveMaterial.bindOnlyWorldMatrix(world);
  13637. }
  13638. });
  13639. // Unbind
  13640. effectiveMaterial.unbind();
  13641. // Outline - step 2
  13642. if (this.renderOutline && savedDepthWrite) {
  13643. engine.setDepthWrite(true);
  13644. engine.setColorWrite(false);
  13645. scene.getOutlineRenderer().render(subMesh, batch);
  13646. engine.setColorWrite(true);
  13647. }
  13648. // Overlay
  13649. if (this.renderOverlay) {
  13650. var currentMode = engine.getAlphaMode();
  13651. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13652. scene.getOutlineRenderer().render(subMesh, batch, true);
  13653. engine.setAlphaMode(currentMode);
  13654. }
  13655. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13656. this._onAfterRenderCallbacks[callbackIndex](this);
  13657. }
  13658. };
  13659. Mesh.prototype.getEmittedParticleSystems = function () {
  13660. var results = new Array();
  13661. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  13662. var particleSystem = this.getScene().particleSystems[index];
  13663. if (particleSystem.emitter === this) {
  13664. results.push(particleSystem);
  13665. }
  13666. }
  13667. return results;
  13668. };
  13669. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  13670. var results = new Array();
  13671. var descendants = this.getDescendants();
  13672. descendants.push(this);
  13673. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  13674. var particleSystem = this.getScene().particleSystems[index];
  13675. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  13676. results.push(particleSystem);
  13677. }
  13678. }
  13679. return results;
  13680. };
  13681. Mesh.prototype.getChildren = function () {
  13682. var results = [];
  13683. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13684. var mesh = this.getScene().meshes[index];
  13685. if (mesh.parent === this) {
  13686. results.push(mesh);
  13687. }
  13688. }
  13689. return results;
  13690. };
  13691. Mesh.prototype._checkDelayState = function () {
  13692. var _this = this;
  13693. var that = this;
  13694. var scene = this.getScene();
  13695. if (this._geometry) {
  13696. this._geometry.load(scene);
  13697. }
  13698. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13699. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  13700. scene._addPendingData(that);
  13701. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  13702. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  13703. if (data instanceof ArrayBuffer) {
  13704. _this._delayLoadingFunction(data, _this);
  13705. }
  13706. else {
  13707. _this._delayLoadingFunction(JSON.parse(data), _this);
  13708. }
  13709. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13710. scene._removePendingData(_this);
  13711. }, function () {
  13712. }, scene.database, getBinaryData);
  13713. }
  13714. };
  13715. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  13716. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13717. return false;
  13718. }
  13719. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  13720. return false;
  13721. }
  13722. this._checkDelayState();
  13723. return true;
  13724. };
  13725. Mesh.prototype.setMaterialByID = function (id) {
  13726. var materials = this.getScene().materials;
  13727. for (var index = 0; index < materials.length; index++) {
  13728. if (materials[index].id === id) {
  13729. this.material = materials[index];
  13730. return;
  13731. }
  13732. }
  13733. // Multi
  13734. var multiMaterials = this.getScene().multiMaterials;
  13735. for (index = 0; index < multiMaterials.length; index++) {
  13736. if (multiMaterials[index].id === id) {
  13737. this.material = multiMaterials[index];
  13738. return;
  13739. }
  13740. }
  13741. };
  13742. Mesh.prototype.getAnimatables = function () {
  13743. var results = [];
  13744. if (this.material) {
  13745. results.push(this.material);
  13746. }
  13747. if (this.skeleton) {
  13748. results.push(this.skeleton);
  13749. }
  13750. return results;
  13751. };
  13752. // Geometry
  13753. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  13754. // Position
  13755. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  13756. return;
  13757. }
  13758. this._resetPointsArrayCache();
  13759. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13760. var temp = [];
  13761. for (var index = 0; index < data.length; index += 3) {
  13762. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  13763. }
  13764. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  13765. // Normals
  13766. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13767. return;
  13768. }
  13769. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13770. temp = [];
  13771. for (index = 0; index < data.length; index += 3) {
  13772. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  13773. }
  13774. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  13775. };
  13776. // Cache
  13777. Mesh.prototype._resetPointsArrayCache = function () {
  13778. this._positions = null;
  13779. };
  13780. Mesh.prototype._generatePointsArray = function () {
  13781. if (this._positions)
  13782. return true;
  13783. this._positions = [];
  13784. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13785. if (!data) {
  13786. return false;
  13787. }
  13788. for (var index = 0; index < data.length; index += 3) {
  13789. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  13790. }
  13791. return true;
  13792. };
  13793. // Clone
  13794. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13795. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  13796. };
  13797. // Dispose
  13798. Mesh.prototype.dispose = function (doNotRecurse) {
  13799. if (this._geometry) {
  13800. this._geometry.releaseForMesh(this, true);
  13801. }
  13802. // Instances
  13803. if (this._worldMatricesInstancesBuffer) {
  13804. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  13805. this._worldMatricesInstancesBuffer = null;
  13806. }
  13807. while (this.instances.length) {
  13808. this.instances[0].dispose();
  13809. }
  13810. _super.prototype.dispose.call(this, doNotRecurse);
  13811. };
  13812. // Geometric tools
  13813. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  13814. var _this = this;
  13815. var scene = this.getScene();
  13816. var onload = function (img) {
  13817. // Getting height map data
  13818. var canvas = document.createElement("canvas");
  13819. var context = canvas.getContext("2d");
  13820. var heightMapWidth = img.width;
  13821. var heightMapHeight = img.height;
  13822. canvas.width = heightMapWidth;
  13823. canvas.height = heightMapHeight;
  13824. context.drawImage(img, 0, 0);
  13825. // Create VertexData from map data
  13826. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  13827. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  13828. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  13829. //execute success callback, if set
  13830. if (onSuccess) {
  13831. onSuccess(_this);
  13832. }
  13833. };
  13834. BABYLON.Tools.LoadImage(url, onload, function () {
  13835. }, scene.database);
  13836. };
  13837. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  13838. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13839. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  13840. return;
  13841. }
  13842. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13843. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13844. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  13845. var position = BABYLON.Vector3.Zero();
  13846. var normal = BABYLON.Vector3.Zero();
  13847. var uv = BABYLON.Vector2.Zero();
  13848. for (var index = 0; index < positions.length; index += 3) {
  13849. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  13850. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  13851. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  13852. // Compute height
  13853. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  13854. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  13855. var pos = (u + v * heightMapWidth) * 4;
  13856. var r = buffer[pos] / 255.0;
  13857. var g = buffer[pos + 1] / 255.0;
  13858. var b = buffer[pos + 2] / 255.0;
  13859. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  13860. normal.normalize();
  13861. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  13862. position = position.add(normal);
  13863. position.toArray(positions, index);
  13864. }
  13865. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  13866. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  13867. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  13868. };
  13869. Mesh.prototype.convertToFlatShadedMesh = function () {
  13870. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  13871. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  13872. var kinds = this.getVerticesDataKinds();
  13873. var vbs = [];
  13874. var data = [];
  13875. var newdata = [];
  13876. var updatableNormals = false;
  13877. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  13878. var kind = kinds[kindIndex];
  13879. var vertexBuffer = this.getVertexBuffer(kind);
  13880. if (kind === BABYLON.VertexBuffer.NormalKind) {
  13881. updatableNormals = vertexBuffer.isUpdatable();
  13882. kinds.splice(kindIndex, 1);
  13883. kindIndex--;
  13884. continue;
  13885. }
  13886. vbs[kind] = vertexBuffer;
  13887. data[kind] = vbs[kind].getData();
  13888. newdata[kind] = [];
  13889. }
  13890. // Save previous submeshes
  13891. var previousSubmeshes = this.subMeshes.slice(0);
  13892. var indices = this.getIndices();
  13893. var totalIndices = this.getTotalIndices();
  13894. for (var index = 0; index < totalIndices; index++) {
  13895. var vertexIndex = indices[index];
  13896. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  13897. kind = kinds[kindIndex];
  13898. var stride = vbs[kind].getStrideSize();
  13899. for (var offset = 0; offset < stride; offset++) {
  13900. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  13901. }
  13902. }
  13903. }
  13904. // Updating faces & normal
  13905. var normals = [];
  13906. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  13907. for (index = 0; index < totalIndices; index += 3) {
  13908. indices[index] = index;
  13909. indices[index + 1] = index + 1;
  13910. indices[index + 2] = index + 2;
  13911. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  13912. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  13913. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  13914. var p1p2 = p1.subtract(p2);
  13915. var p3p2 = p3.subtract(p2);
  13916. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  13917. for (var localIndex = 0; localIndex < 3; localIndex++) {
  13918. normals.push(normal.x);
  13919. normals.push(normal.y);
  13920. normals.push(normal.z);
  13921. }
  13922. }
  13923. this.setIndices(indices);
  13924. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  13925. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  13926. kind = kinds[kindIndex];
  13927. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  13928. }
  13929. // Updating submeshes
  13930. this.releaseSubMeshes();
  13931. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  13932. var previousOne = previousSubmeshes[submeshIndex];
  13933. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  13934. }
  13935. this.synchronizeInstances();
  13936. };
  13937. // Instances
  13938. Mesh.prototype.createInstance = function (name) {
  13939. return new BABYLON.InstancedMesh(name, this);
  13940. };
  13941. Mesh.prototype.synchronizeInstances = function () {
  13942. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  13943. var instance = this.instances[instanceIndex];
  13944. instance._syncSubMeshes();
  13945. }
  13946. };
  13947. /**
  13948. * Simplify the mesh according to the given array of settings.
  13949. * Function will return immediately and will simplify async.
  13950. * @param settings a collection of simplification settings.
  13951. * @param parallelProcessing should all levels calculate parallel or one after the other.
  13952. * @param type the type of simplification to run.
  13953. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  13954. */
  13955. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  13956. if (parallelProcessing === void 0) { parallelProcessing = true; }
  13957. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  13958. this.getScene().simplificationQueue.addTask({
  13959. settings: settings,
  13960. parallelProcessing: parallelProcessing,
  13961. mesh: this,
  13962. simplificationType: simplificationType,
  13963. successCallback: successCallback
  13964. });
  13965. };
  13966. /**
  13967. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  13968. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  13969. * This should be used together with the simplification to avoid disappearing triangles.
  13970. * @param successCallback an optional success callback to be called after the optimization finished.
  13971. */
  13972. Mesh.prototype.optimizeIndices = function (successCallback) {
  13973. var _this = this;
  13974. var indices = this.getIndices();
  13975. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13976. var vectorPositions = [];
  13977. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  13978. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  13979. }
  13980. var dupes = [];
  13981. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  13982. var realPos = vectorPositions.length - 1 - iteration;
  13983. var testedPosition = vectorPositions[realPos];
  13984. for (var j = 0; j < realPos; ++j) {
  13985. var againstPosition = vectorPositions[j];
  13986. if (testedPosition.equals(againstPosition)) {
  13987. dupes[realPos] = j;
  13988. break;
  13989. }
  13990. }
  13991. }, function () {
  13992. for (var i = 0; i < indices.length; ++i) {
  13993. indices[i] = dupes[indices[i]] || indices[i];
  13994. }
  13995. //indices are now reordered
  13996. var originalSubMeshes = _this.subMeshes.slice(0);
  13997. _this.setIndices(indices);
  13998. _this.subMeshes = originalSubMeshes;
  13999. if (successCallback) {
  14000. successCallback(_this);
  14001. }
  14002. });
  14003. };
  14004. // Statics
  14005. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  14006. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14007. if (ribbonInstance === void 0) { ribbonInstance = null; }
  14008. if (ribbonInstance) {
  14009. // positionFunction : ribbon case
  14010. // only pathArray and sideOrientation parameters are taken into account for positions update
  14011. var positionsOfRibbon = function (pathArray, sideOrientation) {
  14012. var positionFunction = function (positions) {
  14013. var minlg = pathArray[0].length;
  14014. var i = 0;
  14015. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  14016. for (var si = 1; si <= ns; si++) {
  14017. for (var p = 0; p < pathArray.length; p++) {
  14018. var path = pathArray[p];
  14019. var l = path.length;
  14020. minlg = (minlg < l) ? minlg : l;
  14021. var j = 0;
  14022. while (j < minlg) {
  14023. positions[i] = path[j].x;
  14024. positions[i + 1] = path[j].y;
  14025. positions[i + 2] = path[j].z;
  14026. j++;
  14027. i += 3;
  14028. }
  14029. }
  14030. }
  14031. };
  14032. return positionFunction;
  14033. };
  14034. var sideOrientation = ribbonInstance.sideOrientation;
  14035. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  14036. var computeNormals = !(ribbonInstance.areNormalsFrozen);
  14037. ribbonInstance.updateMeshPositions(positionFunction, computeNormals);
  14038. return ribbonInstance;
  14039. }
  14040. else {
  14041. var ribbon = new Mesh(name, scene);
  14042. ribbon.sideOrientation = sideOrientation;
  14043. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  14044. vertexData.applyToMesh(ribbon, updatable);
  14045. return ribbon;
  14046. }
  14047. };
  14048. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  14049. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14050. var disc = new Mesh(name, scene);
  14051. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  14052. vertexData.applyToMesh(disc, updatable);
  14053. return disc;
  14054. };
  14055. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  14056. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14057. var box = new Mesh(name, scene);
  14058. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  14059. vertexData.applyToMesh(box, updatable);
  14060. return box;
  14061. };
  14062. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  14063. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14064. var sphere = new Mesh(name, scene);
  14065. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  14066. vertexData.applyToMesh(sphere, updatable);
  14067. return sphere;
  14068. };
  14069. // Cylinder and cone (Code inspired by SharpDX.org)
  14070. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  14071. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14072. // subdivisions is a new parameter, we need to support old signature
  14073. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  14074. if (scene !== undefined) {
  14075. updatable = scene;
  14076. }
  14077. scene = subdivisions;
  14078. subdivisions = 1;
  14079. }
  14080. var cylinder = new Mesh(name, scene);
  14081. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  14082. vertexData.applyToMesh(cylinder, updatable);
  14083. return cylinder;
  14084. };
  14085. // Torus (Code from SharpDX.org)
  14086. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  14087. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14088. var torus = new Mesh(name, scene);
  14089. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  14090. vertexData.applyToMesh(torus, updatable);
  14091. return torus;
  14092. };
  14093. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  14094. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14095. var torusKnot = new Mesh(name, scene);
  14096. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  14097. vertexData.applyToMesh(torusKnot, updatable);
  14098. return torusKnot;
  14099. };
  14100. // Lines
  14101. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  14102. if (linesInstance === void 0) { linesInstance = null; }
  14103. if (linesInstance) {
  14104. var positionsOfLines = function (points) {
  14105. var positionFunction = function (positions) {
  14106. var i = 0;
  14107. for (var p = 0; p < points.length; p++) {
  14108. positions[i] = points[p].x;
  14109. positions[i + 1] = points[p].y;
  14110. positions[i + 2] = points[p].z;
  14111. i += 3;
  14112. }
  14113. };
  14114. return positionFunction;
  14115. };
  14116. var positionFunction = positionsOfLines(points);
  14117. linesInstance.updateMeshPositions(positionFunction, false);
  14118. return linesInstance;
  14119. }
  14120. // lines creation
  14121. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  14122. var vertexData = BABYLON.VertexData.CreateLines(points);
  14123. vertexData.applyToMesh(lines, updatable);
  14124. return lines;
  14125. };
  14126. // Extrusion
  14127. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  14128. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14129. if (extrudedInstance === void 0) { extrudedInstance = null; }
  14130. scale = scale || 1;
  14131. rotation = rotation || 0;
  14132. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  14133. return extruded;
  14134. };
  14135. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  14136. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14137. if (extrudedInstance === void 0) { extrudedInstance = null; }
  14138. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  14139. return extrudedCustom;
  14140. };
  14141. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  14142. // extrusion geometry
  14143. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  14144. var tangents = path3D.getTangents();
  14145. var normals = path3D.getNormals();
  14146. var binormals = path3D.getBinormals();
  14147. var distances = path3D.getDistances();
  14148. var angle = 0;
  14149. var returnScale = function (i, distance) {
  14150. return scale;
  14151. };
  14152. var returnRotation = function (i, distance) {
  14153. return rotation;
  14154. };
  14155. var rotate = custom ? rotateFunction : returnRotation;
  14156. var scl = custom ? scaleFunction : returnScale;
  14157. var index = 0;
  14158. for (var i = 0; i < curve.length; i++) {
  14159. var shapePath = new Array();
  14160. var angleStep = rotate(i, distances[i]);
  14161. var scaleRatio = scl(i, distances[i]);
  14162. for (var p = 0; p < shape.length; p++) {
  14163. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  14164. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  14165. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  14166. shapePath.push(rotated);
  14167. }
  14168. shapePaths[index] = shapePath;
  14169. angle += angleStep;
  14170. index++;
  14171. }
  14172. // cap
  14173. var capPath = function (shapePath) {
  14174. var pointCap = Array();
  14175. var barycenter = BABYLON.Vector3.Zero();
  14176. var i;
  14177. for (i = 0; i < shapePath.length; i++) {
  14178. barycenter.addInPlace(shapePath[i]);
  14179. }
  14180. barycenter.scaleInPlace(1 / shapePath.length);
  14181. for (i = 0; i < shapePath.length; i++) {
  14182. pointCap.push(barycenter);
  14183. }
  14184. return pointCap;
  14185. };
  14186. switch (cap) {
  14187. case BABYLON.Mesh.NO_CAP:
  14188. break;
  14189. case BABYLON.Mesh.CAP_START:
  14190. shapePaths.unshift(capPath(shapePaths[0]));
  14191. break;
  14192. case BABYLON.Mesh.CAP_END:
  14193. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  14194. break;
  14195. case BABYLON.Mesh.CAP_ALL:
  14196. shapePaths.unshift(capPath(shapePaths[0]));
  14197. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  14198. break;
  14199. default:
  14200. break;
  14201. }
  14202. return shapePaths;
  14203. };
  14204. if (instance) {
  14205. var path3D = (instance.path3D).update(curve);
  14206. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  14207. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  14208. return instance;
  14209. }
  14210. // extruded shape creation
  14211. var path3D = new BABYLON.Path3D(curve);
  14212. var newShapePaths = new Array();
  14213. cap = (cap < 0 || cap > 3) ? 0 : cap;
  14214. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  14215. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  14216. extrudedGeneric.pathArray = pathArray;
  14217. extrudedGeneric.path3D = path3D;
  14218. extrudedGeneric.cap = cap;
  14219. return extrudedGeneric;
  14220. };
  14221. // Plane & ground
  14222. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  14223. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14224. var plane = new Mesh(name, scene);
  14225. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  14226. vertexData.applyToMesh(plane, updatable);
  14227. return plane;
  14228. };
  14229. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  14230. var ground = new BABYLON.GroundMesh(name, scene);
  14231. ground._setReady(false);
  14232. ground._subdivisions = subdivisions;
  14233. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  14234. vertexData.applyToMesh(ground, updatable);
  14235. ground._setReady(true);
  14236. return ground;
  14237. };
  14238. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  14239. var tiledGround = new Mesh(name, scene);
  14240. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  14241. vertexData.applyToMesh(tiledGround, updatable);
  14242. return tiledGround;
  14243. };
  14244. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  14245. var ground = new BABYLON.GroundMesh(name, scene);
  14246. ground._subdivisions = subdivisions;
  14247. ground._setReady(false);
  14248. var onload = function (img) {
  14249. // Getting height map data
  14250. var canvas = document.createElement("canvas");
  14251. var context = canvas.getContext("2d");
  14252. var heightMapWidth = img.width;
  14253. var heightMapHeight = img.height;
  14254. canvas.width = heightMapWidth;
  14255. canvas.height = heightMapHeight;
  14256. context.drawImage(img, 0, 0);
  14257. // Create VertexData from map data
  14258. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14259. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14260. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  14261. vertexData.applyToMesh(ground, updatable);
  14262. ground._setReady(true);
  14263. //execute ready callback, if set
  14264. if (onReady) {
  14265. onReady(ground);
  14266. }
  14267. };
  14268. BABYLON.Tools.LoadImage(url, onload, function () {
  14269. }, scene.database);
  14270. return ground;
  14271. };
  14272. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  14273. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14274. if (tubeInstance === void 0) { tubeInstance = null; }
  14275. // tube geometry
  14276. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  14277. var tangents = path3D.getTangents();
  14278. var normals = path3D.getNormals();
  14279. var distances = path3D.getDistances();
  14280. var pi2 = Math.PI * 2;
  14281. var step = pi2 / tessellation;
  14282. var returnRadius = function (i, distance) { return radius; };
  14283. var radiusFunctionFinal = radiusFunction || returnRadius;
  14284. var circlePath;
  14285. var rad;
  14286. var normal;
  14287. var rotated;
  14288. var rotationMatrix;
  14289. var index = 0;
  14290. for (var i = 0; i < path.length; i++) {
  14291. rad = radiusFunctionFinal(i, distances[i]); // current radius
  14292. circlePath = Array(); // current circle array
  14293. normal = normals[i]; // current normal
  14294. for (var t = 0; t < tessellation; t++) {
  14295. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  14296. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  14297. circlePath.push(rotated);
  14298. }
  14299. circlePath.push(circlePath[0]);
  14300. circlePaths[index] = circlePath;
  14301. index++;
  14302. }
  14303. // cap
  14304. var capPath = function (nbPoints, pathIndex) {
  14305. var pointCap = Array();
  14306. for (var i = 0; i < nbPoints; i++) {
  14307. pointCap.push(path[pathIndex]);
  14308. }
  14309. return pointCap;
  14310. };
  14311. switch (cap) {
  14312. case BABYLON.Mesh.NO_CAP:
  14313. break;
  14314. case BABYLON.Mesh.CAP_START:
  14315. circlePaths.unshift(capPath(tessellation + 1, 0));
  14316. break;
  14317. case BABYLON.Mesh.CAP_END:
  14318. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  14319. break;
  14320. case BABYLON.Mesh.CAP_ALL:
  14321. circlePaths.unshift(capPath(tessellation + 1, 0));
  14322. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  14323. break;
  14324. default:
  14325. break;
  14326. }
  14327. return circlePaths;
  14328. };
  14329. if (tubeInstance) {
  14330. var path3D = (tubeInstance.path3D).update(path);
  14331. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  14332. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  14333. return tubeInstance;
  14334. }
  14335. // tube creation
  14336. var path3D = new BABYLON.Path3D(path);
  14337. var newPathArray = new Array();
  14338. cap = (cap < 0 || cap > 3) ? 0 : cap;
  14339. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  14340. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  14341. tube.pathArray = pathArray;
  14342. tube.path3D = path3D;
  14343. tube.tessellation = tessellation;
  14344. tube.cap = cap;
  14345. return tube;
  14346. };
  14347. // Decals
  14348. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  14349. if (angle === void 0) { angle = 0; }
  14350. var indices = sourceMesh.getIndices();
  14351. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14352. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14353. // Getting correct rotation
  14354. if (!normal) {
  14355. var target = new BABYLON.Vector3(0, 0, 1);
  14356. var camera = sourceMesh.getScene().activeCamera;
  14357. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  14358. normal = camera.globalPosition.subtract(cameraWorldTarget);
  14359. }
  14360. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  14361. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  14362. var pitch = Math.atan2(normal.y, len);
  14363. // Matrix
  14364. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  14365. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  14366. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  14367. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  14368. var vertexData = new BABYLON.VertexData();
  14369. vertexData.indices = [];
  14370. vertexData.positions = [];
  14371. vertexData.normals = [];
  14372. vertexData.uvs = [];
  14373. var currentVertexDataIndex = 0;
  14374. var extractDecalVector3 = function (indexId) {
  14375. var vertexId = indices[indexId];
  14376. var result = new BABYLON.PositionNormalVertex();
  14377. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  14378. // Send vector to decal local world
  14379. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  14380. // Get normal
  14381. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  14382. return result;
  14383. };
  14384. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  14385. var clip = function (vertices, axis) {
  14386. if (vertices.length === 0) {
  14387. return vertices;
  14388. }
  14389. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  14390. var clipVertices = function (v0, v1) {
  14391. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  14392. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  14393. };
  14394. var result = new Array();
  14395. for (var index = 0; index < vertices.length; index += 3) {
  14396. var v1Out;
  14397. var v2Out;
  14398. var v3Out;
  14399. var total = 0;
  14400. var nV1, nV2, nV3, nV4;
  14401. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  14402. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  14403. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  14404. v1Out = d1 > 0;
  14405. v2Out = d2 > 0;
  14406. v3Out = d3 > 0;
  14407. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  14408. switch (total) {
  14409. case 0:
  14410. result.push(vertices[index]);
  14411. result.push(vertices[index + 1]);
  14412. result.push(vertices[index + 2]);
  14413. break;
  14414. case 1:
  14415. if (v1Out) {
  14416. nV1 = vertices[index + 1];
  14417. nV2 = vertices[index + 2];
  14418. nV3 = clipVertices(vertices[index], nV1);
  14419. nV4 = clipVertices(vertices[index], nV2);
  14420. }
  14421. if (v2Out) {
  14422. nV1 = vertices[index];
  14423. nV2 = vertices[index + 2];
  14424. nV3 = clipVertices(vertices[index + 1], nV1);
  14425. nV4 = clipVertices(vertices[index + 1], nV2);
  14426. result.push(nV3);
  14427. result.push(nV2.clone());
  14428. result.push(nV1.clone());
  14429. result.push(nV2.clone());
  14430. result.push(nV3.clone());
  14431. result.push(nV4);
  14432. break;
  14433. }
  14434. if (v3Out) {
  14435. nV1 = vertices[index];
  14436. nV2 = vertices[index + 1];
  14437. nV3 = clipVertices(vertices[index + 2], nV1);
  14438. nV4 = clipVertices(vertices[index + 2], nV2);
  14439. }
  14440. result.push(nV1.clone());
  14441. result.push(nV2.clone());
  14442. result.push(nV3);
  14443. result.push(nV4);
  14444. result.push(nV3.clone());
  14445. result.push(nV2.clone());
  14446. break;
  14447. case 2:
  14448. if (!v1Out) {
  14449. nV1 = vertices[index].clone();
  14450. nV2 = clipVertices(nV1, vertices[index + 1]);
  14451. nV3 = clipVertices(nV1, vertices[index + 2]);
  14452. result.push(nV1);
  14453. result.push(nV2);
  14454. result.push(nV3);
  14455. }
  14456. if (!v2Out) {
  14457. nV1 = vertices[index + 1].clone();
  14458. nV2 = clipVertices(nV1, vertices[index + 2]);
  14459. nV3 = clipVertices(nV1, vertices[index]);
  14460. result.push(nV1);
  14461. result.push(nV2);
  14462. result.push(nV3);
  14463. }
  14464. if (!v3Out) {
  14465. nV1 = vertices[index + 2].clone();
  14466. nV2 = clipVertices(nV1, vertices[index]);
  14467. nV3 = clipVertices(nV1, vertices[index + 1]);
  14468. result.push(nV1);
  14469. result.push(nV2);
  14470. result.push(nV3);
  14471. }
  14472. break;
  14473. case 3:
  14474. break;
  14475. }
  14476. }
  14477. return result;
  14478. };
  14479. for (var index = 0; index < indices.length; index += 3) {
  14480. var faceVertices = new Array();
  14481. faceVertices.push(extractDecalVector3(index));
  14482. faceVertices.push(extractDecalVector3(index + 1));
  14483. faceVertices.push(extractDecalVector3(index + 2));
  14484. // Clip
  14485. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  14486. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  14487. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  14488. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  14489. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  14490. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  14491. if (faceVertices.length === 0) {
  14492. continue;
  14493. }
  14494. // Add UVs and get back to world
  14495. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  14496. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  14497. var vertex = faceVertices[vIndex];
  14498. vertexData.indices.push(currentVertexDataIndex);
  14499. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  14500. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  14501. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  14502. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  14503. currentVertexDataIndex++;
  14504. }
  14505. }
  14506. // Return mesh
  14507. var decal = new Mesh(name, sourceMesh.getScene());
  14508. vertexData.applyToMesh(decal);
  14509. decal.position = position.clone();
  14510. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  14511. return decal;
  14512. };
  14513. // Tools
  14514. Mesh.MinMax = function (meshes) {
  14515. var minVector = null;
  14516. var maxVector = null;
  14517. for (var i in meshes) {
  14518. var mesh = meshes[i];
  14519. var boundingBox = mesh.getBoundingInfo().boundingBox;
  14520. if (!minVector) {
  14521. minVector = boundingBox.minimumWorld;
  14522. maxVector = boundingBox.maximumWorld;
  14523. continue;
  14524. }
  14525. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  14526. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  14527. }
  14528. return {
  14529. min: minVector,
  14530. max: maxVector
  14531. };
  14532. };
  14533. Mesh.Center = function (meshesOrMinMaxVector) {
  14534. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  14535. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  14536. };
  14537. /**
  14538. * Merge the array of meshes into a single mesh for performance reasons.
  14539. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  14540. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  14541. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  14542. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  14543. */
  14544. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  14545. if (disposeSource === void 0) { disposeSource = true; }
  14546. if (!allow32BitsIndices) {
  14547. var totalVertices = 0;
  14548. for (var index = 0; index < meshes.length; index++) {
  14549. if (meshes[index]) {
  14550. totalVertices += meshes[index].getTotalVertices();
  14551. if (totalVertices > 65536) {
  14552. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  14553. return null;
  14554. }
  14555. }
  14556. }
  14557. }
  14558. // Merge
  14559. var vertexData;
  14560. var otherVertexData;
  14561. var source;
  14562. for (index = 0; index < meshes.length; index++) {
  14563. if (meshes[index]) {
  14564. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  14565. otherVertexData.transform(meshes[index].getWorldMatrix());
  14566. if (vertexData) {
  14567. vertexData.merge(otherVertexData);
  14568. }
  14569. else {
  14570. vertexData = otherVertexData;
  14571. source = meshes[index];
  14572. }
  14573. }
  14574. }
  14575. if (!meshSubclass) {
  14576. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  14577. }
  14578. vertexData.applyToMesh(meshSubclass);
  14579. // Setting properties
  14580. meshSubclass.material = source.material;
  14581. meshSubclass.checkCollisions = source.checkCollisions;
  14582. // Cleaning
  14583. if (disposeSource) {
  14584. for (index = 0; index < meshes.length; index++) {
  14585. if (meshes[index]) {
  14586. meshes[index].dispose();
  14587. }
  14588. }
  14589. }
  14590. return meshSubclass;
  14591. };
  14592. // Consts
  14593. Mesh._FRONTSIDE = 0;
  14594. Mesh._BACKSIDE = 1;
  14595. Mesh._DOUBLESIDE = 2;
  14596. Mesh._DEFAULTSIDE = 0;
  14597. Mesh._NO_CAP = 0;
  14598. Mesh._CAP_START = 1;
  14599. Mesh._CAP_END = 2;
  14600. Mesh._CAP_ALL = 3;
  14601. return Mesh;
  14602. })(BABYLON.AbstractMesh);
  14603. BABYLON.Mesh = Mesh;
  14604. })(BABYLON || (BABYLON = {}));
  14605. //# sourceMappingURL=babylon.mesh.js.map
  14606. var BABYLON;
  14607. (function (BABYLON) {
  14608. var SubMesh = (function () {
  14609. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  14610. if (createBoundingBox === void 0) { createBoundingBox = true; }
  14611. this.materialIndex = materialIndex;
  14612. this.verticesStart = verticesStart;
  14613. this.verticesCount = verticesCount;
  14614. this.indexStart = indexStart;
  14615. this.indexCount = indexCount;
  14616. this._renderId = 0;
  14617. this._mesh = mesh;
  14618. this._renderingMesh = renderingMesh || mesh;
  14619. mesh.subMeshes.push(this);
  14620. this._trianglePlanes = [];
  14621. this._id = mesh.subMeshes.length - 1;
  14622. if (createBoundingBox) {
  14623. this.refreshBoundingInfo();
  14624. mesh.computeWorldMatrix(true);
  14625. }
  14626. }
  14627. SubMesh.prototype.getBoundingInfo = function () {
  14628. return this._boundingInfo;
  14629. };
  14630. SubMesh.prototype.getMesh = function () {
  14631. return this._mesh;
  14632. };
  14633. SubMesh.prototype.getRenderingMesh = function () {
  14634. return this._renderingMesh;
  14635. };
  14636. SubMesh.prototype.getMaterial = function () {
  14637. var rootMaterial = this._renderingMesh.material;
  14638. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  14639. var multiMaterial = rootMaterial;
  14640. return multiMaterial.getSubMaterial(this.materialIndex);
  14641. }
  14642. if (!rootMaterial) {
  14643. return this._mesh.getScene().defaultMaterial;
  14644. }
  14645. return rootMaterial;
  14646. };
  14647. // Methods
  14648. SubMesh.prototype.refreshBoundingInfo = function () {
  14649. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14650. if (!data) {
  14651. this._boundingInfo = this._mesh._boundingInfo;
  14652. return;
  14653. }
  14654. var indices = this._renderingMesh.getIndices();
  14655. var extend;
  14656. if (this.indexStart === 0 && this.indexCount === indices.length) {
  14657. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  14658. }
  14659. else {
  14660. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  14661. }
  14662. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14663. };
  14664. SubMesh.prototype._checkCollision = function (collider) {
  14665. return this._boundingInfo._checkCollision(collider);
  14666. };
  14667. SubMesh.prototype.updateBoundingInfo = function (world) {
  14668. if (!this._boundingInfo) {
  14669. this.refreshBoundingInfo();
  14670. }
  14671. this._boundingInfo._update(world);
  14672. };
  14673. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  14674. return this._boundingInfo.isInFrustum(frustumPlanes);
  14675. };
  14676. SubMesh.prototype.render = function () {
  14677. this._renderingMesh.render(this);
  14678. };
  14679. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  14680. if (!this._linesIndexBuffer) {
  14681. var linesIndices = [];
  14682. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  14683. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  14684. }
  14685. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  14686. this.linesIndexCount = linesIndices.length;
  14687. }
  14688. return this._linesIndexBuffer;
  14689. };
  14690. SubMesh.prototype.canIntersects = function (ray) {
  14691. return ray.intersectsBox(this._boundingInfo.boundingBox);
  14692. };
  14693. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  14694. var intersectInfo = null;
  14695. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  14696. var p0 = positions[indices[index]];
  14697. var p1 = positions[indices[index + 1]];
  14698. var p2 = positions[indices[index + 2]];
  14699. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  14700. if (currentIntersectInfo) {
  14701. if (currentIntersectInfo.distance < 0) {
  14702. continue;
  14703. }
  14704. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14705. intersectInfo = currentIntersectInfo;
  14706. intersectInfo.faceId = index / 3;
  14707. if (fastCheck) {
  14708. break;
  14709. }
  14710. }
  14711. }
  14712. }
  14713. return intersectInfo;
  14714. };
  14715. // Clone
  14716. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  14717. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  14718. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  14719. return result;
  14720. };
  14721. // Dispose
  14722. SubMesh.prototype.dispose = function () {
  14723. if (this._linesIndexBuffer) {
  14724. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  14725. this._linesIndexBuffer = null;
  14726. }
  14727. // Remove from mesh
  14728. var index = this._mesh.subMeshes.indexOf(this);
  14729. this._mesh.subMeshes.splice(index, 1);
  14730. };
  14731. // Statics
  14732. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  14733. var minVertexIndex = Number.MAX_VALUE;
  14734. var maxVertexIndex = -Number.MAX_VALUE;
  14735. renderingMesh = renderingMesh || mesh;
  14736. var indices = renderingMesh.getIndices();
  14737. for (var index = startIndex; index < startIndex + indexCount; index++) {
  14738. var vertexIndex = indices[index];
  14739. if (vertexIndex < minVertexIndex)
  14740. minVertexIndex = vertexIndex;
  14741. if (vertexIndex > maxVertexIndex)
  14742. maxVertexIndex = vertexIndex;
  14743. }
  14744. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  14745. };
  14746. return SubMesh;
  14747. })();
  14748. BABYLON.SubMesh = SubMesh;
  14749. })(BABYLON || (BABYLON = {}));
  14750. //# sourceMappingURL=babylon.subMesh.js.map
  14751. var BABYLON;
  14752. (function (BABYLON) {
  14753. var BaseTexture = (function () {
  14754. function BaseTexture(scene) {
  14755. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14756. this.hasAlpha = false;
  14757. this.getAlphaFromRGB = false;
  14758. this.level = 1;
  14759. this.isCube = false;
  14760. this.isRenderTarget = false;
  14761. this.animations = new Array();
  14762. this.coordinatesIndex = 0;
  14763. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  14764. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  14765. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  14766. this.anisotropicFilteringLevel = 4;
  14767. this._scene = scene;
  14768. this._scene.textures.push(this);
  14769. }
  14770. BaseTexture.prototype.getScene = function () {
  14771. return this._scene;
  14772. };
  14773. BaseTexture.prototype.getTextureMatrix = function () {
  14774. return null;
  14775. };
  14776. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  14777. return null;
  14778. };
  14779. BaseTexture.prototype.getInternalTexture = function () {
  14780. return this._texture;
  14781. };
  14782. BaseTexture.prototype.isReady = function () {
  14783. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14784. return true;
  14785. }
  14786. if (this._texture) {
  14787. return this._texture.isReady;
  14788. }
  14789. return false;
  14790. };
  14791. BaseTexture.prototype.getSize = function () {
  14792. if (this._texture._width) {
  14793. return { width: this._texture._width, height: this._texture._height };
  14794. }
  14795. if (this._texture._size) {
  14796. return { width: this._texture._size, height: this._texture._size };
  14797. }
  14798. return { width: 0, height: 0 };
  14799. };
  14800. BaseTexture.prototype.getBaseSize = function () {
  14801. if (!this.isReady())
  14802. return { width: 0, height: 0 };
  14803. if (this._texture._size) {
  14804. return { width: this._texture._size, height: this._texture._size };
  14805. }
  14806. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  14807. };
  14808. BaseTexture.prototype.scale = function (ratio) {
  14809. };
  14810. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  14811. get: function () {
  14812. return false;
  14813. },
  14814. enumerable: true,
  14815. configurable: true
  14816. });
  14817. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  14818. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  14819. for (var index = 0; index < texturesCache.length; index++) {
  14820. var texturesCacheEntry = texturesCache[index];
  14821. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  14822. texturesCache.splice(index, 1);
  14823. return;
  14824. }
  14825. }
  14826. };
  14827. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  14828. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  14829. for (var index = 0; index < texturesCache.length; index++) {
  14830. var texturesCacheEntry = texturesCache[index];
  14831. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  14832. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  14833. texturesCacheEntry.references++;
  14834. return texturesCacheEntry;
  14835. }
  14836. }
  14837. }
  14838. return null;
  14839. };
  14840. BaseTexture.prototype.delayLoad = function () {
  14841. };
  14842. BaseTexture.prototype.releaseInternalTexture = function () {
  14843. if (!this._texture) {
  14844. return;
  14845. }
  14846. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  14847. this._texture.references--;
  14848. // Final reference ?
  14849. if (this._texture.references === 0) {
  14850. var index = texturesCache.indexOf(this._texture);
  14851. texturesCache.splice(index, 1);
  14852. this._scene.getEngine()._releaseTexture(this._texture);
  14853. delete this._texture;
  14854. }
  14855. };
  14856. BaseTexture.prototype.clone = function () {
  14857. return null;
  14858. };
  14859. BaseTexture.prototype.dispose = function () {
  14860. // Remove from scene
  14861. var index = this._scene.textures.indexOf(this);
  14862. if (index >= 0) {
  14863. this._scene.textures.splice(index, 1);
  14864. }
  14865. if (this._texture === undefined) {
  14866. return;
  14867. }
  14868. this.releaseInternalTexture();
  14869. // Callback
  14870. if (this.onDispose) {
  14871. this.onDispose();
  14872. }
  14873. };
  14874. return BaseTexture;
  14875. })();
  14876. BABYLON.BaseTexture = BaseTexture;
  14877. })(BABYLON || (BABYLON = {}));
  14878. //# sourceMappingURL=babylon.baseTexture.js.map
  14879. var __extends = this.__extends || function (d, b) {
  14880. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14881. function __() { this.constructor = d; }
  14882. __.prototype = b.prototype;
  14883. d.prototype = new __();
  14884. };
  14885. var BABYLON;
  14886. (function (BABYLON) {
  14887. var Texture = (function (_super) {
  14888. __extends(Texture, _super);
  14889. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  14890. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  14891. if (onLoad === void 0) { onLoad = null; }
  14892. if (onError === void 0) { onError = null; }
  14893. if (buffer === void 0) { buffer = null; }
  14894. if (deleteBuffer === void 0) { deleteBuffer = false; }
  14895. _super.call(this, scene);
  14896. this.uOffset = 0;
  14897. this.vOffset = 0;
  14898. this.uScale = 1.0;
  14899. this.vScale = 1.0;
  14900. this.uAng = 0;
  14901. this.vAng = 0;
  14902. this.wAng = 0;
  14903. this.name = url;
  14904. this.url = url;
  14905. this._noMipmap = noMipmap;
  14906. this._invertY = invertY;
  14907. this._samplingMode = samplingMode;
  14908. this._buffer = buffer;
  14909. this._deleteBuffer = deleteBuffer;
  14910. if (!url) {
  14911. return;
  14912. }
  14913. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  14914. if (!this._texture) {
  14915. if (!scene.useDelayedTextureLoading) {
  14916. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  14917. if (deleteBuffer) {
  14918. delete this._buffer;
  14919. }
  14920. }
  14921. else {
  14922. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  14923. }
  14924. }
  14925. }
  14926. Texture.prototype.delayLoad = function () {
  14927. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14928. return;
  14929. }
  14930. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14931. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  14932. if (!this._texture) {
  14933. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  14934. if (this._deleteBuffer) {
  14935. delete this._buffer;
  14936. }
  14937. }
  14938. };
  14939. Texture.prototype.updateSamplingMode = function (samplingMode) {
  14940. if (!this._texture) {
  14941. return;
  14942. }
  14943. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  14944. };
  14945. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  14946. x -= this.uOffset + 0.5;
  14947. y -= this.vOffset + 0.5;
  14948. z -= 0.5;
  14949. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  14950. t.x *= this.uScale;
  14951. t.y *= this.vScale;
  14952. t.x += 0.5;
  14953. t.y += 0.5;
  14954. t.z += 0.5;
  14955. };
  14956. Texture.prototype.getTextureMatrix = function () {
  14957. 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) {
  14958. return this._cachedTextureMatrix;
  14959. }
  14960. this._cachedUOffset = this.uOffset;
  14961. this._cachedVOffset = this.vOffset;
  14962. this._cachedUScale = this.uScale;
  14963. this._cachedVScale = this.vScale;
  14964. this._cachedUAng = this.uAng;
  14965. this._cachedVAng = this.vAng;
  14966. this._cachedWAng = this.wAng;
  14967. if (!this._cachedTextureMatrix) {
  14968. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  14969. this._rowGenerationMatrix = new BABYLON.Matrix();
  14970. this._t0 = BABYLON.Vector3.Zero();
  14971. this._t1 = BABYLON.Vector3.Zero();
  14972. this._t2 = BABYLON.Vector3.Zero();
  14973. }
  14974. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  14975. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  14976. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  14977. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  14978. this._t1.subtractInPlace(this._t0);
  14979. this._t2.subtractInPlace(this._t0);
  14980. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  14981. this._cachedTextureMatrix.m[0] = this._t1.x;
  14982. this._cachedTextureMatrix.m[1] = this._t1.y;
  14983. this._cachedTextureMatrix.m[2] = this._t1.z;
  14984. this._cachedTextureMatrix.m[4] = this._t2.x;
  14985. this._cachedTextureMatrix.m[5] = this._t2.y;
  14986. this._cachedTextureMatrix.m[6] = this._t2.z;
  14987. this._cachedTextureMatrix.m[8] = this._t0.x;
  14988. this._cachedTextureMatrix.m[9] = this._t0.y;
  14989. this._cachedTextureMatrix.m[10] = this._t0.z;
  14990. return this._cachedTextureMatrix;
  14991. };
  14992. Texture.prototype.getReflectionTextureMatrix = function () {
  14993. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  14994. return this._cachedTextureMatrix;
  14995. }
  14996. if (!this._cachedTextureMatrix) {
  14997. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  14998. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  14999. }
  15000. this._cachedCoordinatesMode = this.coordinatesMode;
  15001. switch (this.coordinatesMode) {
  15002. case Texture.SPHERICAL_MODE:
  15003. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15004. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  15005. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  15006. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  15007. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  15008. break;
  15009. case Texture.PLANAR_MODE:
  15010. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15011. this._cachedTextureMatrix[0] = this.uScale;
  15012. this._cachedTextureMatrix[5] = this.vScale;
  15013. this._cachedTextureMatrix[12] = this.uOffset;
  15014. this._cachedTextureMatrix[13] = this.vOffset;
  15015. break;
  15016. case Texture.PROJECTION_MODE:
  15017. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  15018. this._projectionModeMatrix.m[0] = 0.5;
  15019. this._projectionModeMatrix.m[5] = -0.5;
  15020. this._projectionModeMatrix.m[10] = 0.0;
  15021. this._projectionModeMatrix.m[12] = 0.5;
  15022. this._projectionModeMatrix.m[13] = 0.5;
  15023. this._projectionModeMatrix.m[14] = 1.0;
  15024. this._projectionModeMatrix.m[15] = 1.0;
  15025. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  15026. break;
  15027. default:
  15028. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15029. break;
  15030. }
  15031. return this._cachedTextureMatrix;
  15032. };
  15033. Texture.prototype.clone = function () {
  15034. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  15035. // Base texture
  15036. newTexture.hasAlpha = this.hasAlpha;
  15037. newTexture.level = this.level;
  15038. newTexture.wrapU = this.wrapU;
  15039. newTexture.wrapV = this.wrapV;
  15040. newTexture.coordinatesIndex = this.coordinatesIndex;
  15041. newTexture.coordinatesMode = this.coordinatesMode;
  15042. // Texture
  15043. newTexture.uOffset = this.uOffset;
  15044. newTexture.vOffset = this.vOffset;
  15045. newTexture.uScale = this.uScale;
  15046. newTexture.vScale = this.vScale;
  15047. newTexture.uAng = this.uAng;
  15048. newTexture.vAng = this.vAng;
  15049. newTexture.wAng = this.wAng;
  15050. return newTexture;
  15051. };
  15052. // Statics
  15053. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  15054. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  15055. if (onLoad === void 0) { onLoad = null; }
  15056. if (onError === void 0) { onError = null; }
  15057. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  15058. };
  15059. // Constants
  15060. Texture.NEAREST_SAMPLINGMODE = 1;
  15061. Texture.BILINEAR_SAMPLINGMODE = 2;
  15062. Texture.TRILINEAR_SAMPLINGMODE = 3;
  15063. Texture.EXPLICIT_MODE = 0;
  15064. Texture.SPHERICAL_MODE = 1;
  15065. Texture.PLANAR_MODE = 2;
  15066. Texture.CUBIC_MODE = 3;
  15067. Texture.PROJECTION_MODE = 4;
  15068. Texture.SKYBOX_MODE = 5;
  15069. Texture.CLAMP_ADDRESSMODE = 0;
  15070. Texture.WRAP_ADDRESSMODE = 1;
  15071. Texture.MIRROR_ADDRESSMODE = 2;
  15072. return Texture;
  15073. })(BABYLON.BaseTexture);
  15074. BABYLON.Texture = Texture;
  15075. })(BABYLON || (BABYLON = {}));
  15076. //# sourceMappingURL=babylon.texture.js.map
  15077. var __extends = this.__extends || function (d, b) {
  15078. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15079. function __() { this.constructor = d; }
  15080. __.prototype = b.prototype;
  15081. d.prototype = new __();
  15082. };
  15083. var BABYLON;
  15084. (function (BABYLON) {
  15085. var CubeTexture = (function (_super) {
  15086. __extends(CubeTexture, _super);
  15087. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  15088. _super.call(this, scene);
  15089. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  15090. this.name = rootUrl;
  15091. this.url = rootUrl;
  15092. this._noMipmap = noMipmap;
  15093. this.hasAlpha = false;
  15094. this._texture = this._getFromCache(rootUrl, noMipmap);
  15095. if (!extensions) {
  15096. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  15097. }
  15098. this._extensions = extensions;
  15099. if (!this._texture) {
  15100. if (!scene.useDelayedTextureLoading) {
  15101. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  15102. }
  15103. else {
  15104. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15105. }
  15106. }
  15107. this.isCube = true;
  15108. this._textureMatrix = BABYLON.Matrix.Identity();
  15109. }
  15110. CubeTexture.prototype.clone = function () {
  15111. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  15112. // Base texture
  15113. newTexture.level = this.level;
  15114. newTexture.wrapU = this.wrapU;
  15115. newTexture.wrapV = this.wrapV;
  15116. newTexture.coordinatesIndex = this.coordinatesIndex;
  15117. newTexture.coordinatesMode = this.coordinatesMode;
  15118. return newTexture;
  15119. };
  15120. // Methods
  15121. CubeTexture.prototype.delayLoad = function () {
  15122. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15123. return;
  15124. }
  15125. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15126. this._texture = this._getFromCache(this.url, this._noMipmap);
  15127. if (!this._texture) {
  15128. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  15129. }
  15130. };
  15131. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  15132. return this._textureMatrix;
  15133. };
  15134. return CubeTexture;
  15135. })(BABYLON.BaseTexture);
  15136. BABYLON.CubeTexture = CubeTexture;
  15137. })(BABYLON || (BABYLON = {}));
  15138. //# sourceMappingURL=babylon.cubeTexture.js.map
  15139. var __extends = this.__extends || function (d, b) {
  15140. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15141. function __() { this.constructor = d; }
  15142. __.prototype = b.prototype;
  15143. d.prototype = new __();
  15144. };
  15145. var BABYLON;
  15146. (function (BABYLON) {
  15147. var RenderTargetTexture = (function (_super) {
  15148. __extends(RenderTargetTexture, _super);
  15149. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  15150. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  15151. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  15152. _super.call(this, null, scene, !generateMipMaps);
  15153. this.renderList = new Array();
  15154. this.renderParticles = true;
  15155. this.renderSprites = false;
  15156. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  15157. this._currentRefreshId = -1;
  15158. this._refreshRate = 1;
  15159. this.name = name;
  15160. this.isRenderTarget = true;
  15161. this._size = size;
  15162. this._generateMipMaps = generateMipMaps;
  15163. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  15164. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  15165. // Rendering groups
  15166. this._renderingManager = new BABYLON.RenderingManager(scene);
  15167. }
  15168. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  15169. this._currentRefreshId = -1;
  15170. };
  15171. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  15172. get: function () {
  15173. return this._refreshRate;
  15174. },
  15175. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  15176. set: function (value) {
  15177. this._refreshRate = value;
  15178. this.resetRefreshCounter();
  15179. },
  15180. enumerable: true,
  15181. configurable: true
  15182. });
  15183. RenderTargetTexture.prototype._shouldRender = function () {
  15184. if (this._currentRefreshId === -1) {
  15185. this._currentRefreshId = 1;
  15186. return true;
  15187. }
  15188. if (this.refreshRate === this._currentRefreshId) {
  15189. this._currentRefreshId = 1;
  15190. return true;
  15191. }
  15192. this._currentRefreshId++;
  15193. return false;
  15194. };
  15195. RenderTargetTexture.prototype.isReady = function () {
  15196. if (!this.getScene().renderTargetsEnabled) {
  15197. return false;
  15198. }
  15199. return _super.prototype.isReady.call(this);
  15200. };
  15201. RenderTargetTexture.prototype.getRenderSize = function () {
  15202. return this._size;
  15203. };
  15204. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  15205. get: function () {
  15206. return true;
  15207. },
  15208. enumerable: true,
  15209. configurable: true
  15210. });
  15211. RenderTargetTexture.prototype.scale = function (ratio) {
  15212. var newSize = this._size * ratio;
  15213. this.resize(newSize, this._generateMipMaps);
  15214. };
  15215. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  15216. this.releaseInternalTexture();
  15217. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  15218. };
  15219. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  15220. var scene = this.getScene();
  15221. var engine = scene.getEngine();
  15222. if (this._waitingRenderList) {
  15223. this.renderList = [];
  15224. for (var index = 0; index < this._waitingRenderList.length; index++) {
  15225. var id = this._waitingRenderList[index];
  15226. this.renderList.push(scene.getMeshByID(id));
  15227. }
  15228. delete this._waitingRenderList;
  15229. }
  15230. if (this.renderList && this.renderList.length === 0) {
  15231. return;
  15232. }
  15233. // Bind
  15234. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  15235. engine.bindFramebuffer(this._texture);
  15236. }
  15237. this._renderingManager.reset();
  15238. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  15239. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  15240. var mesh = currentRenderList[meshIndex];
  15241. if (mesh) {
  15242. if (!mesh.isReady()) {
  15243. // Reset _currentRefreshId
  15244. this.resetRefreshCounter();
  15245. continue;
  15246. }
  15247. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  15248. mesh._activate(scene.getRenderId());
  15249. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  15250. var subMesh = mesh.subMeshes[subIndex];
  15251. scene._activeIndices += subMesh.indexCount;
  15252. this._renderingManager.dispatch(subMesh);
  15253. }
  15254. }
  15255. }
  15256. }
  15257. if (this.onBeforeRender) {
  15258. this.onBeforeRender();
  15259. }
  15260. // Clear
  15261. if (this.onClear) {
  15262. this.onClear(engine);
  15263. }
  15264. else {
  15265. engine.clear(scene.clearColor, true, true);
  15266. }
  15267. if (!this._doNotChangeAspectRatio) {
  15268. scene.updateTransformMatrix(true);
  15269. }
  15270. // Render
  15271. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  15272. if (useCameraPostProcess) {
  15273. scene.postProcessManager._finalizeFrame(false, this._texture);
  15274. }
  15275. if (!this._doNotChangeAspectRatio) {
  15276. scene.updateTransformMatrix(true);
  15277. }
  15278. if (this.onAfterRender) {
  15279. this.onAfterRender();
  15280. }
  15281. // Dump ?
  15282. if (dumpForDebug) {
  15283. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  15284. }
  15285. // Unbind
  15286. engine.unBindFramebuffer(this._texture);
  15287. if (this.onAfterUnbind) {
  15288. this.onAfterUnbind();
  15289. }
  15290. };
  15291. RenderTargetTexture.prototype.clone = function () {
  15292. var textureSize = this.getSize();
  15293. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  15294. // Base texture
  15295. newTexture.hasAlpha = this.hasAlpha;
  15296. newTexture.level = this.level;
  15297. // RenderTarget Texture
  15298. newTexture.coordinatesMode = this.coordinatesMode;
  15299. newTexture.renderList = this.renderList.slice(0);
  15300. return newTexture;
  15301. };
  15302. return RenderTargetTexture;
  15303. })(BABYLON.Texture);
  15304. BABYLON.RenderTargetTexture = RenderTargetTexture;
  15305. })(BABYLON || (BABYLON = {}));
  15306. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  15307. var __extends = this.__extends || function (d, b) {
  15308. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15309. function __() { this.constructor = d; }
  15310. __.prototype = b.prototype;
  15311. d.prototype = new __();
  15312. };
  15313. var BABYLON;
  15314. (function (BABYLON) {
  15315. var ProceduralTexture = (function (_super) {
  15316. __extends(ProceduralTexture, _super);
  15317. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  15318. if (generateMipMaps === void 0) { generateMipMaps = true; }
  15319. _super.call(this, null, scene, !generateMipMaps);
  15320. this._currentRefreshId = -1;
  15321. this._refreshRate = 1;
  15322. this._vertexDeclaration = [2];
  15323. this._vertexStrideSize = 2 * 4;
  15324. this._uniforms = new Array();
  15325. this._samplers = new Array();
  15326. this._textures = new Array();
  15327. this._floats = new Array();
  15328. this._floatsArrays = {};
  15329. this._colors3 = new Array();
  15330. this._colors4 = new Array();
  15331. this._vectors2 = new Array();
  15332. this._vectors3 = new Array();
  15333. this._matrices = new Array();
  15334. this._fallbackTextureUsed = false;
  15335. scene._proceduralTextures.push(this);
  15336. this.name = name;
  15337. this.isRenderTarget = true;
  15338. this._size = size;
  15339. this._generateMipMaps = generateMipMaps;
  15340. this.setFragment(fragment);
  15341. this._fallbackTexture = fallbackTexture;
  15342. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  15343. // VBO
  15344. var vertices = [];
  15345. vertices.push(1, 1);
  15346. vertices.push(-1, 1);
  15347. vertices.push(-1, -1);
  15348. vertices.push(1, -1);
  15349. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15350. // Indices
  15351. var indices = [];
  15352. indices.push(0);
  15353. indices.push(1);
  15354. indices.push(2);
  15355. indices.push(0);
  15356. indices.push(2);
  15357. indices.push(3);
  15358. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15359. }
  15360. ProceduralTexture.prototype.reset = function () {
  15361. if (this._effect === undefined) {
  15362. return;
  15363. }
  15364. var engine = this.getScene().getEngine();
  15365. engine._releaseEffect(this._effect);
  15366. };
  15367. ProceduralTexture.prototype.isReady = function () {
  15368. var _this = this;
  15369. var engine = this.getScene().getEngine();
  15370. var shaders;
  15371. if (!this._fragment) {
  15372. return false;
  15373. }
  15374. if (this._fallbackTextureUsed) {
  15375. return true;
  15376. }
  15377. if (this._fragment.fragmentElement !== undefined) {
  15378. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  15379. }
  15380. else {
  15381. shaders = { vertex: "procedural", fragment: this._fragment };
  15382. }
  15383. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  15384. _this.releaseInternalTexture();
  15385. if (_this._fallbackTexture) {
  15386. _this._texture = _this._fallbackTexture._texture;
  15387. _this._texture.references++;
  15388. }
  15389. _this._fallbackTextureUsed = true;
  15390. });
  15391. return this._effect.isReady();
  15392. };
  15393. ProceduralTexture.prototype.resetRefreshCounter = function () {
  15394. this._currentRefreshId = -1;
  15395. };
  15396. ProceduralTexture.prototype.setFragment = function (fragment) {
  15397. this._fragment = fragment;
  15398. };
  15399. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  15400. get: function () {
  15401. return this._refreshRate;
  15402. },
  15403. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  15404. set: function (value) {
  15405. this._refreshRate = value;
  15406. this.resetRefreshCounter();
  15407. },
  15408. enumerable: true,
  15409. configurable: true
  15410. });
  15411. ProceduralTexture.prototype._shouldRender = function () {
  15412. if (!this.isReady() || !this._texture) {
  15413. return false;
  15414. }
  15415. if (this._fallbackTextureUsed) {
  15416. return false;
  15417. }
  15418. if (this._currentRefreshId === -1) {
  15419. this._currentRefreshId = 1;
  15420. return true;
  15421. }
  15422. if (this.refreshRate === this._currentRefreshId) {
  15423. this._currentRefreshId = 1;
  15424. return true;
  15425. }
  15426. this._currentRefreshId++;
  15427. return false;
  15428. };
  15429. ProceduralTexture.prototype.getRenderSize = function () {
  15430. return this._size;
  15431. };
  15432. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  15433. if (this._fallbackTextureUsed) {
  15434. return;
  15435. }
  15436. this.releaseInternalTexture();
  15437. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  15438. };
  15439. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  15440. if (this._uniforms.indexOf(uniformName) === -1) {
  15441. this._uniforms.push(uniformName);
  15442. }
  15443. };
  15444. ProceduralTexture.prototype.setTexture = function (name, texture) {
  15445. if (this._samplers.indexOf(name) === -1) {
  15446. this._samplers.push(name);
  15447. }
  15448. this._textures[name] = texture;
  15449. return this;
  15450. };
  15451. ProceduralTexture.prototype.setFloat = function (name, value) {
  15452. this._checkUniform(name);
  15453. this._floats[name] = value;
  15454. return this;
  15455. };
  15456. ProceduralTexture.prototype.setFloats = function (name, value) {
  15457. this._checkUniform(name);
  15458. this._floatsArrays[name] = value;
  15459. return this;
  15460. };
  15461. ProceduralTexture.prototype.setColor3 = function (name, value) {
  15462. this._checkUniform(name);
  15463. this._colors3[name] = value;
  15464. return this;
  15465. };
  15466. ProceduralTexture.prototype.setColor4 = function (name, value) {
  15467. this._checkUniform(name);
  15468. this._colors4[name] = value;
  15469. return this;
  15470. };
  15471. ProceduralTexture.prototype.setVector2 = function (name, value) {
  15472. this._checkUniform(name);
  15473. this._vectors2[name] = value;
  15474. return this;
  15475. };
  15476. ProceduralTexture.prototype.setVector3 = function (name, value) {
  15477. this._checkUniform(name);
  15478. this._vectors3[name] = value;
  15479. return this;
  15480. };
  15481. ProceduralTexture.prototype.setMatrix = function (name, value) {
  15482. this._checkUniform(name);
  15483. this._matrices[name] = value;
  15484. return this;
  15485. };
  15486. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  15487. var scene = this.getScene();
  15488. var engine = scene.getEngine();
  15489. engine.bindFramebuffer(this._texture);
  15490. // Clear
  15491. engine.clear(scene.clearColor, true, true);
  15492. // Render
  15493. engine.enableEffect(this._effect);
  15494. engine.setState(false);
  15495. for (var name in this._textures) {
  15496. this._effect.setTexture(name, this._textures[name]);
  15497. }
  15498. for (name in this._floats) {
  15499. this._effect.setFloat(name, this._floats[name]);
  15500. }
  15501. for (name in this._floatsArrays) {
  15502. this._effect.setArray(name, this._floatsArrays[name]);
  15503. }
  15504. for (name in this._colors3) {
  15505. this._effect.setColor3(name, this._colors3[name]);
  15506. }
  15507. for (name in this._colors4) {
  15508. var color = this._colors4[name];
  15509. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  15510. }
  15511. for (name in this._vectors2) {
  15512. this._effect.setVector2(name, this._vectors2[name]);
  15513. }
  15514. for (name in this._vectors3) {
  15515. this._effect.setVector3(name, this._vectors3[name]);
  15516. }
  15517. for (name in this._matrices) {
  15518. this._effect.setMatrix(name, this._matrices[name]);
  15519. }
  15520. // VBOs
  15521. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15522. // Draw order
  15523. engine.draw(true, 0, 6);
  15524. // Unbind
  15525. engine.unBindFramebuffer(this._texture);
  15526. };
  15527. ProceduralTexture.prototype.clone = function () {
  15528. var textureSize = this.getSize();
  15529. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  15530. // Base texture
  15531. newTexture.hasAlpha = this.hasAlpha;
  15532. newTexture.level = this.level;
  15533. // RenderTarget Texture
  15534. newTexture.coordinatesMode = this.coordinatesMode;
  15535. return newTexture;
  15536. };
  15537. ProceduralTexture.prototype.dispose = function () {
  15538. var index = this.getScene()._proceduralTextures.indexOf(this);
  15539. if (index >= 0) {
  15540. this.getScene()._proceduralTextures.splice(index, 1);
  15541. }
  15542. _super.prototype.dispose.call(this);
  15543. };
  15544. return ProceduralTexture;
  15545. })(BABYLON.Texture);
  15546. BABYLON.ProceduralTexture = ProceduralTexture;
  15547. })(BABYLON || (BABYLON = {}));
  15548. //# sourceMappingURL=babylon.proceduralTexture.js.map
  15549. var __extends = this.__extends || function (d, b) {
  15550. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15551. function __() { this.constructor = d; }
  15552. __.prototype = b.prototype;
  15553. d.prototype = new __();
  15554. };
  15555. var BABYLON;
  15556. (function (BABYLON) {
  15557. var MirrorTexture = (function (_super) {
  15558. __extends(MirrorTexture, _super);
  15559. function MirrorTexture(name, size, scene, generateMipMaps) {
  15560. var _this = this;
  15561. _super.call(this, name, size, scene, generateMipMaps, true);
  15562. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  15563. this._transformMatrix = BABYLON.Matrix.Zero();
  15564. this._mirrorMatrix = BABYLON.Matrix.Zero();
  15565. this.onBeforeRender = function () {
  15566. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  15567. _this._savedViewMatrix = scene.getViewMatrix();
  15568. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  15569. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  15570. scene.clipPlane = _this.mirrorPlane;
  15571. scene.getEngine().cullBackFaces = false;
  15572. };
  15573. this.onAfterRender = function () {
  15574. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  15575. scene.getEngine().cullBackFaces = true;
  15576. delete scene.clipPlane;
  15577. };
  15578. }
  15579. MirrorTexture.prototype.clone = function () {
  15580. var textureSize = this.getSize();
  15581. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  15582. // Base texture
  15583. newTexture.hasAlpha = this.hasAlpha;
  15584. newTexture.level = this.level;
  15585. // Mirror Texture
  15586. newTexture.mirrorPlane = this.mirrorPlane.clone();
  15587. newTexture.renderList = this.renderList.slice(0);
  15588. return newTexture;
  15589. };
  15590. return MirrorTexture;
  15591. })(BABYLON.RenderTargetTexture);
  15592. BABYLON.MirrorTexture = MirrorTexture;
  15593. })(BABYLON || (BABYLON = {}));
  15594. //# sourceMappingURL=babylon.mirrorTexture.js.map
  15595. var __extends = this.__extends || function (d, b) {
  15596. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15597. function __() { this.constructor = d; }
  15598. __.prototype = b.prototype;
  15599. d.prototype = new __();
  15600. };
  15601. var BABYLON;
  15602. (function (BABYLON) {
  15603. var DynamicTexture = (function (_super) {
  15604. __extends(DynamicTexture, _super);
  15605. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  15606. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15607. _super.call(this, null, scene, !generateMipMaps);
  15608. this.name = name;
  15609. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15610. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15611. this._generateMipMaps = generateMipMaps;
  15612. if (options.getContext) {
  15613. this._canvas = options;
  15614. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  15615. }
  15616. else {
  15617. this._canvas = document.createElement("canvas");
  15618. if (options.width) {
  15619. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  15620. }
  15621. else {
  15622. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  15623. }
  15624. }
  15625. var textureSize = this.getSize();
  15626. this._canvas.width = textureSize.width;
  15627. this._canvas.height = textureSize.height;
  15628. this._context = this._canvas.getContext("2d");
  15629. }
  15630. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  15631. get: function () {
  15632. return true;
  15633. },
  15634. enumerable: true,
  15635. configurable: true
  15636. });
  15637. DynamicTexture.prototype.scale = function (ratio) {
  15638. var textureSize = this.getSize();
  15639. textureSize.width *= ratio;
  15640. textureSize.height *= ratio;
  15641. this._canvas.width = textureSize.width;
  15642. this._canvas.height = textureSize.height;
  15643. this.releaseInternalTexture();
  15644. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  15645. };
  15646. DynamicTexture.prototype.getContext = function () {
  15647. return this._context;
  15648. };
  15649. DynamicTexture.prototype.clear = function () {
  15650. var size = this.getSize();
  15651. this._context.fillRect(0, 0, size.width, size.height);
  15652. };
  15653. DynamicTexture.prototype.update = function (invertY) {
  15654. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  15655. };
  15656. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  15657. if (update === void 0) { update = true; }
  15658. var size = this.getSize();
  15659. if (clearColor) {
  15660. this._context.fillStyle = clearColor;
  15661. this._context.fillRect(0, 0, size.width, size.height);
  15662. }
  15663. this._context.font = font;
  15664. if (x === null) {
  15665. var textSize = this._context.measureText(text);
  15666. x = (size.width - textSize.width) / 2;
  15667. }
  15668. this._context.fillStyle = color;
  15669. this._context.fillText(text, x, y);
  15670. if (update) {
  15671. this.update(invertY);
  15672. }
  15673. };
  15674. DynamicTexture.prototype.clone = function () {
  15675. var textureSize = this.getSize();
  15676. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  15677. // Base texture
  15678. newTexture.hasAlpha = this.hasAlpha;
  15679. newTexture.level = this.level;
  15680. // Dynamic Texture
  15681. newTexture.wrapU = this.wrapU;
  15682. newTexture.wrapV = this.wrapV;
  15683. return newTexture;
  15684. };
  15685. return DynamicTexture;
  15686. })(BABYLON.Texture);
  15687. BABYLON.DynamicTexture = DynamicTexture;
  15688. })(BABYLON || (BABYLON = {}));
  15689. //# sourceMappingURL=babylon.dynamicTexture.js.map
  15690. var __extends = this.__extends || function (d, b) {
  15691. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15692. function __() { this.constructor = d; }
  15693. __.prototype = b.prototype;
  15694. d.prototype = new __();
  15695. };
  15696. var BABYLON;
  15697. (function (BABYLON) {
  15698. var VideoTexture = (function (_super) {
  15699. __extends(VideoTexture, _super);
  15700. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  15701. var _this = this;
  15702. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15703. _super.call(this, null, scene, !generateMipMaps, invertY);
  15704. this._autoLaunch = true;
  15705. this.name = name;
  15706. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  15707. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  15708. var requiredWidth = size.width || size;
  15709. var requiredHeight = size.height || size;
  15710. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  15711. var textureSize = this.getSize();
  15712. this.video = document.createElement("video");
  15713. this.video.width = textureSize.width;
  15714. this.video.height = textureSize.height;
  15715. this.video.autoplay = false;
  15716. this.video.loop = true;
  15717. this.video.addEventListener("canplaythrough", function () {
  15718. if (_this._texture) {
  15719. _this._texture.isReady = true;
  15720. }
  15721. });
  15722. urls.forEach(function (url) {
  15723. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  15724. var source = document.createElement("source");
  15725. source.src = url;
  15726. _this.video.appendChild(source);
  15727. });
  15728. this._lastUpdate = BABYLON.Tools.Now;
  15729. }
  15730. VideoTexture.prototype.update = function () {
  15731. if (this._autoLaunch) {
  15732. this._autoLaunch = false;
  15733. this.video.play();
  15734. }
  15735. var now = BABYLON.Tools.Now;
  15736. if (now - this._lastUpdate < 15) {
  15737. return false;
  15738. }
  15739. this._lastUpdate = now;
  15740. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  15741. return true;
  15742. };
  15743. return VideoTexture;
  15744. })(BABYLON.Texture);
  15745. BABYLON.VideoTexture = VideoTexture;
  15746. })(BABYLON || (BABYLON = {}));
  15747. //# sourceMappingURL=babylon.videoTexture.js.map
  15748. var __extends = this.__extends || function (d, b) {
  15749. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15750. function __() { this.constructor = d; }
  15751. __.prototype = b.prototype;
  15752. d.prototype = new __();
  15753. };
  15754. var BABYLON;
  15755. (function (BABYLON) {
  15756. var CustomProceduralTexture = (function (_super) {
  15757. __extends(CustomProceduralTexture, _super);
  15758. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  15759. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  15760. this._animate = true;
  15761. this._time = 0;
  15762. this._texturePath = texturePath;
  15763. //Try to load json
  15764. this.loadJson(texturePath);
  15765. this.refreshRate = 1;
  15766. }
  15767. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  15768. var _this = this;
  15769. var that = this;
  15770. function noConfigFile() {
  15771. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  15772. try {
  15773. that.setFragment(that._texturePath);
  15774. }
  15775. catch (ex) {
  15776. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  15777. }
  15778. }
  15779. var configFileUrl = jsonUrl + "/config.json";
  15780. var xhr = new XMLHttpRequest();
  15781. xhr.open("GET", configFileUrl, true);
  15782. xhr.addEventListener("load", function () {
  15783. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15784. try {
  15785. _this._config = JSON.parse(xhr.response);
  15786. _this.updateShaderUniforms();
  15787. _this.updateTextures();
  15788. _this.setFragment(_this._texturePath + "/custom");
  15789. _this._animate = _this._config.animate;
  15790. _this.refreshRate = _this._config.refreshrate;
  15791. }
  15792. catch (ex) {
  15793. noConfigFile();
  15794. }
  15795. }
  15796. else {
  15797. noConfigFile();
  15798. }
  15799. }, false);
  15800. xhr.addEventListener("error", function () {
  15801. noConfigFile();
  15802. }, false);
  15803. try {
  15804. xhr.send();
  15805. }
  15806. catch (ex) {
  15807. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  15808. }
  15809. };
  15810. CustomProceduralTexture.prototype.isReady = function () {
  15811. if (!_super.prototype.isReady.call(this)) {
  15812. return false;
  15813. }
  15814. for (var name in this._textures) {
  15815. var texture = this._textures[name];
  15816. if (!texture.isReady()) {
  15817. return false;
  15818. }
  15819. }
  15820. return true;
  15821. };
  15822. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  15823. if (this._animate) {
  15824. this._time += this.getScene().getAnimationRatio() * 0.03;
  15825. this.updateShaderUniforms();
  15826. }
  15827. _super.prototype.render.call(this, useCameraPostProcess);
  15828. };
  15829. CustomProceduralTexture.prototype.updateTextures = function () {
  15830. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  15831. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  15832. }
  15833. };
  15834. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  15835. if (this._config) {
  15836. for (var j = 0; j < this._config.uniforms.length; j++) {
  15837. var uniform = this._config.uniforms[j];
  15838. switch (uniform.type) {
  15839. case "float":
  15840. this.setFloat(uniform.name, uniform.value);
  15841. break;
  15842. case "color3":
  15843. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  15844. break;
  15845. case "color4":
  15846. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  15847. break;
  15848. case "vector2":
  15849. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  15850. break;
  15851. case "vector3":
  15852. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  15853. break;
  15854. }
  15855. }
  15856. }
  15857. this.setFloat("time", this._time);
  15858. };
  15859. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  15860. get: function () {
  15861. return this._animate;
  15862. },
  15863. set: function (value) {
  15864. this._animate = value;
  15865. },
  15866. enumerable: true,
  15867. configurable: true
  15868. });
  15869. return CustomProceduralTexture;
  15870. })(BABYLON.ProceduralTexture);
  15871. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  15872. })(BABYLON || (BABYLON = {}));
  15873. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  15874. var __extends = this.__extends || function (d, b) {
  15875. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15876. function __() { this.constructor = d; }
  15877. __.prototype = b.prototype;
  15878. d.prototype = new __();
  15879. };
  15880. var BABYLON;
  15881. (function (BABYLON) {
  15882. var WoodProceduralTexture = (function (_super) {
  15883. __extends(WoodProceduralTexture, _super);
  15884. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  15885. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  15886. this._ampScale = 100.0;
  15887. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  15888. this.updateShaderUniforms();
  15889. this.refreshRate = 0;
  15890. }
  15891. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  15892. this.setFloat("ampScale", this._ampScale);
  15893. this.setColor3("woodColor", this._woodColor);
  15894. };
  15895. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  15896. get: function () {
  15897. return this._ampScale;
  15898. },
  15899. set: function (value) {
  15900. this._ampScale = value;
  15901. this.updateShaderUniforms();
  15902. },
  15903. enumerable: true,
  15904. configurable: true
  15905. });
  15906. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  15907. get: function () {
  15908. return this._woodColor;
  15909. },
  15910. set: function (value) {
  15911. this._woodColor = value;
  15912. this.updateShaderUniforms();
  15913. },
  15914. enumerable: true,
  15915. configurable: true
  15916. });
  15917. return WoodProceduralTexture;
  15918. })(BABYLON.ProceduralTexture);
  15919. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  15920. var FireProceduralTexture = (function (_super) {
  15921. __extends(FireProceduralTexture, _super);
  15922. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  15923. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  15924. this._time = 0.0;
  15925. this._speed = new BABYLON.Vector2(0.5, 0.3);
  15926. this._autoGenerateTime = true;
  15927. this._alphaThreshold = 0.5;
  15928. this._fireColors = FireProceduralTexture.RedFireColors;
  15929. this.updateShaderUniforms();
  15930. this.refreshRate = 1;
  15931. }
  15932. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  15933. this.setFloat("time", this._time);
  15934. this.setVector2("speed", this._speed);
  15935. this.setColor3("c1", this._fireColors[0]);
  15936. this.setColor3("c2", this._fireColors[1]);
  15937. this.setColor3("c3", this._fireColors[2]);
  15938. this.setColor3("c4", this._fireColors[3]);
  15939. this.setColor3("c5", this._fireColors[4]);
  15940. this.setColor3("c6", this._fireColors[5]);
  15941. this.setFloat("alphaThreshold", this._alphaThreshold);
  15942. };
  15943. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  15944. if (this._autoGenerateTime) {
  15945. this._time += this.getScene().getAnimationRatio() * 0.03;
  15946. this.updateShaderUniforms();
  15947. }
  15948. _super.prototype.render.call(this, useCameraPostProcess);
  15949. };
  15950. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  15951. get: function () {
  15952. return [
  15953. new BABYLON.Color3(0.5, 0.0, 1.0),
  15954. new BABYLON.Color3(0.9, 0.0, 1.0),
  15955. new BABYLON.Color3(0.2, 0.0, 1.0),
  15956. new BABYLON.Color3(1.0, 0.9, 1.0),
  15957. new BABYLON.Color3(0.1, 0.1, 1.0),
  15958. new BABYLON.Color3(0.9, 0.9, 1.0)
  15959. ];
  15960. },
  15961. enumerable: true,
  15962. configurable: true
  15963. });
  15964. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  15965. get: function () {
  15966. return [
  15967. new BABYLON.Color3(0.5, 1.0, 0.0),
  15968. new BABYLON.Color3(0.5, 1.0, 0.0),
  15969. new BABYLON.Color3(0.3, 0.4, 0.0),
  15970. new BABYLON.Color3(0.5, 1.0, 0.0),
  15971. new BABYLON.Color3(0.2, 0.0, 0.0),
  15972. new BABYLON.Color3(0.5, 1.0, 0.0)
  15973. ];
  15974. },
  15975. enumerable: true,
  15976. configurable: true
  15977. });
  15978. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  15979. get: function () {
  15980. return [
  15981. new BABYLON.Color3(0.5, 0.0, 0.1),
  15982. new BABYLON.Color3(0.9, 0.0, 0.0),
  15983. new BABYLON.Color3(0.2, 0.0, 0.0),
  15984. new BABYLON.Color3(1.0, 0.9, 0.0),
  15985. new BABYLON.Color3(0.1, 0.1, 0.1),
  15986. new BABYLON.Color3(0.9, 0.9, 0.9)
  15987. ];
  15988. },
  15989. enumerable: true,
  15990. configurable: true
  15991. });
  15992. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  15993. get: function () {
  15994. return [
  15995. new BABYLON.Color3(0.1, 0.0, 0.5),
  15996. new BABYLON.Color3(0.0, 0.0, 0.5),
  15997. new BABYLON.Color3(0.1, 0.0, 0.2),
  15998. new BABYLON.Color3(0.0, 0.0, 1.0),
  15999. new BABYLON.Color3(0.1, 0.2, 0.3),
  16000. new BABYLON.Color3(0.0, 0.2, 0.9)
  16001. ];
  16002. },
  16003. enumerable: true,
  16004. configurable: true
  16005. });
  16006. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  16007. get: function () {
  16008. return this._fireColors;
  16009. },
  16010. set: function (value) {
  16011. this._fireColors = value;
  16012. this.updateShaderUniforms();
  16013. },
  16014. enumerable: true,
  16015. configurable: true
  16016. });
  16017. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  16018. get: function () {
  16019. return this._time;
  16020. },
  16021. set: function (value) {
  16022. this._time = value;
  16023. this.updateShaderUniforms();
  16024. },
  16025. enumerable: true,
  16026. configurable: true
  16027. });
  16028. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  16029. get: function () {
  16030. return this._speed;
  16031. },
  16032. set: function (value) {
  16033. this._speed = value;
  16034. this.updateShaderUniforms();
  16035. },
  16036. enumerable: true,
  16037. configurable: true
  16038. });
  16039. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  16040. get: function () {
  16041. return this._alphaThreshold;
  16042. },
  16043. set: function (value) {
  16044. this._alphaThreshold = value;
  16045. this.updateShaderUniforms();
  16046. },
  16047. enumerable: true,
  16048. configurable: true
  16049. });
  16050. return FireProceduralTexture;
  16051. })(BABYLON.ProceduralTexture);
  16052. BABYLON.FireProceduralTexture = FireProceduralTexture;
  16053. var CloudProceduralTexture = (function (_super) {
  16054. __extends(CloudProceduralTexture, _super);
  16055. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16056. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  16057. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  16058. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  16059. this.updateShaderUniforms();
  16060. this.refreshRate = 0;
  16061. }
  16062. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  16063. this.setColor3("skyColor", this._skyColor);
  16064. this.setColor3("cloudColor", this._cloudColor);
  16065. };
  16066. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  16067. get: function () {
  16068. return this._skyColor;
  16069. },
  16070. set: function (value) {
  16071. this._skyColor = value;
  16072. this.updateShaderUniforms();
  16073. },
  16074. enumerable: true,
  16075. configurable: true
  16076. });
  16077. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  16078. get: function () {
  16079. return this._cloudColor;
  16080. },
  16081. set: function (value) {
  16082. this._cloudColor = value;
  16083. this.updateShaderUniforms();
  16084. },
  16085. enumerable: true,
  16086. configurable: true
  16087. });
  16088. return CloudProceduralTexture;
  16089. })(BABYLON.ProceduralTexture);
  16090. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  16091. var GrassProceduralTexture = (function (_super) {
  16092. __extends(GrassProceduralTexture, _super);
  16093. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16094. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  16095. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  16096. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  16097. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  16098. this._groundColor = new BABYLON.Color3(1, 1, 1);
  16099. this._grassColors = [
  16100. new BABYLON.Color3(0.29, 0.38, 0.02),
  16101. new BABYLON.Color3(0.36, 0.49, 0.09),
  16102. new BABYLON.Color3(0.51, 0.6, 0.28)
  16103. ];
  16104. this.updateShaderUniforms();
  16105. this.refreshRate = 0;
  16106. }
  16107. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  16108. this.setColor3("herb1Color", this._grassColors[0]);
  16109. this.setColor3("herb2Color", this._grassColors[1]);
  16110. this.setColor3("herb3Color", this._grassColors[2]);
  16111. this.setColor3("groundColor", this._groundColor);
  16112. };
  16113. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  16114. get: function () {
  16115. return this._grassColors;
  16116. },
  16117. set: function (value) {
  16118. this._grassColors = value;
  16119. this.updateShaderUniforms();
  16120. },
  16121. enumerable: true,
  16122. configurable: true
  16123. });
  16124. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  16125. get: function () {
  16126. return this._groundColor;
  16127. },
  16128. set: function (value) {
  16129. this.groundColor = value;
  16130. this.updateShaderUniforms();
  16131. },
  16132. enumerable: true,
  16133. configurable: true
  16134. });
  16135. return GrassProceduralTexture;
  16136. })(BABYLON.ProceduralTexture);
  16137. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  16138. var RoadProceduralTexture = (function (_super) {
  16139. __extends(RoadProceduralTexture, _super);
  16140. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16141. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  16142. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  16143. this.updateShaderUniforms();
  16144. this.refreshRate = 0;
  16145. }
  16146. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  16147. this.setColor3("roadColor", this._roadColor);
  16148. };
  16149. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  16150. get: function () {
  16151. return this._roadColor;
  16152. },
  16153. set: function (value) {
  16154. this._roadColor = value;
  16155. this.updateShaderUniforms();
  16156. },
  16157. enumerable: true,
  16158. configurable: true
  16159. });
  16160. return RoadProceduralTexture;
  16161. })(BABYLON.ProceduralTexture);
  16162. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  16163. var BrickProceduralTexture = (function (_super) {
  16164. __extends(BrickProceduralTexture, _super);
  16165. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16166. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  16167. this._numberOfBricksHeight = 15;
  16168. this._numberOfBricksWidth = 5;
  16169. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  16170. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  16171. this.updateShaderUniforms();
  16172. this.refreshRate = 0;
  16173. }
  16174. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  16175. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  16176. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  16177. this.setColor3("brickColor", this._brickColor);
  16178. this.setColor3("jointColor", this._jointColor);
  16179. };
  16180. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  16181. get: function () {
  16182. return this._numberOfBricksHeight;
  16183. },
  16184. set: function (value) {
  16185. this._numberOfBricksHeight = value;
  16186. this.updateShaderUniforms();
  16187. },
  16188. enumerable: true,
  16189. configurable: true
  16190. });
  16191. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  16192. get: function () {
  16193. return this._numberOfBricksWidth;
  16194. },
  16195. set: function (value) {
  16196. this._numberOfBricksHeight = value;
  16197. this.updateShaderUniforms();
  16198. },
  16199. enumerable: true,
  16200. configurable: true
  16201. });
  16202. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  16203. get: function () {
  16204. return this._jointColor;
  16205. },
  16206. set: function (value) {
  16207. this._jointColor = value;
  16208. this.updateShaderUniforms();
  16209. },
  16210. enumerable: true,
  16211. configurable: true
  16212. });
  16213. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  16214. get: function () {
  16215. return this._brickColor;
  16216. },
  16217. set: function (value) {
  16218. this._brickColor = value;
  16219. this.updateShaderUniforms();
  16220. },
  16221. enumerable: true,
  16222. configurable: true
  16223. });
  16224. return BrickProceduralTexture;
  16225. })(BABYLON.ProceduralTexture);
  16226. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  16227. var MarbleProceduralTexture = (function (_super) {
  16228. __extends(MarbleProceduralTexture, _super);
  16229. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16230. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  16231. this._numberOfTilesHeight = 3;
  16232. this._numberOfTilesWidth = 3;
  16233. this._amplitude = 9.0;
  16234. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  16235. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  16236. this.updateShaderUniforms();
  16237. this.refreshRate = 0;
  16238. }
  16239. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  16240. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  16241. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  16242. this.setFloat("amplitude", this._amplitude);
  16243. this.setColor3("marbleColor", this._marbleColor);
  16244. this.setColor3("jointColor", this._jointColor);
  16245. };
  16246. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  16247. get: function () {
  16248. return this._numberOfTilesHeight;
  16249. },
  16250. set: function (value) {
  16251. this._numberOfTilesHeight = value;
  16252. this.updateShaderUniforms();
  16253. },
  16254. enumerable: true,
  16255. configurable: true
  16256. });
  16257. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  16258. get: function () {
  16259. return this._numberOfTilesWidth;
  16260. },
  16261. set: function (value) {
  16262. this._numberOfTilesWidth = value;
  16263. this.updateShaderUniforms();
  16264. },
  16265. enumerable: true,
  16266. configurable: true
  16267. });
  16268. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  16269. get: function () {
  16270. return this._jointColor;
  16271. },
  16272. set: function (value) {
  16273. this._jointColor = value;
  16274. this.updateShaderUniforms();
  16275. },
  16276. enumerable: true,
  16277. configurable: true
  16278. });
  16279. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  16280. get: function () {
  16281. return this._marbleColor;
  16282. },
  16283. set: function (value) {
  16284. this._marbleColor = value;
  16285. this.updateShaderUniforms();
  16286. },
  16287. enumerable: true,
  16288. configurable: true
  16289. });
  16290. return MarbleProceduralTexture;
  16291. })(BABYLON.ProceduralTexture);
  16292. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  16293. })(BABYLON || (BABYLON = {}));
  16294. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  16295. var BABYLON;
  16296. (function (BABYLON) {
  16297. var EffectFallbacks = (function () {
  16298. function EffectFallbacks() {
  16299. this._defines = {};
  16300. this._currentRank = 32;
  16301. this._maxRank = -1;
  16302. }
  16303. EffectFallbacks.prototype.addFallback = function (rank, define) {
  16304. if (!this._defines[rank]) {
  16305. if (rank < this._currentRank) {
  16306. this._currentRank = rank;
  16307. }
  16308. if (rank > this._maxRank) {
  16309. this._maxRank = rank;
  16310. }
  16311. this._defines[rank] = new Array();
  16312. }
  16313. this._defines[rank].push(define);
  16314. };
  16315. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  16316. get: function () {
  16317. return this._currentRank <= this._maxRank;
  16318. },
  16319. enumerable: true,
  16320. configurable: true
  16321. });
  16322. EffectFallbacks.prototype.reduce = function (currentDefines) {
  16323. var currentFallbacks = this._defines[this._currentRank];
  16324. for (var index = 0; index < currentFallbacks.length; index++) {
  16325. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  16326. }
  16327. this._currentRank++;
  16328. return currentDefines;
  16329. };
  16330. return EffectFallbacks;
  16331. })();
  16332. BABYLON.EffectFallbacks = EffectFallbacks;
  16333. var Effect = (function () {
  16334. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  16335. var _this = this;
  16336. this._isReady = false;
  16337. this._compilationError = "";
  16338. this._valueCache = [];
  16339. this._engine = engine;
  16340. this.name = baseName;
  16341. this.defines = defines;
  16342. this._uniformsNames = uniformsNames.concat(samplers);
  16343. this._samplers = samplers;
  16344. this._attributesNames = attributesNames;
  16345. this.onError = onError;
  16346. this.onCompiled = onCompiled;
  16347. var vertexSource;
  16348. var fragmentSource;
  16349. if (baseName.vertexElement) {
  16350. vertexSource = document.getElementById(baseName.vertexElement);
  16351. if (!vertexSource) {
  16352. vertexSource = baseName.vertexElement;
  16353. }
  16354. }
  16355. else {
  16356. vertexSource = baseName.vertex || baseName;
  16357. }
  16358. if (baseName.fragmentElement) {
  16359. fragmentSource = document.getElementById(baseName.fragmentElement);
  16360. if (!fragmentSource) {
  16361. fragmentSource = baseName.fragmentElement;
  16362. }
  16363. }
  16364. else {
  16365. fragmentSource = baseName.fragment || baseName;
  16366. }
  16367. this._loadVertexShader(vertexSource, function (vertexCode) {
  16368. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  16369. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  16370. });
  16371. });
  16372. }
  16373. // Properties
  16374. Effect.prototype.isReady = function () {
  16375. return this._isReady;
  16376. };
  16377. Effect.prototype.getProgram = function () {
  16378. return this._program;
  16379. };
  16380. Effect.prototype.getAttributesNames = function () {
  16381. return this._attributesNames;
  16382. };
  16383. Effect.prototype.getAttributeLocation = function (index) {
  16384. return this._attributes[index];
  16385. };
  16386. Effect.prototype.getAttributeLocationByName = function (name) {
  16387. var index = this._attributesNames.indexOf(name);
  16388. return this._attributes[index];
  16389. };
  16390. Effect.prototype.getAttributesCount = function () {
  16391. return this._attributes.length;
  16392. };
  16393. Effect.prototype.getUniformIndex = function (uniformName) {
  16394. return this._uniformsNames.indexOf(uniformName);
  16395. };
  16396. Effect.prototype.getUniform = function (uniformName) {
  16397. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  16398. };
  16399. Effect.prototype.getSamplers = function () {
  16400. return this._samplers;
  16401. };
  16402. Effect.prototype.getCompilationError = function () {
  16403. return this._compilationError;
  16404. };
  16405. // Methods
  16406. Effect.prototype._loadVertexShader = function (vertex, callback) {
  16407. // DOM element ?
  16408. if (vertex instanceof HTMLElement) {
  16409. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  16410. callback(vertexCode);
  16411. return;
  16412. }
  16413. // Is in local store ?
  16414. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  16415. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  16416. return;
  16417. }
  16418. var vertexShaderUrl;
  16419. if (vertex[0] === ".") {
  16420. vertexShaderUrl = vertex;
  16421. }
  16422. else {
  16423. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  16424. }
  16425. // Vertex shader
  16426. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  16427. };
  16428. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  16429. // DOM element ?
  16430. if (fragment instanceof HTMLElement) {
  16431. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  16432. callback(fragmentCode);
  16433. return;
  16434. }
  16435. // Is in local store ?
  16436. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  16437. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  16438. return;
  16439. }
  16440. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  16441. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  16442. return;
  16443. }
  16444. var fragmentShaderUrl;
  16445. if (fragment[0] === ".") {
  16446. fragmentShaderUrl = fragment;
  16447. }
  16448. else {
  16449. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  16450. }
  16451. // Fragment shader
  16452. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  16453. };
  16454. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  16455. try {
  16456. var engine = this._engine;
  16457. if (!engine.getCaps().highPrecisionShaderSupported) {
  16458. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  16459. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  16460. }
  16461. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  16462. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  16463. this._attributes = engine.getAttributes(this._program, attributesNames);
  16464. for (var index = 0; index < this._samplers.length; index++) {
  16465. var sampler = this.getUniform(this._samplers[index]);
  16466. if (sampler == null) {
  16467. this._samplers.splice(index, 1);
  16468. index--;
  16469. }
  16470. }
  16471. engine.bindSamplers(this);
  16472. this._isReady = true;
  16473. if (this.onCompiled) {
  16474. this.onCompiled(this);
  16475. }
  16476. }
  16477. catch (e) {
  16478. // Is it a problem with precision?
  16479. if (e.message.indexOf("highp") !== -1) {
  16480. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  16481. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  16482. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  16483. return;
  16484. }
  16485. // Let's go through fallbacks then
  16486. if (fallbacks && fallbacks.isMoreFallbacks) {
  16487. defines = fallbacks.reduce(defines);
  16488. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  16489. }
  16490. else {
  16491. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  16492. BABYLON.Tools.Error("Defines: " + defines);
  16493. BABYLON.Tools.Error("Error: " + e.message);
  16494. this._compilationError = e.message;
  16495. if (this.onError) {
  16496. this.onError(this, this._compilationError);
  16497. }
  16498. }
  16499. }
  16500. };
  16501. Effect.prototype._bindTexture = function (channel, texture) {
  16502. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  16503. };
  16504. Effect.prototype.setTexture = function (channel, texture) {
  16505. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  16506. };
  16507. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16508. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  16509. };
  16510. //public _cacheMatrix(uniformName, matrix) {
  16511. // if (!this._valueCache[uniformName]) {
  16512. // this._valueCache[uniformName] = new BABYLON.Matrix();
  16513. // }
  16514. // for (var index = 0; index < 16; index++) {
  16515. // this._valueCache[uniformName].m[index] = matrix.m[index];
  16516. // }
  16517. //};
  16518. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  16519. if (!this._valueCache[uniformName]) {
  16520. this._valueCache[uniformName] = [x, y];
  16521. return;
  16522. }
  16523. this._valueCache[uniformName][0] = x;
  16524. this._valueCache[uniformName][1] = y;
  16525. };
  16526. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  16527. if (!this._valueCache[uniformName]) {
  16528. this._valueCache[uniformName] = [x, y, z];
  16529. return;
  16530. }
  16531. this._valueCache[uniformName][0] = x;
  16532. this._valueCache[uniformName][1] = y;
  16533. this._valueCache[uniformName][2] = z;
  16534. };
  16535. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  16536. if (!this._valueCache[uniformName]) {
  16537. this._valueCache[uniformName] = [x, y, z, w];
  16538. return;
  16539. }
  16540. this._valueCache[uniformName][0] = x;
  16541. this._valueCache[uniformName][1] = y;
  16542. this._valueCache[uniformName][2] = z;
  16543. this._valueCache[uniformName][3] = w;
  16544. };
  16545. Effect.prototype.setArray = function (uniformName, array) {
  16546. this._engine.setArray(this.getUniform(uniformName), array);
  16547. return this;
  16548. };
  16549. Effect.prototype.setArray2 = function (uniformName, array) {
  16550. this._engine.setArray2(this.getUniform(uniformName), array);
  16551. return this;
  16552. };
  16553. Effect.prototype.setArray3 = function (uniformName, array) {
  16554. this._engine.setArray3(this.getUniform(uniformName), array);
  16555. return this;
  16556. };
  16557. Effect.prototype.setArray4 = function (uniformName, array) {
  16558. this._engine.setArray4(this.getUniform(uniformName), array);
  16559. return this;
  16560. };
  16561. Effect.prototype.setMatrices = function (uniformName, matrices) {
  16562. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  16563. return this;
  16564. };
  16565. Effect.prototype.setMatrix = function (uniformName, matrix) {
  16566. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  16567. // return;
  16568. //this._cacheMatrix(uniformName, matrix);
  16569. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  16570. return this;
  16571. };
  16572. Effect.prototype.setFloat = function (uniformName, value) {
  16573. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  16574. return this;
  16575. this._valueCache[uniformName] = value;
  16576. this._engine.setFloat(this.getUniform(uniformName), value);
  16577. return this;
  16578. };
  16579. Effect.prototype.setBool = function (uniformName, bool) {
  16580. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  16581. return this;
  16582. this._valueCache[uniformName] = bool;
  16583. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  16584. return this;
  16585. };
  16586. Effect.prototype.setVector2 = function (uniformName, vector2) {
  16587. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  16588. return this;
  16589. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  16590. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  16591. return this;
  16592. };
  16593. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  16594. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  16595. return this;
  16596. this._cacheFloat2(uniformName, x, y);
  16597. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  16598. return this;
  16599. };
  16600. Effect.prototype.setVector3 = function (uniformName, vector3) {
  16601. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  16602. return this;
  16603. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  16604. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  16605. return this;
  16606. };
  16607. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  16608. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  16609. return this;
  16610. this._cacheFloat3(uniformName, x, y, z);
  16611. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  16612. return this;
  16613. };
  16614. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  16615. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  16616. return this;
  16617. this._cacheFloat4(uniformName, x, y, z, w);
  16618. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  16619. return this;
  16620. };
  16621. Effect.prototype.setColor3 = function (uniformName, color3) {
  16622. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  16623. return this;
  16624. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  16625. this._engine.setColor3(this.getUniform(uniformName), color3);
  16626. return this;
  16627. };
  16628. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  16629. 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)
  16630. return this;
  16631. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  16632. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  16633. return this;
  16634. };
  16635. // Statics
  16636. Effect.ShadersStore = {};
  16637. return Effect;
  16638. })();
  16639. BABYLON.Effect = Effect;
  16640. })(BABYLON || (BABYLON = {}));
  16641. //# sourceMappingURL=babylon.effect.js.map
  16642. var BABYLON;
  16643. (function (BABYLON) {
  16644. var Material = (function () {
  16645. function Material(name, scene, doNotAdd) {
  16646. this.name = name;
  16647. this.checkReadyOnEveryCall = true;
  16648. this.checkReadyOnlyOnce = false;
  16649. this.state = "";
  16650. this.alpha = 1.0;
  16651. this.backFaceCulling = true;
  16652. this._wasPreviouslyReady = false;
  16653. this._fillMode = Material.TriangleFillMode;
  16654. this.pointSize = 1.0;
  16655. this.zOffset = 0;
  16656. this.id = name;
  16657. this._scene = scene;
  16658. if (!doNotAdd) {
  16659. scene.materials.push(this);
  16660. }
  16661. }
  16662. Object.defineProperty(Material, "TriangleFillMode", {
  16663. get: function () {
  16664. return Material._TriangleFillMode;
  16665. },
  16666. enumerable: true,
  16667. configurable: true
  16668. });
  16669. Object.defineProperty(Material, "WireFrameFillMode", {
  16670. get: function () {
  16671. return Material._WireFrameFillMode;
  16672. },
  16673. enumerable: true,
  16674. configurable: true
  16675. });
  16676. Object.defineProperty(Material, "PointFillMode", {
  16677. get: function () {
  16678. return Material._PointFillMode;
  16679. },
  16680. enumerable: true,
  16681. configurable: true
  16682. });
  16683. Object.defineProperty(Material.prototype, "wireframe", {
  16684. get: function () {
  16685. return this._fillMode === Material.WireFrameFillMode;
  16686. },
  16687. set: function (value) {
  16688. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  16689. },
  16690. enumerable: true,
  16691. configurable: true
  16692. });
  16693. Object.defineProperty(Material.prototype, "pointsCloud", {
  16694. get: function () {
  16695. return this._fillMode === Material.PointFillMode;
  16696. },
  16697. set: function (value) {
  16698. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  16699. },
  16700. enumerable: true,
  16701. configurable: true
  16702. });
  16703. Object.defineProperty(Material.prototype, "fillMode", {
  16704. get: function () {
  16705. return this._fillMode;
  16706. },
  16707. set: function (value) {
  16708. this._fillMode = value;
  16709. },
  16710. enumerable: true,
  16711. configurable: true
  16712. });
  16713. Material.prototype.isReady = function (mesh, useInstances) {
  16714. return true;
  16715. };
  16716. Material.prototype.getEffect = function () {
  16717. return this._effect;
  16718. };
  16719. Material.prototype.getScene = function () {
  16720. return this._scene;
  16721. };
  16722. Material.prototype.needAlphaBlending = function () {
  16723. return (this.alpha < 1.0);
  16724. };
  16725. Material.prototype.needAlphaTesting = function () {
  16726. return false;
  16727. };
  16728. Material.prototype.getAlphaTestTexture = function () {
  16729. return null;
  16730. };
  16731. Material.prototype.trackCreation = function (onCompiled, onError) {
  16732. };
  16733. Material.prototype._preBind = function () {
  16734. var engine = this._scene.getEngine();
  16735. engine.enableEffect(this._effect);
  16736. engine.setState(this.backFaceCulling, this.zOffset);
  16737. };
  16738. Material.prototype.bind = function (world, mesh) {
  16739. this._scene._cachedMaterial = this;
  16740. if (this.onBind) {
  16741. this.onBind(this, mesh);
  16742. }
  16743. };
  16744. Material.prototype.bindOnlyWorldMatrix = function (world) {
  16745. };
  16746. Material.prototype.unbind = function () {
  16747. };
  16748. Material.prototype.dispose = function (forceDisposeEffect) {
  16749. // Remove from scene
  16750. var index = this._scene.materials.indexOf(this);
  16751. this._scene.materials.splice(index, 1);
  16752. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  16753. if (forceDisposeEffect && this._effect) {
  16754. this._scene.getEngine()._releaseEffect(this._effect);
  16755. this._effect = null;
  16756. }
  16757. // Callback
  16758. if (this.onDispose) {
  16759. this.onDispose();
  16760. }
  16761. };
  16762. Material._TriangleFillMode = 0;
  16763. Material._WireFrameFillMode = 1;
  16764. Material._PointFillMode = 2;
  16765. return Material;
  16766. })();
  16767. BABYLON.Material = Material;
  16768. })(BABYLON || (BABYLON = {}));
  16769. //# sourceMappingURL=babylon.material.js.map
  16770. var __extends = this.__extends || function (d, b) {
  16771. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16772. function __() { this.constructor = d; }
  16773. __.prototype = b.prototype;
  16774. d.prototype = new __();
  16775. };
  16776. var BABYLON;
  16777. (function (BABYLON) {
  16778. var maxSimultaneousLights = 4;
  16779. var FresnelParameters = (function () {
  16780. function FresnelParameters() {
  16781. this.isEnabled = true;
  16782. this.leftColor = BABYLON.Color3.White();
  16783. this.rightColor = BABYLON.Color3.Black();
  16784. this.bias = 0;
  16785. this.power = 1;
  16786. }
  16787. return FresnelParameters;
  16788. })();
  16789. BABYLON.FresnelParameters = FresnelParameters;
  16790. var StandardMaterial = (function (_super) {
  16791. __extends(StandardMaterial, _super);
  16792. function StandardMaterial(name, scene) {
  16793. var _this = this;
  16794. _super.call(this, name, scene);
  16795. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16796. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  16797. this.specularColor = new BABYLON.Color3(1, 1, 1);
  16798. this.specularPower = 64;
  16799. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  16800. this.useAlphaFromDiffuseTexture = false;
  16801. this.useSpecularOverAlpha = true;
  16802. this.fogEnabled = true;
  16803. this._cachedDefines = null;
  16804. this._renderTargets = new BABYLON.SmartArray(16);
  16805. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  16806. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  16807. this._scaledDiffuse = new BABYLON.Color3();
  16808. this._scaledSpecular = new BABYLON.Color3();
  16809. this.getRenderTargetTextures = function () {
  16810. _this._renderTargets.reset();
  16811. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  16812. _this._renderTargets.push(_this.reflectionTexture);
  16813. }
  16814. return _this._renderTargets;
  16815. };
  16816. }
  16817. StandardMaterial.prototype.needAlphaBlending = function () {
  16818. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  16819. };
  16820. StandardMaterial.prototype.needAlphaTesting = function () {
  16821. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  16822. };
  16823. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  16824. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  16825. };
  16826. StandardMaterial.prototype.getAlphaTestTexture = function () {
  16827. return this.diffuseTexture;
  16828. };
  16829. // Methods
  16830. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  16831. if (this.checkReadyOnlyOnce) {
  16832. if (this._wasPreviouslyReady) {
  16833. return true;
  16834. }
  16835. }
  16836. var scene = this.getScene();
  16837. if (!this.checkReadyOnEveryCall) {
  16838. if (this._renderId === scene.getRenderId()) {
  16839. return true;
  16840. }
  16841. }
  16842. var engine = scene.getEngine();
  16843. var defines = [];
  16844. var fallbacks = new BABYLON.EffectFallbacks();
  16845. var needNormals = false;
  16846. var needUVs = false;
  16847. // Textures
  16848. if (scene.texturesEnabled) {
  16849. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  16850. if (!this.diffuseTexture.isReady()) {
  16851. return false;
  16852. }
  16853. else {
  16854. needUVs = true;
  16855. defines.push("#define DIFFUSE");
  16856. }
  16857. }
  16858. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  16859. if (!this.ambientTexture.isReady()) {
  16860. return false;
  16861. }
  16862. else {
  16863. needUVs = true;
  16864. defines.push("#define AMBIENT");
  16865. }
  16866. }
  16867. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  16868. if (!this.opacityTexture.isReady()) {
  16869. return false;
  16870. }
  16871. else {
  16872. needUVs = true;
  16873. defines.push("#define OPACITY");
  16874. if (this.opacityTexture.getAlphaFromRGB) {
  16875. defines.push("#define OPACITYRGB");
  16876. }
  16877. }
  16878. }
  16879. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  16880. if (!this.reflectionTexture.isReady()) {
  16881. return false;
  16882. }
  16883. else {
  16884. needNormals = true;
  16885. needUVs = true;
  16886. defines.push("#define REFLECTION");
  16887. fallbacks.addFallback(0, "REFLECTION");
  16888. }
  16889. }
  16890. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  16891. if (!this.emissiveTexture.isReady()) {
  16892. return false;
  16893. }
  16894. else {
  16895. needUVs = true;
  16896. defines.push("#define EMISSIVE");
  16897. }
  16898. }
  16899. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  16900. if (!this.specularTexture.isReady()) {
  16901. return false;
  16902. }
  16903. else {
  16904. needUVs = true;
  16905. defines.push("#define SPECULAR");
  16906. fallbacks.addFallback(0, "SPECULAR");
  16907. }
  16908. }
  16909. }
  16910. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  16911. if (!this.bumpTexture.isReady()) {
  16912. return false;
  16913. }
  16914. else {
  16915. needUVs = true;
  16916. defines.push("#define BUMP");
  16917. fallbacks.addFallback(0, "BUMP");
  16918. }
  16919. }
  16920. // Effect
  16921. if (this.useSpecularOverAlpha) {
  16922. defines.push("#define SPECULAROVERALPHA");
  16923. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  16924. }
  16925. if (scene.clipPlane) {
  16926. defines.push("#define CLIPPLANE");
  16927. }
  16928. if (engine.getAlphaTesting()) {
  16929. defines.push("#define ALPHATEST");
  16930. }
  16931. if (this._shouldUseAlphaFromDiffuseTexture()) {
  16932. defines.push("#define ALPHAFROMDIFFUSE");
  16933. }
  16934. // Point size
  16935. if (this.pointsCloud || scene.forcePointsCloud) {
  16936. defines.push("#define POINTSIZE");
  16937. }
  16938. // Fog
  16939. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  16940. defines.push("#define FOG");
  16941. fallbacks.addFallback(1, "FOG");
  16942. }
  16943. var shadowsActivated = false;
  16944. var lightIndex = 0;
  16945. if (scene.lightsEnabled) {
  16946. for (var index = 0; index < scene.lights.length; index++) {
  16947. var light = scene.lights[index];
  16948. if (!light.isEnabled()) {
  16949. continue;
  16950. }
  16951. // Excluded check
  16952. if (light._excludedMeshesIds.length > 0) {
  16953. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  16954. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  16955. if (excludedMesh) {
  16956. light.excludedMeshes.push(excludedMesh);
  16957. }
  16958. }
  16959. light._excludedMeshesIds = [];
  16960. }
  16961. // Included check
  16962. if (light._includedOnlyMeshesIds.length > 0) {
  16963. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  16964. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  16965. if (includedOnlyMesh) {
  16966. light.includedOnlyMeshes.push(includedOnlyMesh);
  16967. }
  16968. }
  16969. light._includedOnlyMeshesIds = [];
  16970. }
  16971. if (!light.canAffectMesh(mesh)) {
  16972. continue;
  16973. }
  16974. needNormals = true;
  16975. defines.push("#define LIGHT" + lightIndex);
  16976. if (lightIndex > 0) {
  16977. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  16978. }
  16979. var type;
  16980. if (light instanceof BABYLON.SpotLight) {
  16981. type = "#define SPOTLIGHT" + lightIndex;
  16982. }
  16983. else if (light instanceof BABYLON.HemisphericLight) {
  16984. type = "#define HEMILIGHT" + lightIndex;
  16985. }
  16986. else {
  16987. type = "#define POINTDIRLIGHT" + lightIndex;
  16988. }
  16989. defines.push(type);
  16990. if (lightIndex > 0) {
  16991. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  16992. }
  16993. // Shadows
  16994. if (scene.shadowsEnabled) {
  16995. var shadowGenerator = light.getShadowGenerator();
  16996. if (mesh && mesh.receiveShadows && shadowGenerator) {
  16997. defines.push("#define SHADOW" + lightIndex);
  16998. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  16999. if (!shadowsActivated) {
  17000. defines.push("#define SHADOWS");
  17001. shadowsActivated = true;
  17002. }
  17003. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  17004. defines.push("#define SHADOWVSM" + lightIndex);
  17005. if (lightIndex > 0) {
  17006. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  17007. }
  17008. }
  17009. if (shadowGenerator.usePoissonSampling) {
  17010. defines.push("#define SHADOWPCF" + lightIndex);
  17011. if (lightIndex > 0) {
  17012. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  17013. }
  17014. }
  17015. }
  17016. }
  17017. lightIndex++;
  17018. if (lightIndex === maxSimultaneousLights)
  17019. break;
  17020. }
  17021. }
  17022. if (StandardMaterial.FresnelEnabled) {
  17023. // Fresnel
  17024. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  17025. var fresnelRank = 1;
  17026. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  17027. defines.push("#define DIFFUSEFRESNEL");
  17028. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  17029. fresnelRank++;
  17030. }
  17031. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  17032. defines.push("#define OPACITYFRESNEL");
  17033. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  17034. fresnelRank++;
  17035. }
  17036. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  17037. defines.push("#define REFLECTIONFRESNEL");
  17038. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  17039. fresnelRank++;
  17040. }
  17041. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  17042. defines.push("#define EMISSIVEFRESNEL");
  17043. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  17044. fresnelRank++;
  17045. }
  17046. needNormals = true;
  17047. defines.push("#define FRESNEL");
  17048. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  17049. }
  17050. }
  17051. // Attribs
  17052. var attribs = [BABYLON.VertexBuffer.PositionKind];
  17053. if (mesh) {
  17054. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17055. attribs.push(BABYLON.VertexBuffer.NormalKind);
  17056. defines.push("#define NORMAL");
  17057. }
  17058. if (needUVs) {
  17059. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17060. attribs.push(BABYLON.VertexBuffer.UVKind);
  17061. defines.push("#define UV1");
  17062. }
  17063. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17064. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  17065. defines.push("#define UV2");
  17066. }
  17067. }
  17068. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17069. attribs.push(BABYLON.VertexBuffer.ColorKind);
  17070. defines.push("#define VERTEXCOLOR");
  17071. if (mesh.hasVertexAlpha) {
  17072. defines.push("#define VERTEXALPHA");
  17073. }
  17074. }
  17075. if (mesh.useBones) {
  17076. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17077. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17078. defines.push("#define BONES");
  17079. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  17080. defines.push("#define BONES4");
  17081. fallbacks.addFallback(0, "BONES4");
  17082. }
  17083. // Instances
  17084. if (useInstances) {
  17085. defines.push("#define INSTANCES");
  17086. attribs.push("world0");
  17087. attribs.push("world1");
  17088. attribs.push("world2");
  17089. attribs.push("world3");
  17090. }
  17091. }
  17092. // Get correct effect
  17093. var join = defines.join("\n");
  17094. if (this._cachedDefines !== join) {
  17095. this._cachedDefines = join;
  17096. scene.resetCachedMaterial();
  17097. // Legacy browser patch
  17098. var shaderName = "default";
  17099. if (!scene.getEngine().getCaps().standardDerivatives) {
  17100. shaderName = "legacydefault";
  17101. }
  17102. 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);
  17103. }
  17104. if (!this._effect.isReady()) {
  17105. return false;
  17106. }
  17107. this._renderId = scene.getRenderId();
  17108. this._wasPreviouslyReady = true;
  17109. return true;
  17110. };
  17111. StandardMaterial.prototype.unbind = function () {
  17112. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  17113. this._effect.setTexture("reflection2DSampler", null);
  17114. }
  17115. };
  17116. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  17117. this._effect.setMatrix("world", world);
  17118. };
  17119. StandardMaterial.prototype.bind = function (world, mesh) {
  17120. var scene = this.getScene();
  17121. // Matrices
  17122. this.bindOnlyWorldMatrix(world);
  17123. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  17124. // Bones
  17125. if (mesh && mesh.useBones) {
  17126. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  17127. }
  17128. if (scene.getCachedMaterial() !== this) {
  17129. if (StandardMaterial.FresnelEnabled) {
  17130. // Fresnel
  17131. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  17132. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  17133. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  17134. }
  17135. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  17136. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  17137. }
  17138. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  17139. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  17140. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  17141. }
  17142. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  17143. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  17144. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  17145. }
  17146. }
  17147. // Textures
  17148. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  17149. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  17150. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  17151. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  17152. }
  17153. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  17154. this._effect.setTexture("ambientSampler", this.ambientTexture);
  17155. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  17156. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  17157. }
  17158. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  17159. this._effect.setTexture("opacitySampler", this.opacityTexture);
  17160. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  17161. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  17162. }
  17163. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  17164. if (this.reflectionTexture.isCube) {
  17165. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  17166. }
  17167. else {
  17168. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  17169. }
  17170. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  17171. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  17172. }
  17173. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  17174. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  17175. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  17176. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  17177. }
  17178. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  17179. this._effect.setTexture("specularSampler", this.specularTexture);
  17180. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  17181. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  17182. }
  17183. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  17184. this._effect.setTexture("bumpSampler", this.bumpTexture);
  17185. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  17186. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  17187. }
  17188. // Clip plane
  17189. if (scene.clipPlane) {
  17190. var clipPlane = scene.clipPlane;
  17191. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  17192. }
  17193. // Point size
  17194. if (this.pointsCloud) {
  17195. this._effect.setFloat("pointSize", this.pointSize);
  17196. }
  17197. // Colors
  17198. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  17199. // Scaling down color according to emissive
  17200. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  17201. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  17202. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  17203. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  17204. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  17205. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  17206. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  17207. }
  17208. // Scaling down color according to emissive
  17209. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  17210. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  17211. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  17212. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  17213. if (scene.lightsEnabled) {
  17214. var lightIndex = 0;
  17215. for (var index = 0; index < scene.lights.length; index++) {
  17216. var light = scene.lights[index];
  17217. if (!light.isEnabled()) {
  17218. continue;
  17219. }
  17220. if (!light.canAffectMesh(mesh)) {
  17221. continue;
  17222. }
  17223. if (light instanceof BABYLON.PointLight) {
  17224. // Point Light
  17225. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  17226. }
  17227. else if (light instanceof BABYLON.DirectionalLight) {
  17228. // Directional Light
  17229. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  17230. }
  17231. else if (light instanceof BABYLON.SpotLight) {
  17232. // Spot Light
  17233. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  17234. }
  17235. else if (light instanceof BABYLON.HemisphericLight) {
  17236. // Hemispheric Light
  17237. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  17238. }
  17239. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  17240. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  17241. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  17242. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  17243. // Shadows
  17244. if (scene.shadowsEnabled) {
  17245. var shadowGenerator = light.getShadowGenerator();
  17246. if (mesh.receiveShadows && shadowGenerator) {
  17247. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  17248. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  17249. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  17250. }
  17251. }
  17252. lightIndex++;
  17253. if (lightIndex === maxSimultaneousLights)
  17254. break;
  17255. }
  17256. }
  17257. // View
  17258. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  17259. this._effect.setMatrix("view", scene.getViewMatrix());
  17260. }
  17261. // Fog
  17262. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  17263. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  17264. this._effect.setColor3("vFogColor", scene.fogColor);
  17265. }
  17266. _super.prototype.bind.call(this, world, mesh);
  17267. };
  17268. StandardMaterial.prototype.getAnimatables = function () {
  17269. var results = [];
  17270. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  17271. results.push(this.diffuseTexture);
  17272. }
  17273. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  17274. results.push(this.ambientTexture);
  17275. }
  17276. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  17277. results.push(this.opacityTexture);
  17278. }
  17279. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  17280. results.push(this.reflectionTexture);
  17281. }
  17282. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  17283. results.push(this.emissiveTexture);
  17284. }
  17285. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  17286. results.push(this.specularTexture);
  17287. }
  17288. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  17289. results.push(this.bumpTexture);
  17290. }
  17291. return results;
  17292. };
  17293. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  17294. if (this.diffuseTexture) {
  17295. this.diffuseTexture.dispose();
  17296. }
  17297. if (this.ambientTexture) {
  17298. this.ambientTexture.dispose();
  17299. }
  17300. if (this.opacityTexture) {
  17301. this.opacityTexture.dispose();
  17302. }
  17303. if (this.reflectionTexture) {
  17304. this.reflectionTexture.dispose();
  17305. }
  17306. if (this.emissiveTexture) {
  17307. this.emissiveTexture.dispose();
  17308. }
  17309. if (this.specularTexture) {
  17310. this.specularTexture.dispose();
  17311. }
  17312. if (this.bumpTexture) {
  17313. this.bumpTexture.dispose();
  17314. }
  17315. _super.prototype.dispose.call(this, forceDisposeEffect);
  17316. };
  17317. StandardMaterial.prototype.clone = function (name) {
  17318. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  17319. // Base material
  17320. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  17321. newStandardMaterial.alpha = this.alpha;
  17322. newStandardMaterial.fillMode = this.fillMode;
  17323. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  17324. // Standard material
  17325. if (this.diffuseTexture && this.diffuseTexture.clone) {
  17326. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  17327. }
  17328. if (this.ambientTexture && this.ambientTexture.clone) {
  17329. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  17330. }
  17331. if (this.opacityTexture && this.opacityTexture.clone) {
  17332. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  17333. }
  17334. if (this.reflectionTexture && this.reflectionTexture.clone) {
  17335. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  17336. }
  17337. if (this.emissiveTexture && this.emissiveTexture.clone) {
  17338. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  17339. }
  17340. if (this.specularTexture && this.specularTexture.clone) {
  17341. newStandardMaterial.specularTexture = this.specularTexture.clone();
  17342. }
  17343. if (this.bumpTexture && this.bumpTexture.clone) {
  17344. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  17345. }
  17346. newStandardMaterial.ambientColor = this.ambientColor.clone();
  17347. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  17348. newStandardMaterial.specularColor = this.specularColor.clone();
  17349. newStandardMaterial.specularPower = this.specularPower;
  17350. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  17351. return newStandardMaterial;
  17352. };
  17353. // Statics
  17354. // Flags used to enable or disable a type of texture for all Standard Materials
  17355. StandardMaterial.DiffuseTextureEnabled = true;
  17356. StandardMaterial.AmbientTextureEnabled = true;
  17357. StandardMaterial.OpacityTextureEnabled = true;
  17358. StandardMaterial.ReflectionTextureEnabled = true;
  17359. StandardMaterial.EmissiveTextureEnabled = true;
  17360. StandardMaterial.SpecularTextureEnabled = true;
  17361. StandardMaterial.BumpTextureEnabled = true;
  17362. StandardMaterial.FresnelEnabled = true;
  17363. return StandardMaterial;
  17364. })(BABYLON.Material);
  17365. BABYLON.StandardMaterial = StandardMaterial;
  17366. })(BABYLON || (BABYLON = {}));
  17367. //# sourceMappingURL=babylon.standardMaterial.js.map
  17368. var __extends = this.__extends || function (d, b) {
  17369. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17370. function __() { this.constructor = d; }
  17371. __.prototype = b.prototype;
  17372. d.prototype = new __();
  17373. };
  17374. var BABYLON;
  17375. (function (BABYLON) {
  17376. var MultiMaterial = (function (_super) {
  17377. __extends(MultiMaterial, _super);
  17378. function MultiMaterial(name, scene) {
  17379. _super.call(this, name, scene, true);
  17380. this.subMaterials = new Array();
  17381. scene.multiMaterials.push(this);
  17382. }
  17383. // Properties
  17384. MultiMaterial.prototype.getSubMaterial = function (index) {
  17385. if (index < 0 || index >= this.subMaterials.length) {
  17386. return this.getScene().defaultMaterial;
  17387. }
  17388. return this.subMaterials[index];
  17389. };
  17390. // Methods
  17391. MultiMaterial.prototype.isReady = function (mesh) {
  17392. for (var index = 0; index < this.subMaterials.length; index++) {
  17393. var subMaterial = this.subMaterials[index];
  17394. if (subMaterial) {
  17395. if (!this.subMaterials[index].isReady(mesh)) {
  17396. return false;
  17397. }
  17398. }
  17399. }
  17400. return true;
  17401. };
  17402. MultiMaterial.prototype.clone = function (name) {
  17403. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  17404. for (var index = 0; index < this.subMaterials.length; index++) {
  17405. var subMaterial = this.subMaterials[index];
  17406. newMultiMaterial.subMaterials.push(subMaterial);
  17407. }
  17408. return newMultiMaterial;
  17409. };
  17410. return MultiMaterial;
  17411. })(BABYLON.Material);
  17412. BABYLON.MultiMaterial = MultiMaterial;
  17413. })(BABYLON || (BABYLON = {}));
  17414. //# sourceMappingURL=babylon.multiMaterial.js.map
  17415. var BABYLON;
  17416. (function (BABYLON) {
  17417. var SceneLoader = (function () {
  17418. function SceneLoader() {
  17419. }
  17420. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17421. get: function () {
  17422. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17423. },
  17424. set: function (value) {
  17425. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17426. },
  17427. enumerable: true,
  17428. configurable: true
  17429. });
  17430. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17431. get: function () {
  17432. return SceneLoader._ShowLoadingScreen;
  17433. },
  17434. set: function (value) {
  17435. SceneLoader._ShowLoadingScreen = value;
  17436. },
  17437. enumerable: true,
  17438. configurable: true
  17439. });
  17440. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17441. var dotPosition = sceneFilename.lastIndexOf(".");
  17442. var queryStringPosition = sceneFilename.indexOf("?");
  17443. if (queryStringPosition === -1) {
  17444. queryStringPosition = sceneFilename.length;
  17445. }
  17446. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17447. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17448. var plugin = this._registeredPlugins[index];
  17449. if (plugin.extensions.indexOf(extension) !== -1) {
  17450. return plugin;
  17451. }
  17452. }
  17453. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17454. };
  17455. // Public functions
  17456. SceneLoader.RegisterPlugin = function (plugin) {
  17457. plugin.extensions = plugin.extensions.toLowerCase();
  17458. SceneLoader._registeredPlugins.push(plugin);
  17459. };
  17460. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17461. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  17462. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  17463. return;
  17464. }
  17465. var manifestChecked = function (success) {
  17466. scene.database = database;
  17467. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17468. var importMeshFromData = function (data) {
  17469. var meshes = [];
  17470. var particleSystems = [];
  17471. var skeletons = [];
  17472. try {
  17473. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17474. if (onerror) {
  17475. onerror(scene, 'unable to load the scene');
  17476. }
  17477. return;
  17478. }
  17479. }
  17480. catch (e) {
  17481. if (onerror) {
  17482. onerror(scene, e);
  17483. }
  17484. return;
  17485. }
  17486. if (onsuccess) {
  17487. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17488. onsuccess(meshes, particleSystems, skeletons);
  17489. }
  17490. };
  17491. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17492. // Direct load
  17493. importMeshFromData(sceneFilename.substr(5));
  17494. return;
  17495. }
  17496. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17497. importMeshFromData(data);
  17498. }, progressCallBack, database);
  17499. };
  17500. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17501. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17502. };
  17503. /**
  17504. * Load a scene
  17505. * @param rootUrl a string that defines the root url for scene and resources
  17506. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17507. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17508. */
  17509. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17510. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17511. };
  17512. /**
  17513. * Append a scene
  17514. * @param rootUrl a string that defines the root url for scene and resources
  17515. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17516. * @param scene is the instance of BABYLON.Scene to append to
  17517. */
  17518. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17519. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  17520. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  17521. return;
  17522. }
  17523. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17524. var database;
  17525. if (SceneLoader.ShowLoadingScreen) {
  17526. scene.getEngine().displayLoadingUI();
  17527. }
  17528. var loadSceneFromData = function (data) {
  17529. scene.database = database;
  17530. if (!plugin.load(scene, data, rootUrl)) {
  17531. if (onerror) {
  17532. onerror(scene);
  17533. }
  17534. scene.getEngine().hideLoadingUI();
  17535. return;
  17536. }
  17537. if (onsuccess) {
  17538. onsuccess(scene);
  17539. }
  17540. if (SceneLoader.ShowLoadingScreen) {
  17541. scene.executeWhenReady(function () {
  17542. scene.getEngine().hideLoadingUI();
  17543. });
  17544. }
  17545. };
  17546. var manifestChecked = function (success) {
  17547. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17548. };
  17549. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17550. // Direct load
  17551. loadSceneFromData(sceneFilename.substr(5));
  17552. return;
  17553. }
  17554. if (rootUrl.indexOf("file:") === -1) {
  17555. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17556. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17557. }
  17558. else {
  17559. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17560. }
  17561. };
  17562. // Flags
  17563. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17564. SceneLoader._ShowLoadingScreen = true;
  17565. // Members
  17566. SceneLoader._registeredPlugins = new Array();
  17567. return SceneLoader;
  17568. })();
  17569. BABYLON.SceneLoader = SceneLoader;
  17570. ;
  17571. })(BABYLON || (BABYLON = {}));
  17572. //# sourceMappingURL=babylon.sceneLoader.js.map
  17573. var BABYLON;
  17574. (function (BABYLON) {
  17575. var Internals;
  17576. (function (Internals) {
  17577. var checkColors4 = function (colors, count) {
  17578. // Check if color3 was used
  17579. if (colors.length === count * 3) {
  17580. var colors4 = [];
  17581. for (var index = 0; index < colors.length; index += 3) {
  17582. var newIndex = (index / 3) * 4;
  17583. colors4[newIndex] = colors[index];
  17584. colors4[newIndex + 1] = colors[index + 1];
  17585. colors4[newIndex + 2] = colors[index + 2];
  17586. colors4[newIndex + 3] = 1.0;
  17587. }
  17588. return colors4;
  17589. }
  17590. return colors;
  17591. };
  17592. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  17593. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  17594. texture.name = parsedTexture.name;
  17595. texture.hasAlpha = parsedTexture.hasAlpha;
  17596. texture.level = parsedTexture.level;
  17597. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17598. return texture;
  17599. };
  17600. var loadTexture = function (rootUrl, parsedTexture, scene) {
  17601. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17602. return null;
  17603. }
  17604. if (parsedTexture.isCube) {
  17605. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17606. }
  17607. var texture;
  17608. if (parsedTexture.mirrorPlane) {
  17609. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17610. texture._waitingRenderList = parsedTexture.renderList;
  17611. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17612. }
  17613. else if (parsedTexture.isRenderTarget) {
  17614. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17615. texture._waitingRenderList = parsedTexture.renderList;
  17616. }
  17617. else {
  17618. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17619. }
  17620. texture.name = parsedTexture.name;
  17621. texture.hasAlpha = parsedTexture.hasAlpha;
  17622. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17623. texture.level = parsedTexture.level;
  17624. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17625. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17626. texture.uOffset = parsedTexture.uOffset;
  17627. texture.vOffset = parsedTexture.vOffset;
  17628. texture.uScale = parsedTexture.uScale;
  17629. texture.vScale = parsedTexture.vScale;
  17630. texture.uAng = parsedTexture.uAng;
  17631. texture.vAng = parsedTexture.vAng;
  17632. texture.wAng = parsedTexture.wAng;
  17633. texture.wrapU = parsedTexture.wrapU;
  17634. texture.wrapV = parsedTexture.wrapV;
  17635. // Animations
  17636. if (parsedTexture.animations) {
  17637. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17638. var parsedAnimation = parsedTexture.animations[animationIndex];
  17639. texture.animations.push(parseAnimation(parsedAnimation));
  17640. }
  17641. }
  17642. return texture;
  17643. };
  17644. var parseSkeleton = function (parsedSkeleton, scene) {
  17645. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  17646. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  17647. var parsedBone = parsedSkeleton.bones[index];
  17648. var parentBone = null;
  17649. if (parsedBone.parentBoneIndex > -1) {
  17650. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  17651. }
  17652. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  17653. if (parsedBone.animation) {
  17654. bone.animations.push(parseAnimation(parsedBone.animation));
  17655. }
  17656. }
  17657. return skeleton;
  17658. };
  17659. var parseFresnelParameters = function (parsedFresnelParameters) {
  17660. var fresnelParameters = new BABYLON.FresnelParameters();
  17661. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  17662. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  17663. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  17664. fresnelParameters.bias = parsedFresnelParameters.bias;
  17665. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  17666. return fresnelParameters;
  17667. };
  17668. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  17669. var material;
  17670. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  17671. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  17672. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  17673. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  17674. material.specularPower = parsedMaterial.specularPower;
  17675. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  17676. material.alpha = parsedMaterial.alpha;
  17677. material.id = parsedMaterial.id;
  17678. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  17679. material.backFaceCulling = parsedMaterial.backFaceCulling;
  17680. material.wireframe = parsedMaterial.wireframe;
  17681. if (parsedMaterial.diffuseTexture) {
  17682. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  17683. }
  17684. if (parsedMaterial.diffuseFresnelParameters) {
  17685. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  17686. }
  17687. if (parsedMaterial.ambientTexture) {
  17688. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  17689. }
  17690. if (parsedMaterial.opacityTexture) {
  17691. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  17692. }
  17693. if (parsedMaterial.opacityFresnelParameters) {
  17694. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  17695. }
  17696. if (parsedMaterial.reflectionTexture) {
  17697. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  17698. }
  17699. if (parsedMaterial.reflectionFresnelParameters) {
  17700. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  17701. }
  17702. if (parsedMaterial.emissiveTexture) {
  17703. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  17704. }
  17705. if (parsedMaterial.emissiveFresnelParameters) {
  17706. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  17707. }
  17708. if (parsedMaterial.specularTexture) {
  17709. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  17710. }
  17711. if (parsedMaterial.bumpTexture) {
  17712. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  17713. }
  17714. return material;
  17715. };
  17716. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  17717. for (var index = 0; index < parsedData.materials.length; index++) {
  17718. var parsedMaterial = parsedData.materials[index];
  17719. if (parsedMaterial.id === id) {
  17720. return parseMaterial(parsedMaterial, scene, rootUrl);
  17721. }
  17722. }
  17723. return null;
  17724. };
  17725. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  17726. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17727. multiMaterial.id = parsedMultiMaterial.id;
  17728. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17729. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17730. var subMatId = parsedMultiMaterial.materials[matIndex];
  17731. if (subMatId) {
  17732. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17733. }
  17734. else {
  17735. multiMaterial.subMaterials.push(null);
  17736. }
  17737. }
  17738. return multiMaterial;
  17739. };
  17740. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17741. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17742. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17743. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17744. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17745. var parsedFlare = parsedLensFlareSystem.flares[index];
  17746. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17747. }
  17748. return lensFlareSystem;
  17749. };
  17750. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17751. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17752. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17753. if (parsedParticleSystem.textureName) {
  17754. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17755. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17756. }
  17757. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17758. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17759. particleSystem.minSize = parsedParticleSystem.minSize;
  17760. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17761. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17762. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17763. particleSystem.emitter = emitter;
  17764. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17765. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17766. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17767. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17768. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17769. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17770. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17771. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17772. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17773. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17774. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17775. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17776. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17777. particleSystem.start();
  17778. return particleSystem;
  17779. };
  17780. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17781. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17782. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17783. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17784. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17785. shadowGenerator.getShadowMap().renderList.push(mesh);
  17786. }
  17787. if (parsedShadowGenerator.usePoissonSampling) {
  17788. shadowGenerator.usePoissonSampling = true;
  17789. }
  17790. else if (parsedShadowGenerator.useVarianceShadowMap) {
  17791. shadowGenerator.useVarianceShadowMap = true;
  17792. }
  17793. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  17794. shadowGenerator.useBlurVarianceShadowMap = true;
  17795. if (parsedShadowGenerator.blurScale) {
  17796. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  17797. }
  17798. if (parsedShadowGenerator.blurBoxOffset) {
  17799. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  17800. }
  17801. }
  17802. if (parsedShadowGenerator.bias !== undefined) {
  17803. shadowGenerator.bias = parsedShadowGenerator.bias;
  17804. }
  17805. return shadowGenerator;
  17806. };
  17807. var parseAnimation = function (parsedAnimation) {
  17808. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17809. var dataType = parsedAnimation.dataType;
  17810. var keys = [];
  17811. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17812. var key = parsedAnimation.keys[index];
  17813. var data;
  17814. switch (dataType) {
  17815. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17816. data = key.values[0];
  17817. break;
  17818. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17819. data = BABYLON.Quaternion.FromArray(key.values);
  17820. break;
  17821. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17822. data = BABYLON.Matrix.FromArray(key.values);
  17823. break;
  17824. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17825. default:
  17826. data = BABYLON.Vector3.FromArray(key.values);
  17827. break;
  17828. }
  17829. keys.push({
  17830. frame: key.frame,
  17831. value: data
  17832. });
  17833. }
  17834. animation.setKeys(keys);
  17835. return animation;
  17836. };
  17837. var parseLight = function (parsedLight, scene) {
  17838. var light;
  17839. switch (parsedLight.type) {
  17840. case 0:
  17841. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17842. break;
  17843. case 1:
  17844. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17845. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17846. break;
  17847. case 2:
  17848. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  17849. break;
  17850. case 3:
  17851. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17852. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  17853. break;
  17854. }
  17855. light.id = parsedLight.id;
  17856. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  17857. if (parsedLight.intensity !== undefined) {
  17858. light.intensity = parsedLight.intensity;
  17859. }
  17860. if (parsedLight.range) {
  17861. light.range = parsedLight.range;
  17862. }
  17863. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  17864. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  17865. if (parsedLight.excludedMeshesIds) {
  17866. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17867. }
  17868. // Parent
  17869. if (parsedLight.parentId) {
  17870. light._waitingParentId = parsedLight.parentId;
  17871. }
  17872. if (parsedLight.includedOnlyMeshesIds) {
  17873. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17874. }
  17875. // Animations
  17876. if (parsedLight.animations) {
  17877. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17878. var parsedAnimation = parsedLight.animations[animationIndex];
  17879. light.animations.push(parseAnimation(parsedAnimation));
  17880. }
  17881. }
  17882. if (parsedLight.autoAnimate) {
  17883. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  17884. }
  17885. };
  17886. var parseCamera = function (parsedCamera, scene) {
  17887. var camera;
  17888. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  17889. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  17890. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  17891. var alpha = parsedCamera.alpha;
  17892. var beta = parsedCamera.beta;
  17893. var radius = parsedCamera.radius;
  17894. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  17895. var eye_space = parsedCamera.eye_space;
  17896. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  17897. }
  17898. else {
  17899. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  17900. }
  17901. }
  17902. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  17903. eye_space = parsedCamera.eye_space;
  17904. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  17905. }
  17906. else if (parsedCamera.type === "DeviceOrientationCamera") {
  17907. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  17908. }
  17909. else if (parsedCamera.type === "FollowCamera") {
  17910. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  17911. camera.heightOffset = parsedCamera.heightOffset;
  17912. camera.radius = parsedCamera.radius;
  17913. camera.rotationOffset = parsedCamera.rotationOffset;
  17914. if (lockedTargetMesh)
  17915. camera.target = lockedTargetMesh;
  17916. }
  17917. else if (parsedCamera.type === "GamepadCamera") {
  17918. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  17919. }
  17920. else if (parsedCamera.type === "OculusCamera") {
  17921. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  17922. }
  17923. else if (parsedCamera.type === "OculusGamepadCamera") {
  17924. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  17925. }
  17926. else if (parsedCamera.type === "TouchCamera") {
  17927. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  17928. }
  17929. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  17930. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  17931. }
  17932. else if (parsedCamera.type === "WebVRCamera") {
  17933. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  17934. }
  17935. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  17936. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  17937. }
  17938. else {
  17939. // Free Camera is the default value
  17940. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  17941. }
  17942. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  17943. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  17944. camera.lockedTarget = lockedTargetMesh;
  17945. }
  17946. camera.id = parsedCamera.id;
  17947. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  17948. // Parent
  17949. if (parsedCamera.parentId) {
  17950. camera._waitingParentId = parsedCamera.parentId;
  17951. }
  17952. // Target
  17953. if (parsedCamera.target) {
  17954. if (camera.setTarget) {
  17955. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17956. }
  17957. else {
  17958. //For ArcRotate
  17959. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  17960. }
  17961. }
  17962. else {
  17963. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  17964. }
  17965. camera.fov = parsedCamera.fov;
  17966. camera.minZ = parsedCamera.minZ;
  17967. camera.maxZ = parsedCamera.maxZ;
  17968. camera.speed = parsedCamera.speed;
  17969. camera.inertia = parsedCamera.inertia;
  17970. camera.checkCollisions = parsedCamera.checkCollisions;
  17971. camera.applyGravity = parsedCamera.applyGravity;
  17972. if (parsedCamera.ellipsoid) {
  17973. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  17974. }
  17975. // Animations
  17976. if (parsedCamera.animations) {
  17977. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17978. var parsedAnimation = parsedCamera.animations[animationIndex];
  17979. camera.animations.push(parseAnimation(parsedAnimation));
  17980. }
  17981. }
  17982. if (parsedCamera.autoAnimate) {
  17983. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  17984. }
  17985. // Layer Mask
  17986. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  17987. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  17988. }
  17989. else {
  17990. camera.layerMask = 0xFFFFFFFF;
  17991. }
  17992. return camera;
  17993. };
  17994. var parseGeometry = function (parsedGeometry, scene) {
  17995. var id = parsedGeometry.id;
  17996. return scene.getGeometryByID(id);
  17997. };
  17998. var parseBox = function (parsedBox, scene) {
  17999. if (parseGeometry(parsedBox, scene)) {
  18000. return null; // null since geometry could be something else than a box...
  18001. }
  18002. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  18003. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  18004. scene.pushGeometry(box, true);
  18005. return box;
  18006. };
  18007. var parseSphere = function (parsedSphere, scene) {
  18008. if (parseGeometry(parsedSphere, scene)) {
  18009. return null; // null since geometry could be something else than a sphere...
  18010. }
  18011. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18012. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18013. scene.pushGeometry(sphere, true);
  18014. return sphere;
  18015. };
  18016. var parseCylinder = function (parsedCylinder, scene) {
  18017. if (parseGeometry(parsedCylinder, scene)) {
  18018. return null; // null since geometry could be something else than a cylinder...
  18019. }
  18020. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18021. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18022. scene.pushGeometry(cylinder, true);
  18023. return cylinder;
  18024. };
  18025. var parseTorus = function (parsedTorus, scene) {
  18026. if (parseGeometry(parsedTorus, scene)) {
  18027. return null; // null since geometry could be something else than a torus...
  18028. }
  18029. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18030. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18031. scene.pushGeometry(torus, true);
  18032. return torus;
  18033. };
  18034. var parseGround = function (parsedGround, scene) {
  18035. if (parseGeometry(parsedGround, scene)) {
  18036. return null; // null since geometry could be something else than a ground...
  18037. }
  18038. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18039. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18040. scene.pushGeometry(ground, true);
  18041. return ground;
  18042. };
  18043. var parsePlane = function (parsedPlane, scene) {
  18044. if (parseGeometry(parsedPlane, scene)) {
  18045. return null; // null since geometry could be something else than a plane...
  18046. }
  18047. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18048. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18049. scene.pushGeometry(plane, true);
  18050. return plane;
  18051. };
  18052. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18053. if (parseGeometry(parsedTorusKnot, scene)) {
  18054. return null; // null since geometry could be something else than a torusKnot...
  18055. }
  18056. 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);
  18057. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18058. scene.pushGeometry(torusKnot, true);
  18059. return torusKnot;
  18060. };
  18061. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18062. if (parseGeometry(parsedVertexData, scene)) {
  18063. return null; // null since geometry could be a primitive
  18064. }
  18065. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18066. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18067. if (parsedVertexData.delayLoadingFile) {
  18068. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18069. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18070. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18071. geometry._delayInfo = [];
  18072. if (parsedVertexData.hasUVs) {
  18073. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18074. }
  18075. if (parsedVertexData.hasUVs2) {
  18076. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18077. }
  18078. if (parsedVertexData.hasColors) {
  18079. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18080. }
  18081. if (parsedVertexData.hasMatricesIndices) {
  18082. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18083. }
  18084. if (parsedVertexData.hasMatricesWeights) {
  18085. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18086. }
  18087. geometry._delayLoadingFunction = importVertexData;
  18088. }
  18089. else {
  18090. importVertexData(parsedVertexData, geometry);
  18091. }
  18092. scene.pushGeometry(geometry, true);
  18093. return geometry;
  18094. };
  18095. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18096. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18097. mesh.id = parsedMesh.id;
  18098. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18099. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18100. if (parsedMesh.rotationQuaternion) {
  18101. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18102. }
  18103. else if (parsedMesh.rotation) {
  18104. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18105. }
  18106. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18107. if (parsedMesh.localMatrix) {
  18108. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18109. }
  18110. else if (parsedMesh.pivotMatrix) {
  18111. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18112. }
  18113. mesh.setEnabled(parsedMesh.isEnabled);
  18114. mesh.isVisible = parsedMesh.isVisible;
  18115. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18116. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18117. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18118. if (parsedMesh.applyFog !== undefined) {
  18119. mesh.applyFog = parsedMesh.applyFog;
  18120. }
  18121. if (parsedMesh.pickable !== undefined) {
  18122. mesh.isPickable = parsedMesh.pickable;
  18123. }
  18124. if (parsedMesh.alphaIndex !== undefined) {
  18125. mesh.alphaIndex = parsedMesh.alphaIndex;
  18126. }
  18127. mesh.receiveShadows = parsedMesh.receiveShadows;
  18128. mesh.billboardMode = parsedMesh.billboardMode;
  18129. if (parsedMesh.visibility !== undefined) {
  18130. mesh.visibility = parsedMesh.visibility;
  18131. }
  18132. mesh.checkCollisions = parsedMesh.checkCollisions;
  18133. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18134. // Parent
  18135. if (parsedMesh.parentId) {
  18136. mesh._waitingParentId = parsedMesh.parentId;
  18137. }
  18138. // Actions
  18139. if (parsedMesh.actions !== undefined) {
  18140. mesh._waitingActions = parsedMesh.actions;
  18141. }
  18142. // Geometry
  18143. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18144. if (parsedMesh.delayLoadingFile) {
  18145. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18146. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18147. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18148. if (parsedMesh._binaryInfo) {
  18149. mesh._binaryInfo = parsedMesh._binaryInfo;
  18150. }
  18151. mesh._delayInfo = [];
  18152. if (parsedMesh.hasUVs) {
  18153. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18154. }
  18155. if (parsedMesh.hasUVs2) {
  18156. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18157. }
  18158. if (parsedMesh.hasColors) {
  18159. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18160. }
  18161. if (parsedMesh.hasMatricesIndices) {
  18162. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18163. }
  18164. if (parsedMesh.hasMatricesWeights) {
  18165. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18166. }
  18167. mesh._delayLoadingFunction = importGeometry;
  18168. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18169. mesh._checkDelayState();
  18170. }
  18171. }
  18172. else {
  18173. importGeometry(parsedMesh, mesh);
  18174. }
  18175. // Material
  18176. if (parsedMesh.materialId) {
  18177. mesh.setMaterialByID(parsedMesh.materialId);
  18178. }
  18179. else {
  18180. mesh.material = null;
  18181. }
  18182. // Skeleton
  18183. if (parsedMesh.skeletonId > -1) {
  18184. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18185. }
  18186. // Physics
  18187. if (parsedMesh.physicsImpostor) {
  18188. if (!scene.isPhysicsEnabled()) {
  18189. scene.enablePhysics();
  18190. }
  18191. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18192. }
  18193. // Animations
  18194. if (parsedMesh.animations) {
  18195. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18196. var parsedAnimation = parsedMesh.animations[animationIndex];
  18197. mesh.animations.push(parseAnimation(parsedAnimation));
  18198. }
  18199. }
  18200. if (parsedMesh.autoAnimate) {
  18201. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18202. }
  18203. // Layer Mask
  18204. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18205. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18206. }
  18207. else {
  18208. mesh.layerMask = 0xFFFFFFFF;
  18209. }
  18210. // Instances
  18211. if (parsedMesh.instances) {
  18212. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18213. var parsedInstance = parsedMesh.instances[index];
  18214. var instance = mesh.createInstance(parsedInstance.name);
  18215. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18216. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18217. if (parsedInstance.rotationQuaternion) {
  18218. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18219. }
  18220. else if (parsedInstance.rotation) {
  18221. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18222. }
  18223. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18224. instance.checkCollisions = mesh.checkCollisions;
  18225. if (parsedMesh.animations) {
  18226. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18227. parsedAnimation = parsedMesh.animations[animationIndex];
  18228. instance.animations.push(parseAnimation(parsedAnimation));
  18229. }
  18230. }
  18231. }
  18232. }
  18233. return mesh;
  18234. };
  18235. var parseActions = function (parsedActions, object, scene) {
  18236. var actionManager = new BABYLON.ActionManager(scene);
  18237. if (object === null)
  18238. scene.actionManager = actionManager;
  18239. else
  18240. object.actionManager = actionManager;
  18241. // instanciate a new object
  18242. var instanciate = function (name, params) {
  18243. var newInstance = Object.create(BABYLON[name].prototype);
  18244. newInstance.constructor.apply(newInstance, params);
  18245. return newInstance;
  18246. };
  18247. var parseParameter = function (name, value, target, propertyPath) {
  18248. if (propertyPath === null) {
  18249. // String, boolean or float
  18250. var floatValue = parseFloat(value);
  18251. if (value === "true" || value === "false")
  18252. return value === "true";
  18253. else
  18254. return isNaN(floatValue) ? value : floatValue;
  18255. }
  18256. var effectiveTarget = propertyPath.split(".");
  18257. var values = value.split(",");
  18258. for (var i = 0; i < effectiveTarget.length; i++) {
  18259. target = target[effectiveTarget[i]];
  18260. }
  18261. // Return appropriate value with its type
  18262. if (typeof (target) === "boolean")
  18263. return values[0] === "true";
  18264. if (typeof (target) === "string")
  18265. return values[0];
  18266. // Parameters with multiple values such as Vector3 etc.
  18267. var split = new Array();
  18268. for (var i = 0; i < values.length; i++)
  18269. split.push(parseFloat(values[i]));
  18270. if (target instanceof BABYLON.Vector3)
  18271. return BABYLON.Vector3.FromArray(split);
  18272. if (target instanceof BABYLON.Vector4)
  18273. return BABYLON.Vector4.FromArray(split);
  18274. if (target instanceof BABYLON.Color3)
  18275. return BABYLON.Color3.FromArray(split);
  18276. if (target instanceof BABYLON.Color4)
  18277. return BABYLON.Color4.FromArray(split);
  18278. return parseFloat(values[0]);
  18279. };
  18280. // traverse graph per trigger
  18281. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  18282. if (combineArray === void 0) { combineArray = null; }
  18283. if (parsedAction.detached)
  18284. return;
  18285. var parameters = new Array();
  18286. var target = null;
  18287. var propertyPath = null;
  18288. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  18289. // Parameters
  18290. if (parsedAction.type === 2)
  18291. parameters.push(actionManager);
  18292. else
  18293. parameters.push(trigger);
  18294. if (combine) {
  18295. var actions = new Array();
  18296. for (var j = 0; j < parsedAction.combine.length; j++) {
  18297. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  18298. }
  18299. parameters.push(actions);
  18300. }
  18301. else {
  18302. for (var i = 0; i < parsedAction.properties.length; i++) {
  18303. var value = parsedAction.properties[i].value;
  18304. var name = parsedAction.properties[i].name;
  18305. var targetType = parsedAction.properties[i].targetType;
  18306. if (name === "target")
  18307. if (targetType !== null && targetType === "SceneProperties")
  18308. value = target = scene;
  18309. else
  18310. value = target = scene.getNodeByName(value);
  18311. else if (name === "parent")
  18312. value = scene.getNodeByName(value);
  18313. else if (name === "sound")
  18314. value = scene.getSoundByName(value);
  18315. else if (name !== "propertyPath") {
  18316. if (parsedAction.type === 2 && name === "operator")
  18317. value = BABYLON.ValueCondition[value];
  18318. else
  18319. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  18320. }
  18321. else {
  18322. propertyPath = value;
  18323. }
  18324. parameters.push(value);
  18325. }
  18326. }
  18327. if (combineArray === null) {
  18328. parameters.push(condition);
  18329. }
  18330. else {
  18331. parameters.push(null);
  18332. }
  18333. // If interpolate value action
  18334. if (parsedAction.name === "InterpolateValueAction") {
  18335. var param = parameters[parameters.length - 2];
  18336. parameters[parameters.length - 1] = param;
  18337. parameters[parameters.length - 2] = condition;
  18338. }
  18339. // Action or condition(s) and not CombineAction
  18340. var newAction = instanciate(parsedAction.name, parameters);
  18341. if (combineArray === null) {
  18342. if (newAction instanceof BABYLON.Condition) {
  18343. condition = newAction;
  18344. newAction = action;
  18345. }
  18346. else {
  18347. condition = null;
  18348. if (action)
  18349. action.then(newAction);
  18350. else
  18351. actionManager.registerAction(newAction);
  18352. }
  18353. }
  18354. else {
  18355. combineArray.push(newAction);
  18356. }
  18357. for (var i = 0; i < parsedAction.children.length; i++)
  18358. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  18359. };
  18360. for (var i = 0; i < parsedActions.children.length; i++) {
  18361. var triggerParams;
  18362. var trigger = parsedActions.children[i];
  18363. if (trigger.properties.length > 0) {
  18364. var param = trigger.properties[0].value;
  18365. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  18366. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  18367. }
  18368. else
  18369. triggerParams = BABYLON.ActionManager[trigger.name];
  18370. for (var j = 0; j < trigger.children.length; j++) {
  18371. if (!trigger.detached)
  18372. traverse(trigger.children[j], triggerParams, null, null);
  18373. }
  18374. }
  18375. };
  18376. var parseSound = function (parsedSound, scene, rootUrl) {
  18377. var soundName = parsedSound.name;
  18378. var soundUrl = rootUrl + soundName;
  18379. var options = {
  18380. autoplay: parsedSound.autoplay,
  18381. loop: parsedSound.loop,
  18382. volume: parsedSound.volume,
  18383. spatialSound: parsedSound.spatialSound,
  18384. maxDistance: parsedSound.maxDistance,
  18385. rolloffFactor: parsedSound.rolloffFactor,
  18386. refDistance: parsedSound.refDistance,
  18387. distanceModel: parsedSound.distanceModel,
  18388. playbackRate: parsedSound.playbackRate
  18389. };
  18390. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  18391. scene._removePendingData(newSound);
  18392. }, options);
  18393. scene._addPendingData(newSound);
  18394. if (parsedSound.position) {
  18395. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  18396. newSound.setPosition(soundPosition);
  18397. }
  18398. if (parsedSound.isDirectional) {
  18399. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  18400. if (parsedSound.localDirectionToMesh) {
  18401. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  18402. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  18403. }
  18404. }
  18405. if (parsedSound.connectedMeshId) {
  18406. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  18407. if (connectedMesh) {
  18408. newSound.attachToMesh(connectedMesh);
  18409. }
  18410. }
  18411. };
  18412. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18413. names = (names instanceof Array) ? names : [names];
  18414. for (var i in names) {
  18415. if (mesh.name === names[i]) {
  18416. hierarchyIds.push(mesh.id);
  18417. return true;
  18418. }
  18419. }
  18420. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18421. hierarchyIds.push(mesh.id);
  18422. return true;
  18423. }
  18424. return false;
  18425. };
  18426. var importVertexData = function (parsedVertexData, geometry) {
  18427. var vertexData = new BABYLON.VertexData();
  18428. // positions
  18429. var positions = parsedVertexData.positions;
  18430. if (positions) {
  18431. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18432. }
  18433. // normals
  18434. var normals = parsedVertexData.normals;
  18435. if (normals) {
  18436. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18437. }
  18438. // uvs
  18439. var uvs = parsedVertexData.uvs;
  18440. if (uvs) {
  18441. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18442. }
  18443. // uv2s
  18444. var uv2s = parsedVertexData.uv2s;
  18445. if (uv2s) {
  18446. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18447. }
  18448. // colors
  18449. var colors = parsedVertexData.colors;
  18450. if (colors) {
  18451. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18452. }
  18453. // matricesIndices
  18454. var matricesIndices = parsedVertexData.matricesIndices;
  18455. if (matricesIndices) {
  18456. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  18457. }
  18458. // matricesWeights
  18459. var matricesWeights = parsedVertexData.matricesWeights;
  18460. if (matricesWeights) {
  18461. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  18462. }
  18463. // indices
  18464. var indices = parsedVertexData.indices;
  18465. if (indices) {
  18466. vertexData.indices = indices;
  18467. }
  18468. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  18469. };
  18470. var importGeometry = function (parsedGeometry, mesh) {
  18471. var scene = mesh.getScene();
  18472. // Geometry
  18473. var geometryId = parsedGeometry.geometryId;
  18474. if (geometryId) {
  18475. var geometry = scene.getGeometryByID(geometryId);
  18476. if (geometry) {
  18477. geometry.applyToMesh(mesh);
  18478. }
  18479. }
  18480. else if (parsedGeometry instanceof ArrayBuffer) {
  18481. var binaryInfo = mesh._binaryInfo;
  18482. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  18483. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  18484. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  18485. }
  18486. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18487. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18488. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18489. }
  18490. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18491. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18492. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18493. }
  18494. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18495. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18496. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18497. }
  18498. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18499. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18500. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18501. }
  18502. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18503. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18504. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18505. }
  18506. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18507. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18508. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18509. }
  18510. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18511. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18512. mesh.setIndices(indicesData);
  18513. }
  18514. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18515. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18516. mesh.subMeshes = [];
  18517. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18518. var materialIndex = subMeshesData[(i * 5) + 0];
  18519. var verticesStart = subMeshesData[(i * 5) + 1];
  18520. var verticesCount = subMeshesData[(i * 5) + 2];
  18521. var indexStart = subMeshesData[(i * 5) + 3];
  18522. var indexCount = subMeshesData[(i * 5) + 4];
  18523. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18524. }
  18525. }
  18526. }
  18527. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18528. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18529. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18530. if (parsedGeometry.uvs) {
  18531. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  18532. }
  18533. if (parsedGeometry.uvs2) {
  18534. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  18535. }
  18536. if (parsedGeometry.colors) {
  18537. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  18538. }
  18539. if (parsedGeometry.matricesIndices) {
  18540. if (!parsedGeometry.matricesIndices._isExpanded) {
  18541. var floatIndices = [];
  18542. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  18543. var matricesIndex = parsedGeometry.matricesIndices[i];
  18544. floatIndices.push(matricesIndex & 0x000000FF);
  18545. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  18546. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  18547. floatIndices.push(matricesIndex >> 24);
  18548. }
  18549. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  18550. }
  18551. else {
  18552. delete parsedGeometry.matricesIndices._isExpanded;
  18553. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  18554. }
  18555. }
  18556. if (parsedGeometry.matricesWeights) {
  18557. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  18558. }
  18559. mesh.setIndices(parsedGeometry.indices);
  18560. // SubMeshes
  18561. if (parsedGeometry.subMeshes) {
  18562. mesh.subMeshes = [];
  18563. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  18564. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  18565. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  18566. }
  18567. }
  18568. }
  18569. // Flat shading
  18570. if (mesh._shouldGenerateFlatShading) {
  18571. mesh.convertToFlatShadedMesh();
  18572. delete mesh._shouldGenerateFlatShading;
  18573. }
  18574. // Update
  18575. mesh.computeWorldMatrix(true);
  18576. // Octree
  18577. if (scene._selectionOctree) {
  18578. scene._selectionOctree.addMesh(mesh);
  18579. }
  18580. };
  18581. BABYLON.SceneLoader.RegisterPlugin({
  18582. extensions: ".babylon",
  18583. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  18584. var parsedData = JSON.parse(data);
  18585. var loadedSkeletonsIds = [];
  18586. var loadedMaterialsIds = [];
  18587. var hierarchyIds = [];
  18588. for (var index = 0; index < parsedData.meshes.length; index++) {
  18589. var parsedMesh = parsedData.meshes[index];
  18590. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  18591. if (meshesNames instanceof Array) {
  18592. // Remove found mesh name from list.
  18593. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  18594. }
  18595. // Material ?
  18596. if (parsedMesh.materialId) {
  18597. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  18598. if (!materialFound) {
  18599. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  18600. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  18601. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  18602. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18603. var subMatId = parsedMultiMaterial.materials[matIndex];
  18604. loadedMaterialsIds.push(subMatId);
  18605. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  18606. }
  18607. loadedMaterialsIds.push(parsedMultiMaterial.id);
  18608. parseMultiMaterial(parsedMultiMaterial, scene);
  18609. materialFound = true;
  18610. break;
  18611. }
  18612. }
  18613. }
  18614. if (!materialFound) {
  18615. loadedMaterialsIds.push(parsedMesh.materialId);
  18616. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  18617. }
  18618. }
  18619. // Skeleton ?
  18620. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  18621. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  18622. if (!skeletonAlreadyLoaded) {
  18623. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  18624. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  18625. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  18626. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  18627. loadedSkeletonsIds.push(parsedSkeleton.id);
  18628. }
  18629. }
  18630. }
  18631. }
  18632. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  18633. meshes.push(mesh);
  18634. }
  18635. }
  18636. for (index = 0; index < scene.meshes.length; index++) {
  18637. var currentMesh = scene.meshes[index];
  18638. if (currentMesh._waitingParentId) {
  18639. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  18640. currentMesh._waitingParentId = undefined;
  18641. }
  18642. }
  18643. // Particles
  18644. if (parsedData.particleSystems) {
  18645. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18646. var parsedParticleSystem = parsedData.particleSystems[index];
  18647. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  18648. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  18649. }
  18650. }
  18651. }
  18652. return true;
  18653. },
  18654. load: function (scene, data, rootUrl) {
  18655. var parsedData = JSON.parse(data);
  18656. // Scene
  18657. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  18658. scene.autoClear = parsedData.autoClear;
  18659. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  18660. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  18661. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  18662. // Fog
  18663. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  18664. scene.fogMode = parsedData.fogMode;
  18665. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  18666. scene.fogStart = parsedData.fogStart;
  18667. scene.fogEnd = parsedData.fogEnd;
  18668. scene.fogDensity = parsedData.fogDensity;
  18669. }
  18670. for (var index = 0; index < parsedData.lights.length; index++) {
  18671. var parsedLight = parsedData.lights[index];
  18672. parseLight(parsedLight, scene);
  18673. }
  18674. // Materials
  18675. if (parsedData.materials) {
  18676. for (index = 0; index < parsedData.materials.length; index++) {
  18677. var parsedMaterial = parsedData.materials[index];
  18678. parseMaterial(parsedMaterial, scene, rootUrl);
  18679. }
  18680. }
  18681. if (parsedData.multiMaterials) {
  18682. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  18683. var parsedMultiMaterial = parsedData.multiMaterials[index];
  18684. parseMultiMaterial(parsedMultiMaterial, scene);
  18685. }
  18686. }
  18687. // Skeletons
  18688. if (parsedData.skeletons) {
  18689. for (index = 0; index < parsedData.skeletons.length; index++) {
  18690. var parsedSkeleton = parsedData.skeletons[index];
  18691. parseSkeleton(parsedSkeleton, scene);
  18692. }
  18693. }
  18694. // Geometries
  18695. var geometries = parsedData.geometries;
  18696. if (geometries) {
  18697. // Boxes
  18698. var boxes = geometries.boxes;
  18699. if (boxes) {
  18700. for (index = 0; index < boxes.length; index++) {
  18701. var parsedBox = boxes[index];
  18702. parseBox(parsedBox, scene);
  18703. }
  18704. }
  18705. // Spheres
  18706. var spheres = geometries.spheres;
  18707. if (spheres) {
  18708. for (index = 0; index < spheres.length; index++) {
  18709. var parsedSphere = spheres[index];
  18710. parseSphere(parsedSphere, scene);
  18711. }
  18712. }
  18713. // Cylinders
  18714. var cylinders = geometries.cylinders;
  18715. if (cylinders) {
  18716. for (index = 0; index < cylinders.length; index++) {
  18717. var parsedCylinder = cylinders[index];
  18718. parseCylinder(parsedCylinder, scene);
  18719. }
  18720. }
  18721. // Toruses
  18722. var toruses = geometries.toruses;
  18723. if (toruses) {
  18724. for (index = 0; index < toruses.length; index++) {
  18725. var parsedTorus = toruses[index];
  18726. parseTorus(parsedTorus, scene);
  18727. }
  18728. }
  18729. // Grounds
  18730. var grounds = geometries.grounds;
  18731. if (grounds) {
  18732. for (index = 0; index < grounds.length; index++) {
  18733. var parsedGround = grounds[index];
  18734. parseGround(parsedGround, scene);
  18735. }
  18736. }
  18737. // Planes
  18738. var planes = geometries.planes;
  18739. if (planes) {
  18740. for (index = 0; index < planes.length; index++) {
  18741. var parsedPlane = planes[index];
  18742. parsePlane(parsedPlane, scene);
  18743. }
  18744. }
  18745. // TorusKnots
  18746. var torusKnots = geometries.torusKnots;
  18747. if (torusKnots) {
  18748. for (index = 0; index < torusKnots.length; index++) {
  18749. var parsedTorusKnot = torusKnots[index];
  18750. parseTorusKnot(parsedTorusKnot, scene);
  18751. }
  18752. }
  18753. // VertexData
  18754. var vertexData = geometries.vertexData;
  18755. if (vertexData) {
  18756. for (index = 0; index < vertexData.length; index++) {
  18757. var parsedVertexData = vertexData[index];
  18758. parseVertexData(parsedVertexData, scene, rootUrl);
  18759. }
  18760. }
  18761. }
  18762. for (index = 0; index < parsedData.meshes.length; index++) {
  18763. var parsedMesh = parsedData.meshes[index];
  18764. parseMesh(parsedMesh, scene, rootUrl);
  18765. }
  18766. for (index = 0; index < parsedData.cameras.length; index++) {
  18767. var parsedCamera = parsedData.cameras[index];
  18768. parseCamera(parsedCamera, scene);
  18769. }
  18770. if (parsedData.activeCameraID) {
  18771. scene.setActiveCameraByID(parsedData.activeCameraID);
  18772. }
  18773. for (index = 0; index < scene.cameras.length; index++) {
  18774. var camera = scene.cameras[index];
  18775. if (camera._waitingParentId) {
  18776. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  18777. camera._waitingParentId = undefined;
  18778. }
  18779. }
  18780. for (index = 0; index < scene.lights.length; index++) {
  18781. var light = scene.lights[index];
  18782. if (light._waitingParentId) {
  18783. light.parent = scene.getLastEntryByID(light._waitingParentId);
  18784. light._waitingParentId = undefined;
  18785. }
  18786. }
  18787. // Sounds
  18788. if (parsedData.sounds) {
  18789. for (index = 0; index < parsedData.sounds.length; index++) {
  18790. var parsedSound = parsedData.sounds[index];
  18791. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  18792. parseSound(parsedSound, scene, rootUrl);
  18793. }
  18794. else {
  18795. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  18796. }
  18797. }
  18798. }
  18799. for (index = 0; index < scene.meshes.length; index++) {
  18800. var mesh = scene.meshes[index];
  18801. if (mesh._waitingParentId) {
  18802. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  18803. mesh._waitingParentId = undefined;
  18804. }
  18805. if (mesh._waitingActions) {
  18806. parseActions(mesh._waitingActions, mesh, scene);
  18807. mesh._waitingActions = undefined;
  18808. }
  18809. }
  18810. // Particles Systems
  18811. if (parsedData.particleSystems) {
  18812. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18813. var parsedParticleSystem = parsedData.particleSystems[index];
  18814. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  18815. }
  18816. }
  18817. // Lens flares
  18818. if (parsedData.lensFlareSystems) {
  18819. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  18820. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  18821. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  18822. }
  18823. }
  18824. // Shadows
  18825. if (parsedData.shadowGenerators) {
  18826. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  18827. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  18828. parseShadowGenerator(parsedShadowGenerator, scene);
  18829. }
  18830. }
  18831. // Actions (scene)
  18832. if (parsedData.actions) {
  18833. parseActions(parsedData.actions, null, scene);
  18834. }
  18835. // Finish
  18836. return true;
  18837. }
  18838. });
  18839. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  18840. })(BABYLON || (BABYLON = {}));
  18841. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  18842. var BABYLON;
  18843. (function (BABYLON) {
  18844. var SpriteManager = (function () {
  18845. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  18846. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18847. this.name = name;
  18848. this.cellSize = cellSize;
  18849. this.sprites = new Array();
  18850. this.renderingGroupId = 0;
  18851. this.fogEnabled = true;
  18852. this._vertexDeclaration = [4, 4, 4, 4];
  18853. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  18854. this._capacity = capacity;
  18855. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  18856. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18857. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18858. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  18859. this._scene = scene;
  18860. this._scene.spriteManagers.push(this);
  18861. // VBO
  18862. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  18863. var indices = [];
  18864. var index = 0;
  18865. for (var count = 0; count < capacity; count++) {
  18866. indices.push(index);
  18867. indices.push(index + 1);
  18868. indices.push(index + 2);
  18869. indices.push(index);
  18870. indices.push(index + 2);
  18871. indices.push(index + 3);
  18872. index += 4;
  18873. }
  18874. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18875. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  18876. // Effects
  18877. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  18878. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  18879. }
  18880. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  18881. var arrayOffset = index * 16;
  18882. if (offsetX === 0)
  18883. offsetX = this._epsilon;
  18884. else if (offsetX === 1)
  18885. offsetX = 1 - this._epsilon;
  18886. if (offsetY === 0)
  18887. offsetY = this._epsilon;
  18888. else if (offsetY === 1)
  18889. offsetY = 1 - this._epsilon;
  18890. this._vertices[arrayOffset] = sprite.position.x;
  18891. this._vertices[arrayOffset + 1] = sprite.position.y;
  18892. this._vertices[arrayOffset + 2] = sprite.position.z;
  18893. this._vertices[arrayOffset + 3] = sprite.angle;
  18894. this._vertices[arrayOffset + 4] = sprite.width;
  18895. this._vertices[arrayOffset + 5] = sprite.height;
  18896. this._vertices[arrayOffset + 6] = offsetX;
  18897. this._vertices[arrayOffset + 7] = offsetY;
  18898. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  18899. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  18900. var offset = (sprite.cellIndex / rowSize) >> 0;
  18901. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  18902. this._vertices[arrayOffset + 11] = offset;
  18903. // Color
  18904. this._vertices[arrayOffset + 12] = sprite.color.r;
  18905. this._vertices[arrayOffset + 13] = sprite.color.g;
  18906. this._vertices[arrayOffset + 14] = sprite.color.b;
  18907. this._vertices[arrayOffset + 15] = sprite.color.a;
  18908. };
  18909. SpriteManager.prototype.render = function () {
  18910. // Check
  18911. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  18912. return;
  18913. var engine = this._scene.getEngine();
  18914. var baseSize = this._spriteTexture.getBaseSize();
  18915. // Sprites
  18916. var deltaTime = engine.getDeltaTime();
  18917. var max = Math.min(this._capacity, this.sprites.length);
  18918. var rowSize = baseSize.width / this.cellSize;
  18919. var offset = 0;
  18920. for (var index = 0; index < max; index++) {
  18921. var sprite = this.sprites[index];
  18922. if (!sprite) {
  18923. continue;
  18924. }
  18925. sprite._animate(deltaTime);
  18926. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  18927. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  18928. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  18929. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  18930. }
  18931. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  18932. // Render
  18933. var effect = this._effectBase;
  18934. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18935. effect = this._effectFog;
  18936. }
  18937. engine.enableEffect(effect);
  18938. var viewMatrix = this._scene.getViewMatrix();
  18939. effect.setTexture("diffuseSampler", this._spriteTexture);
  18940. effect.setMatrix("view", viewMatrix);
  18941. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  18942. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  18943. // Fog
  18944. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18945. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  18946. effect.setColor3("vFogColor", this._scene.fogColor);
  18947. }
  18948. // VBOs
  18949. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  18950. // Draw order
  18951. engine.setDepthFunctionToLessOrEqual();
  18952. effect.setBool("alphaTest", true);
  18953. engine.setColorWrite(false);
  18954. engine.draw(true, 0, max * 6);
  18955. engine.setColorWrite(true);
  18956. effect.setBool("alphaTest", false);
  18957. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  18958. engine.draw(true, 0, max * 6);
  18959. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18960. };
  18961. SpriteManager.prototype.dispose = function () {
  18962. if (this._vertexBuffer) {
  18963. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  18964. this._vertexBuffer = null;
  18965. }
  18966. if (this._indexBuffer) {
  18967. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  18968. this._indexBuffer = null;
  18969. }
  18970. if (this._spriteTexture) {
  18971. this._spriteTexture.dispose();
  18972. this._spriteTexture = null;
  18973. }
  18974. // Remove from scene
  18975. var index = this._scene.spriteManagers.indexOf(this);
  18976. this._scene.spriteManagers.splice(index, 1);
  18977. // Callback
  18978. if (this.onDispose) {
  18979. this.onDispose();
  18980. }
  18981. };
  18982. return SpriteManager;
  18983. })();
  18984. BABYLON.SpriteManager = SpriteManager;
  18985. })(BABYLON || (BABYLON = {}));
  18986. //# sourceMappingURL=babylon.spriteManager.js.map
  18987. var BABYLON;
  18988. (function (BABYLON) {
  18989. var Sprite = (function () {
  18990. function Sprite(name, manager) {
  18991. this.name = name;
  18992. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  18993. this.width = 1.0;
  18994. this.height = 1.0;
  18995. this.angle = 0;
  18996. this.cellIndex = 0;
  18997. this.invertU = 0;
  18998. this.invertV = 0;
  18999. this.animations = new Array();
  19000. this._animationStarted = false;
  19001. this._loopAnimation = false;
  19002. this._fromIndex = 0;
  19003. this._toIndex = 0;
  19004. this._delay = 0;
  19005. this._direction = 1;
  19006. this._frameCount = 0;
  19007. this._time = 0;
  19008. this._manager = manager;
  19009. this._manager.sprites.push(this);
  19010. this.position = BABYLON.Vector3.Zero();
  19011. }
  19012. Object.defineProperty(Sprite.prototype, "size", {
  19013. get: function () {
  19014. return this.width;
  19015. },
  19016. set: function (value) {
  19017. this.width = value;
  19018. this.height = value;
  19019. },
  19020. enumerable: true,
  19021. configurable: true
  19022. });
  19023. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  19024. this._fromIndex = from;
  19025. this._toIndex = to;
  19026. this._loopAnimation = loop;
  19027. this._delay = delay;
  19028. this._animationStarted = true;
  19029. this._direction = from < to ? 1 : -1;
  19030. this.cellIndex = from;
  19031. this._time = 0;
  19032. };
  19033. Sprite.prototype.stopAnimation = function () {
  19034. this._animationStarted = false;
  19035. };
  19036. Sprite.prototype._animate = function (deltaTime) {
  19037. if (!this._animationStarted)
  19038. return;
  19039. this._time += deltaTime;
  19040. if (this._time > this._delay) {
  19041. this._time = this._time % this._delay;
  19042. this.cellIndex += this._direction;
  19043. if (this.cellIndex == this._toIndex) {
  19044. if (this._loopAnimation) {
  19045. this.cellIndex = this._fromIndex;
  19046. }
  19047. else {
  19048. this._animationStarted = false;
  19049. if (this.disposeWhenFinishedAnimating) {
  19050. this.dispose();
  19051. }
  19052. }
  19053. }
  19054. }
  19055. };
  19056. Sprite.prototype.dispose = function () {
  19057. for (var i = 0; i < this._manager.sprites.length; i++) {
  19058. if (this._manager.sprites[i] == this) {
  19059. this._manager.sprites.splice(i, 1);
  19060. }
  19061. }
  19062. };
  19063. return Sprite;
  19064. })();
  19065. BABYLON.Sprite = Sprite;
  19066. })(BABYLON || (BABYLON = {}));
  19067. //# sourceMappingURL=babylon.sprite.js.map
  19068. var BABYLON;
  19069. (function (BABYLON) {
  19070. var Layer = (function () {
  19071. function Layer(name, imgUrl, scene, isBackground, color) {
  19072. this.name = name;
  19073. this._vertexDeclaration = [2];
  19074. this._vertexStrideSize = 2 * 4;
  19075. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  19076. this.isBackground = isBackground === undefined ? true : isBackground;
  19077. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  19078. this._scene = scene;
  19079. this._scene.layers.push(this);
  19080. // VBO
  19081. var vertices = [];
  19082. vertices.push(1, 1);
  19083. vertices.push(-1, 1);
  19084. vertices.push(-1, -1);
  19085. vertices.push(1, -1);
  19086. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  19087. // Indices
  19088. var indices = [];
  19089. indices.push(0);
  19090. indices.push(1);
  19091. indices.push(2);
  19092. indices.push(0);
  19093. indices.push(2);
  19094. indices.push(3);
  19095. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  19096. // Effects
  19097. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  19098. }
  19099. Layer.prototype.render = function () {
  19100. // Check
  19101. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  19102. return;
  19103. var engine = this._scene.getEngine();
  19104. // Render
  19105. engine.enableEffect(this._effect);
  19106. engine.setState(false);
  19107. // Texture
  19108. this._effect.setTexture("textureSampler", this.texture);
  19109. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  19110. // Color
  19111. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  19112. // VBOs
  19113. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  19114. // Draw order
  19115. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19116. engine.draw(true, 0, 6);
  19117. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19118. };
  19119. Layer.prototype.dispose = function () {
  19120. if (this._vertexBuffer) {
  19121. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  19122. this._vertexBuffer = null;
  19123. }
  19124. if (this._indexBuffer) {
  19125. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  19126. this._indexBuffer = null;
  19127. }
  19128. if (this.texture) {
  19129. this.texture.dispose();
  19130. this.texture = null;
  19131. }
  19132. // Remove from scene
  19133. var index = this._scene.layers.indexOf(this);
  19134. this._scene.layers.splice(index, 1);
  19135. // Callback
  19136. if (this.onDispose) {
  19137. this.onDispose();
  19138. }
  19139. };
  19140. return Layer;
  19141. })();
  19142. BABYLON.Layer = Layer;
  19143. })(BABYLON || (BABYLON = {}));
  19144. //# sourceMappingURL=babylon.layer.js.map
  19145. var BABYLON;
  19146. (function (BABYLON) {
  19147. var Particle = (function () {
  19148. function Particle() {
  19149. this.position = BABYLON.Vector3.Zero();
  19150. this.direction = BABYLON.Vector3.Zero();
  19151. this.color = new BABYLON.Color4(0, 0, 0, 0);
  19152. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  19153. this.lifeTime = 1.0;
  19154. this.age = 0;
  19155. this.size = 0;
  19156. this.angle = 0;
  19157. this.angularSpeed = 0;
  19158. }
  19159. Particle.prototype.copyTo = function (other) {
  19160. other.position.copyFrom(this.position);
  19161. other.direction.copyFrom(this.direction);
  19162. other.color.copyFrom(this.color);
  19163. other.colorStep.copyFrom(this.colorStep);
  19164. other.lifeTime = this.lifeTime;
  19165. other.age = this.age;
  19166. other.size = this.size;
  19167. other.angle = this.angle;
  19168. other.angularSpeed = this.angularSpeed;
  19169. };
  19170. return Particle;
  19171. })();
  19172. BABYLON.Particle = Particle;
  19173. })(BABYLON || (BABYLON = {}));
  19174. //# sourceMappingURL=babylon.particle.js.map
  19175. var BABYLON;
  19176. (function (BABYLON) {
  19177. var randomNumber = function (min, max) {
  19178. if (min === max) {
  19179. return (min);
  19180. }
  19181. var random = Math.random();
  19182. return ((random * (max - min)) + min);
  19183. };
  19184. var ParticleSystem = (function () {
  19185. function ParticleSystem(name, capacity, scene, customEffect) {
  19186. var _this = this;
  19187. this.name = name;
  19188. this.renderingGroupId = 0;
  19189. this.emitter = null;
  19190. this.emitRate = 10;
  19191. this.manualEmitCount = -1;
  19192. this.updateSpeed = 0.01;
  19193. this.targetStopDuration = 0;
  19194. this.disposeOnStop = false;
  19195. this.minEmitPower = 1;
  19196. this.maxEmitPower = 1;
  19197. this.minLifeTime = 1;
  19198. this.maxLifeTime = 1;
  19199. this.minSize = 1;
  19200. this.maxSize = 1;
  19201. this.minAngularSpeed = 0;
  19202. this.maxAngularSpeed = 0;
  19203. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  19204. this.forceDepthWrite = false;
  19205. this.gravity = BABYLON.Vector3.Zero();
  19206. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  19207. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  19208. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  19209. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  19210. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19211. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19212. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  19213. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19214. this.particles = new Array();
  19215. this._vertexDeclaration = [3, 4, 4];
  19216. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  19217. this._stockParticles = new Array();
  19218. this._newPartsExcess = 0;
  19219. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  19220. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  19221. this._scaledDirection = BABYLON.Vector3.Zero();
  19222. this._scaledGravity = BABYLON.Vector3.Zero();
  19223. this._currentRenderId = -1;
  19224. this._started = false;
  19225. this._stopped = false;
  19226. this._actualFrame = 0;
  19227. this.id = name;
  19228. this._capacity = capacity;
  19229. this._scene = scene;
  19230. this._customEffect = customEffect;
  19231. scene.particleSystems.push(this);
  19232. // VBO
  19233. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  19234. var indices = [];
  19235. var index = 0;
  19236. for (var count = 0; count < capacity; count++) {
  19237. indices.push(index);
  19238. indices.push(index + 1);
  19239. indices.push(index + 2);
  19240. indices.push(index);
  19241. indices.push(index + 2);
  19242. indices.push(index + 3);
  19243. index += 4;
  19244. }
  19245. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  19246. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  19247. // Default behaviors
  19248. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  19249. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  19250. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  19251. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  19252. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  19253. };
  19254. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  19255. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  19256. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  19257. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  19258. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  19259. };
  19260. this.updateFunction = function (particles) {
  19261. for (var index = 0; index < particles.length; index++) {
  19262. var particle = particles[index];
  19263. particle.age += _this._scaledUpdateSpeed;
  19264. if (particle.age >= particle.lifeTime) {
  19265. _this.recycleParticle(particle);
  19266. index--;
  19267. continue;
  19268. }
  19269. else {
  19270. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  19271. particle.color.addInPlace(_this._scaledColorStep);
  19272. if (particle.color.a < 0)
  19273. particle.color.a = 0;
  19274. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  19275. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  19276. particle.position.addInPlace(_this._scaledDirection);
  19277. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  19278. particle.direction.addInPlace(_this._scaledGravity);
  19279. }
  19280. }
  19281. };
  19282. }
  19283. ParticleSystem.prototype.recycleParticle = function (particle) {
  19284. var lastParticle = this.particles.pop();
  19285. if (lastParticle !== particle) {
  19286. lastParticle.copyTo(particle);
  19287. this._stockParticles.push(lastParticle);
  19288. }
  19289. };
  19290. ParticleSystem.prototype.getCapacity = function () {
  19291. return this._capacity;
  19292. };
  19293. ParticleSystem.prototype.isAlive = function () {
  19294. return this._alive;
  19295. };
  19296. ParticleSystem.prototype.isStarted = function () {
  19297. return this._started;
  19298. };
  19299. ParticleSystem.prototype.start = function () {
  19300. this._started = true;
  19301. this._stopped = false;
  19302. this._actualFrame = 0;
  19303. };
  19304. ParticleSystem.prototype.stop = function () {
  19305. this._stopped = true;
  19306. };
  19307. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  19308. var offset = index * 11;
  19309. this._vertices[offset] = particle.position.x;
  19310. this._vertices[offset + 1] = particle.position.y;
  19311. this._vertices[offset + 2] = particle.position.z;
  19312. this._vertices[offset + 3] = particle.color.r;
  19313. this._vertices[offset + 4] = particle.color.g;
  19314. this._vertices[offset + 5] = particle.color.b;
  19315. this._vertices[offset + 6] = particle.color.a;
  19316. this._vertices[offset + 7] = particle.angle;
  19317. this._vertices[offset + 8] = particle.size;
  19318. this._vertices[offset + 9] = offsetX;
  19319. this._vertices[offset + 10] = offsetY;
  19320. };
  19321. ParticleSystem.prototype._update = function (newParticles) {
  19322. // Update current
  19323. this._alive = this.particles.length > 0;
  19324. this.updateFunction(this.particles);
  19325. // Add new ones
  19326. var worldMatrix;
  19327. if (this.emitter.position) {
  19328. worldMatrix = this.emitter.getWorldMatrix();
  19329. }
  19330. else {
  19331. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  19332. }
  19333. for (var index = 0; index < newParticles; index++) {
  19334. if (this.particles.length === this._capacity) {
  19335. break;
  19336. }
  19337. if (this._stockParticles.length !== 0) {
  19338. var particle = this._stockParticles.pop();
  19339. particle.age = 0;
  19340. }
  19341. else {
  19342. particle = new BABYLON.Particle();
  19343. }
  19344. this.particles.push(particle);
  19345. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  19346. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  19347. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  19348. particle.size = randomNumber(this.minSize, this.maxSize);
  19349. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  19350. this.startPositionFunction(worldMatrix, particle.position);
  19351. var step = randomNumber(0, 1.0);
  19352. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  19353. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  19354. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  19355. }
  19356. };
  19357. ParticleSystem.prototype._getEffect = function () {
  19358. if (this._customEffect) {
  19359. return this._customEffect;
  19360. }
  19361. ;
  19362. var defines = [];
  19363. if (this._scene.clipPlane) {
  19364. defines.push("#define CLIPPLANE");
  19365. }
  19366. // Effect
  19367. var join = defines.join("\n");
  19368. if (this._cachedDefines !== join) {
  19369. this._cachedDefines = join;
  19370. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  19371. }
  19372. return this._effect;
  19373. };
  19374. ParticleSystem.prototype.animate = function () {
  19375. if (!this._started)
  19376. return;
  19377. var effect = this._getEffect();
  19378. // Check
  19379. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  19380. return;
  19381. if (this._currentRenderId === this._scene.getRenderId()) {
  19382. return;
  19383. }
  19384. this._currentRenderId = this._scene.getRenderId();
  19385. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  19386. // determine the number of particles we need to create
  19387. var emitCout;
  19388. if (this.manualEmitCount > -1) {
  19389. emitCout = this.manualEmitCount;
  19390. this.manualEmitCount = 0;
  19391. }
  19392. else {
  19393. emitCout = this.emitRate;
  19394. }
  19395. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  19396. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  19397. if (this._newPartsExcess > 1.0) {
  19398. newParticles += this._newPartsExcess >> 0;
  19399. this._newPartsExcess -= this._newPartsExcess >> 0;
  19400. }
  19401. this._alive = false;
  19402. if (!this._stopped) {
  19403. this._actualFrame += this._scaledUpdateSpeed;
  19404. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  19405. this.stop();
  19406. }
  19407. else {
  19408. newParticles = 0;
  19409. }
  19410. this._update(newParticles);
  19411. // Stopped?
  19412. if (this._stopped) {
  19413. if (!this._alive) {
  19414. this._started = false;
  19415. if (this.disposeOnStop) {
  19416. this._scene._toBeDisposed.push(this);
  19417. }
  19418. }
  19419. }
  19420. // Update VBO
  19421. var offset = 0;
  19422. for (var index = 0; index < this.particles.length; index++) {
  19423. var particle = this.particles[index];
  19424. this._appendParticleVertex(offset++, particle, 0, 0);
  19425. this._appendParticleVertex(offset++, particle, 1, 0);
  19426. this._appendParticleVertex(offset++, particle, 1, 1);
  19427. this._appendParticleVertex(offset++, particle, 0, 1);
  19428. }
  19429. var engine = this._scene.getEngine();
  19430. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  19431. };
  19432. ParticleSystem.prototype.render = function () {
  19433. var effect = this._getEffect();
  19434. // Check
  19435. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  19436. return 0;
  19437. var engine = this._scene.getEngine();
  19438. // Render
  19439. engine.enableEffect(effect);
  19440. engine.setState(false);
  19441. var viewMatrix = this._scene.getViewMatrix();
  19442. effect.setTexture("diffuseSampler", this.particleTexture);
  19443. effect.setMatrix("view", viewMatrix);
  19444. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  19445. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  19446. if (this._scene.clipPlane) {
  19447. var clipPlane = this._scene.clipPlane;
  19448. var invView = viewMatrix.clone();
  19449. invView.invert();
  19450. effect.setMatrix("invView", invView);
  19451. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19452. }
  19453. // VBOs
  19454. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  19455. // Draw order
  19456. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  19457. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  19458. }
  19459. else {
  19460. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19461. }
  19462. if (this.forceDepthWrite) {
  19463. engine.setDepthWrite(true);
  19464. }
  19465. engine.draw(true, 0, this.particles.length * 6);
  19466. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19467. return this.particles.length;
  19468. };
  19469. ParticleSystem.prototype.dispose = function () {
  19470. if (this._vertexBuffer) {
  19471. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  19472. this._vertexBuffer = null;
  19473. }
  19474. if (this._indexBuffer) {
  19475. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  19476. this._indexBuffer = null;
  19477. }
  19478. if (this.particleTexture) {
  19479. this.particleTexture.dispose();
  19480. this.particleTexture = null;
  19481. }
  19482. // Remove from scene
  19483. var index = this._scene.particleSystems.indexOf(this);
  19484. this._scene.particleSystems.splice(index, 1);
  19485. // Callback
  19486. if (this.onDispose) {
  19487. this.onDispose();
  19488. }
  19489. };
  19490. // Clone
  19491. ParticleSystem.prototype.clone = function (name, newEmitter) {
  19492. var result = new ParticleSystem(name, this._capacity, this._scene);
  19493. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  19494. if (newEmitter === undefined) {
  19495. newEmitter = this.emitter;
  19496. }
  19497. result.emitter = newEmitter;
  19498. if (this.particleTexture) {
  19499. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  19500. }
  19501. result.start();
  19502. return result;
  19503. };
  19504. // Statics
  19505. ParticleSystem.BLENDMODE_ONEONE = 0;
  19506. ParticleSystem.BLENDMODE_STANDARD = 1;
  19507. return ParticleSystem;
  19508. })();
  19509. BABYLON.ParticleSystem = ParticleSystem;
  19510. })(BABYLON || (BABYLON = {}));
  19511. //# sourceMappingURL=babylon.particleSystem.js.map
  19512. var BABYLON;
  19513. (function (BABYLON) {
  19514. var Animation = (function () {
  19515. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  19516. this.name = name;
  19517. this.targetProperty = targetProperty;
  19518. this.framePerSecond = framePerSecond;
  19519. this.dataType = dataType;
  19520. this.loopMode = loopMode;
  19521. this._offsetsCache = {};
  19522. this._highLimitsCache = {};
  19523. this._stopped = false;
  19524. this.targetPropertyPath = targetProperty.split(".");
  19525. this.dataType = dataType;
  19526. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  19527. }
  19528. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  19529. var dataType = undefined;
  19530. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  19531. dataType = Animation.ANIMATIONTYPE_FLOAT;
  19532. }
  19533. else if (from instanceof BABYLON.Quaternion) {
  19534. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  19535. }
  19536. else if (from instanceof BABYLON.Vector3) {
  19537. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  19538. }
  19539. else if (from instanceof BABYLON.Vector2) {
  19540. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  19541. }
  19542. else if (from instanceof BABYLON.Color3) {
  19543. dataType = Animation.ANIMATIONTYPE_COLOR3;
  19544. }
  19545. if (dataType == undefined) {
  19546. return null;
  19547. }
  19548. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  19549. var keys = [];
  19550. keys.push({ frame: 0, value: from });
  19551. keys.push({ frame: totalFrame, value: to });
  19552. animation.setKeys(keys);
  19553. mesh.animations.push(animation);
  19554. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  19555. };
  19556. // Methods
  19557. Animation.prototype.isStopped = function () {
  19558. return this._stopped;
  19559. };
  19560. Animation.prototype.getKeys = function () {
  19561. return this._keys;
  19562. };
  19563. Animation.prototype.getEasingFunction = function () {
  19564. return this._easingFunction;
  19565. };
  19566. Animation.prototype.setEasingFunction = function (easingFunction) {
  19567. this._easingFunction = easingFunction;
  19568. };
  19569. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  19570. return startValue + (endValue - startValue) * gradient;
  19571. };
  19572. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  19573. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  19574. };
  19575. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  19576. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  19577. };
  19578. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  19579. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  19580. };
  19581. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  19582. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  19583. };
  19584. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  19585. var startScale = new BABYLON.Vector3(0, 0, 0);
  19586. var startRotation = new BABYLON.Quaternion();
  19587. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  19588. startValue.decompose(startScale, startRotation, startTranslation);
  19589. var endScale = new BABYLON.Vector3(0, 0, 0);
  19590. var endRotation = new BABYLON.Quaternion();
  19591. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  19592. endValue.decompose(endScale, endRotation, endTranslation);
  19593. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  19594. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  19595. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  19596. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  19597. return result;
  19598. };
  19599. Animation.prototype.clone = function () {
  19600. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  19601. clone.setKeys(this._keys);
  19602. return clone;
  19603. };
  19604. Animation.prototype.setKeys = function (values) {
  19605. this._keys = values.slice(0);
  19606. this._offsetsCache = {};
  19607. this._highLimitsCache = {};
  19608. };
  19609. Animation.prototype._getKeyValue = function (value) {
  19610. if (typeof value === "function") {
  19611. return value();
  19612. }
  19613. return value;
  19614. };
  19615. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  19616. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  19617. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  19618. }
  19619. this.currentFrame = currentFrame;
  19620. // Try to get a hash to find the right key
  19621. 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));
  19622. if (this._keys[startKey].frame >= currentFrame) {
  19623. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  19624. startKey--;
  19625. }
  19626. }
  19627. for (var key = startKey; key < this._keys.length; key++) {
  19628. if (this._keys[key + 1].frame >= currentFrame) {
  19629. var startValue = this._getKeyValue(this._keys[key].value);
  19630. var endValue = this._getKeyValue(this._keys[key + 1].value);
  19631. // gradient : percent of currentFrame between the frame inf and the frame sup
  19632. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  19633. // check for easingFunction and correction of gradient
  19634. if (this._easingFunction != null) {
  19635. gradient = this._easingFunction.ease(gradient);
  19636. }
  19637. switch (this.dataType) {
  19638. case Animation.ANIMATIONTYPE_FLOAT:
  19639. switch (loopMode) {
  19640. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19641. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19642. return this.floatInterpolateFunction(startValue, endValue, gradient);
  19643. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19644. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  19645. }
  19646. break;
  19647. case Animation.ANIMATIONTYPE_QUATERNION:
  19648. var quaternion = null;
  19649. switch (loopMode) {
  19650. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19651. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19652. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  19653. break;
  19654. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19655. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19656. break;
  19657. }
  19658. return quaternion;
  19659. case Animation.ANIMATIONTYPE_VECTOR3:
  19660. switch (loopMode) {
  19661. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19662. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19663. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  19664. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19665. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19666. }
  19667. case Animation.ANIMATIONTYPE_VECTOR2:
  19668. switch (loopMode) {
  19669. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19670. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19671. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  19672. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19673. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19674. }
  19675. case Animation.ANIMATIONTYPE_COLOR3:
  19676. switch (loopMode) {
  19677. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19678. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19679. return this.color3InterpolateFunction(startValue, endValue, gradient);
  19680. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19681. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  19682. }
  19683. case Animation.ANIMATIONTYPE_MATRIX:
  19684. switch (loopMode) {
  19685. case Animation.ANIMATIONLOOPMODE_CYCLE:
  19686. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  19687. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  19688. return startValue;
  19689. }
  19690. default:
  19691. break;
  19692. }
  19693. break;
  19694. }
  19695. }
  19696. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  19697. };
  19698. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  19699. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  19700. this._stopped = true;
  19701. return false;
  19702. }
  19703. var returnValue = true;
  19704. // Adding a start key at frame 0 if missing
  19705. if (this._keys[0].frame !== 0) {
  19706. var newKey = { frame: 0, value: this._keys[0].value };
  19707. this._keys.splice(0, 0, newKey);
  19708. }
  19709. // Check limits
  19710. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  19711. from = this._keys[0].frame;
  19712. }
  19713. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  19714. to = this._keys[this._keys.length - 1].frame;
  19715. }
  19716. // Compute ratio
  19717. var range = to - from;
  19718. var offsetValue;
  19719. // ratio represents the frame delta between from and to
  19720. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  19721. var highLimitValue = 0;
  19722. if (ratio > range && !loop) {
  19723. returnValue = false;
  19724. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  19725. }
  19726. else {
  19727. // Get max value if required
  19728. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  19729. var keyOffset = to.toString() + from.toString();
  19730. if (!this._offsetsCache[keyOffset]) {
  19731. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  19732. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  19733. switch (this.dataType) {
  19734. case Animation.ANIMATIONTYPE_FLOAT:
  19735. this._offsetsCache[keyOffset] = toValue - fromValue;
  19736. break;
  19737. case Animation.ANIMATIONTYPE_QUATERNION:
  19738. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19739. break;
  19740. case Animation.ANIMATIONTYPE_VECTOR3:
  19741. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19742. case Animation.ANIMATIONTYPE_VECTOR2:
  19743. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19744. case Animation.ANIMATIONTYPE_COLOR3:
  19745. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  19746. default:
  19747. break;
  19748. }
  19749. this._highLimitsCache[keyOffset] = toValue;
  19750. }
  19751. highLimitValue = this._highLimitsCache[keyOffset];
  19752. offsetValue = this._offsetsCache[keyOffset];
  19753. }
  19754. }
  19755. if (offsetValue === undefined) {
  19756. switch (this.dataType) {
  19757. case Animation.ANIMATIONTYPE_FLOAT:
  19758. offsetValue = 0;
  19759. break;
  19760. case Animation.ANIMATIONTYPE_QUATERNION:
  19761. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  19762. break;
  19763. case Animation.ANIMATIONTYPE_VECTOR3:
  19764. offsetValue = BABYLON.Vector3.Zero();
  19765. break;
  19766. case Animation.ANIMATIONTYPE_VECTOR2:
  19767. offsetValue = BABYLON.Vector2.Zero();
  19768. break;
  19769. case Animation.ANIMATIONTYPE_COLOR3:
  19770. offsetValue = BABYLON.Color3.Black();
  19771. }
  19772. }
  19773. // Compute value
  19774. var repeatCount = (ratio / range) >> 0;
  19775. var currentFrame = returnValue ? from + ratio % range : to;
  19776. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  19777. // Set value
  19778. if (this.targetPropertyPath.length > 1) {
  19779. var property = this._target[this.targetPropertyPath[0]];
  19780. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  19781. property = property[this.targetPropertyPath[index]];
  19782. }
  19783. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  19784. }
  19785. else {
  19786. this._target[this.targetPropertyPath[0]] = currentValue;
  19787. }
  19788. if (this._target.markAsDirty) {
  19789. this._target.markAsDirty(this.targetProperty);
  19790. }
  19791. if (!returnValue) {
  19792. this._stopped = true;
  19793. }
  19794. return returnValue;
  19795. };
  19796. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  19797. get: function () {
  19798. return Animation._ANIMATIONTYPE_FLOAT;
  19799. },
  19800. enumerable: true,
  19801. configurable: true
  19802. });
  19803. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  19804. get: function () {
  19805. return Animation._ANIMATIONTYPE_VECTOR3;
  19806. },
  19807. enumerable: true,
  19808. configurable: true
  19809. });
  19810. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  19811. get: function () {
  19812. return Animation._ANIMATIONTYPE_VECTOR2;
  19813. },
  19814. enumerable: true,
  19815. configurable: true
  19816. });
  19817. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  19818. get: function () {
  19819. return Animation._ANIMATIONTYPE_QUATERNION;
  19820. },
  19821. enumerable: true,
  19822. configurable: true
  19823. });
  19824. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  19825. get: function () {
  19826. return Animation._ANIMATIONTYPE_MATRIX;
  19827. },
  19828. enumerable: true,
  19829. configurable: true
  19830. });
  19831. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  19832. get: function () {
  19833. return Animation._ANIMATIONTYPE_COLOR3;
  19834. },
  19835. enumerable: true,
  19836. configurable: true
  19837. });
  19838. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  19839. get: function () {
  19840. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  19841. },
  19842. enumerable: true,
  19843. configurable: true
  19844. });
  19845. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  19846. get: function () {
  19847. return Animation._ANIMATIONLOOPMODE_CYCLE;
  19848. },
  19849. enumerable: true,
  19850. configurable: true
  19851. });
  19852. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  19853. get: function () {
  19854. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  19855. },
  19856. enumerable: true,
  19857. configurable: true
  19858. });
  19859. // Statics
  19860. Animation._ANIMATIONTYPE_FLOAT = 0;
  19861. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  19862. Animation._ANIMATIONTYPE_QUATERNION = 2;
  19863. Animation._ANIMATIONTYPE_MATRIX = 3;
  19864. Animation._ANIMATIONTYPE_COLOR3 = 4;
  19865. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  19866. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  19867. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  19868. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  19869. return Animation;
  19870. })();
  19871. BABYLON.Animation = Animation;
  19872. })(BABYLON || (BABYLON = {}));
  19873. //# sourceMappingURL=babylon.animation.js.map
  19874. var BABYLON;
  19875. (function (BABYLON) {
  19876. var Animatable = (function () {
  19877. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  19878. if (fromFrame === void 0) { fromFrame = 0; }
  19879. if (toFrame === void 0) { toFrame = 100; }
  19880. if (loopAnimation === void 0) { loopAnimation = false; }
  19881. if (speedRatio === void 0) { speedRatio = 1.0; }
  19882. this.target = target;
  19883. this.fromFrame = fromFrame;
  19884. this.toFrame = toFrame;
  19885. this.loopAnimation = loopAnimation;
  19886. this.speedRatio = speedRatio;
  19887. this.onAnimationEnd = onAnimationEnd;
  19888. this._animations = new Array();
  19889. this._paused = false;
  19890. this.animationStarted = false;
  19891. if (animations) {
  19892. this.appendAnimations(target, animations);
  19893. }
  19894. this._scene = scene;
  19895. scene._activeAnimatables.push(this);
  19896. }
  19897. // Methods
  19898. Animatable.prototype.appendAnimations = function (target, animations) {
  19899. for (var index = 0; index < animations.length; index++) {
  19900. var animation = animations[index];
  19901. animation._target = target;
  19902. this._animations.push(animation);
  19903. }
  19904. };
  19905. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  19906. var animations = this._animations;
  19907. for (var index = 0; index < animations.length; index++) {
  19908. if (animations[index].targetProperty === property) {
  19909. return animations[index];
  19910. }
  19911. }
  19912. return null;
  19913. };
  19914. Animatable.prototype.pause = function () {
  19915. if (this._paused) {
  19916. return;
  19917. }
  19918. this._paused = true;
  19919. };
  19920. Animatable.prototype.restart = function () {
  19921. this._paused = false;
  19922. };
  19923. Animatable.prototype.stop = function () {
  19924. var index = this._scene._activeAnimatables.indexOf(this);
  19925. if (index > -1) {
  19926. this._scene._activeAnimatables.splice(index, 1);
  19927. }
  19928. if (this.onAnimationEnd) {
  19929. this.onAnimationEnd();
  19930. }
  19931. };
  19932. Animatable.prototype._animate = function (delay) {
  19933. if (this._paused) {
  19934. if (!this._pausedDelay) {
  19935. this._pausedDelay = delay;
  19936. }
  19937. return true;
  19938. }
  19939. if (!this._localDelayOffset) {
  19940. this._localDelayOffset = delay;
  19941. }
  19942. else if (this._pausedDelay) {
  19943. this._localDelayOffset += delay - this._pausedDelay;
  19944. this._pausedDelay = null;
  19945. }
  19946. // Animating
  19947. var running = false;
  19948. var animations = this._animations;
  19949. for (var index = 0; index < animations.length; index++) {
  19950. var animation = animations[index];
  19951. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  19952. running = running || isRunning;
  19953. }
  19954. if (!running) {
  19955. // Remove from active animatables
  19956. index = this._scene._activeAnimatables.indexOf(this);
  19957. this._scene._activeAnimatables.splice(index, 1);
  19958. }
  19959. if (!running && this.onAnimationEnd) {
  19960. this.onAnimationEnd();
  19961. }
  19962. return running;
  19963. };
  19964. return Animatable;
  19965. })();
  19966. BABYLON.Animatable = Animatable;
  19967. })(BABYLON || (BABYLON = {}));
  19968. //# sourceMappingURL=babylon.animatable.js.map
  19969. var __extends = this.__extends || function (d, b) {
  19970. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19971. function __() { this.constructor = d; }
  19972. __.prototype = b.prototype;
  19973. d.prototype = new __();
  19974. };
  19975. var BABYLON;
  19976. (function (BABYLON) {
  19977. var EasingFunction = (function () {
  19978. function EasingFunction() {
  19979. // Properties
  19980. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  19981. }
  19982. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  19983. get: function () {
  19984. return EasingFunction._EASINGMODE_EASEIN;
  19985. },
  19986. enumerable: true,
  19987. configurable: true
  19988. });
  19989. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  19990. get: function () {
  19991. return EasingFunction._EASINGMODE_EASEOUT;
  19992. },
  19993. enumerable: true,
  19994. configurable: true
  19995. });
  19996. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  19997. get: function () {
  19998. return EasingFunction._EASINGMODE_EASEINOUT;
  19999. },
  20000. enumerable: true,
  20001. configurable: true
  20002. });
  20003. EasingFunction.prototype.setEasingMode = function (easingMode) {
  20004. var n = Math.min(Math.max(easingMode, 0), 2);
  20005. this._easingMode = n;
  20006. };
  20007. EasingFunction.prototype.getEasingMode = function () {
  20008. return this._easingMode;
  20009. };
  20010. EasingFunction.prototype.easeInCore = function (gradient) {
  20011. throw new Error('You must implement this method');
  20012. };
  20013. EasingFunction.prototype.ease = function (gradient) {
  20014. switch (this._easingMode) {
  20015. case EasingFunction.EASINGMODE_EASEIN:
  20016. return this.easeInCore(gradient);
  20017. case EasingFunction.EASINGMODE_EASEOUT:
  20018. return (1 - this.easeInCore(1 - gradient));
  20019. }
  20020. if (gradient >= 0.5) {
  20021. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  20022. }
  20023. return (this.easeInCore(gradient * 2) * 0.5);
  20024. };
  20025. //Statics
  20026. EasingFunction._EASINGMODE_EASEIN = 0;
  20027. EasingFunction._EASINGMODE_EASEOUT = 1;
  20028. EasingFunction._EASINGMODE_EASEINOUT = 2;
  20029. return EasingFunction;
  20030. })();
  20031. BABYLON.EasingFunction = EasingFunction;
  20032. var CircleEase = (function (_super) {
  20033. __extends(CircleEase, _super);
  20034. function CircleEase() {
  20035. _super.apply(this, arguments);
  20036. }
  20037. CircleEase.prototype.easeInCore = function (gradient) {
  20038. gradient = Math.max(0, Math.min(1, gradient));
  20039. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  20040. };
  20041. return CircleEase;
  20042. })(EasingFunction);
  20043. BABYLON.CircleEase = CircleEase;
  20044. var BackEase = (function (_super) {
  20045. __extends(BackEase, _super);
  20046. function BackEase(amplitude) {
  20047. if (amplitude === void 0) { amplitude = 1; }
  20048. _super.call(this);
  20049. this.amplitude = amplitude;
  20050. }
  20051. BackEase.prototype.easeInCore = function (gradient) {
  20052. var num = Math.max(0, this.amplitude);
  20053. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  20054. };
  20055. return BackEase;
  20056. })(EasingFunction);
  20057. BABYLON.BackEase = BackEase;
  20058. var BounceEase = (function (_super) {
  20059. __extends(BounceEase, _super);
  20060. function BounceEase(bounces, bounciness) {
  20061. if (bounces === void 0) { bounces = 3; }
  20062. if (bounciness === void 0) { bounciness = 2; }
  20063. _super.call(this);
  20064. this.bounces = bounces;
  20065. this.bounciness = bounciness;
  20066. }
  20067. BounceEase.prototype.easeInCore = function (gradient) {
  20068. var y = Math.max(0.0, this.bounces);
  20069. var bounciness = this.bounciness;
  20070. if (bounciness <= 1.0) {
  20071. bounciness = 1.001;
  20072. }
  20073. var num9 = Math.pow(bounciness, y);
  20074. var num5 = 1.0 - bounciness;
  20075. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  20076. var num15 = gradient * num4;
  20077. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  20078. var num3 = Math.floor(num65);
  20079. var num13 = num3 + 1.0;
  20080. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  20081. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  20082. var num7 = (num8 + num12) * 0.5;
  20083. var num6 = gradient - num7;
  20084. var num2 = num7 - num8;
  20085. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  20086. };
  20087. return BounceEase;
  20088. })(EasingFunction);
  20089. BABYLON.BounceEase = BounceEase;
  20090. var CubicEase = (function (_super) {
  20091. __extends(CubicEase, _super);
  20092. function CubicEase() {
  20093. _super.apply(this, arguments);
  20094. }
  20095. CubicEase.prototype.easeInCore = function (gradient) {
  20096. return (gradient * gradient * gradient);
  20097. };
  20098. return CubicEase;
  20099. })(EasingFunction);
  20100. BABYLON.CubicEase = CubicEase;
  20101. var ElasticEase = (function (_super) {
  20102. __extends(ElasticEase, _super);
  20103. function ElasticEase(oscillations, springiness) {
  20104. if (oscillations === void 0) { oscillations = 3; }
  20105. if (springiness === void 0) { springiness = 3; }
  20106. _super.call(this);
  20107. this.oscillations = oscillations;
  20108. this.springiness = springiness;
  20109. }
  20110. ElasticEase.prototype.easeInCore = function (gradient) {
  20111. var num2;
  20112. var num3 = Math.max(0.0, this.oscillations);
  20113. var num = Math.max(0.0, this.springiness);
  20114. if (num == 0) {
  20115. num2 = gradient;
  20116. }
  20117. else {
  20118. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  20119. }
  20120. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  20121. };
  20122. return ElasticEase;
  20123. })(EasingFunction);
  20124. BABYLON.ElasticEase = ElasticEase;
  20125. var ExponentialEase = (function (_super) {
  20126. __extends(ExponentialEase, _super);
  20127. function ExponentialEase(exponent) {
  20128. if (exponent === void 0) { exponent = 2; }
  20129. _super.call(this);
  20130. this.exponent = exponent;
  20131. }
  20132. ExponentialEase.prototype.easeInCore = function (gradient) {
  20133. if (this.exponent <= 0) {
  20134. return gradient;
  20135. }
  20136. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  20137. };
  20138. return ExponentialEase;
  20139. })(EasingFunction);
  20140. BABYLON.ExponentialEase = ExponentialEase;
  20141. var PowerEase = (function (_super) {
  20142. __extends(PowerEase, _super);
  20143. function PowerEase(power) {
  20144. if (power === void 0) { power = 2; }
  20145. _super.call(this);
  20146. this.power = power;
  20147. }
  20148. PowerEase.prototype.easeInCore = function (gradient) {
  20149. var y = Math.max(0.0, this.power);
  20150. return Math.pow(gradient, y);
  20151. };
  20152. return PowerEase;
  20153. })(EasingFunction);
  20154. BABYLON.PowerEase = PowerEase;
  20155. var QuadraticEase = (function (_super) {
  20156. __extends(QuadraticEase, _super);
  20157. function QuadraticEase() {
  20158. _super.apply(this, arguments);
  20159. }
  20160. QuadraticEase.prototype.easeInCore = function (gradient) {
  20161. return (gradient * gradient);
  20162. };
  20163. return QuadraticEase;
  20164. })(EasingFunction);
  20165. BABYLON.QuadraticEase = QuadraticEase;
  20166. var QuarticEase = (function (_super) {
  20167. __extends(QuarticEase, _super);
  20168. function QuarticEase() {
  20169. _super.apply(this, arguments);
  20170. }
  20171. QuarticEase.prototype.easeInCore = function (gradient) {
  20172. return (gradient * gradient * gradient * gradient);
  20173. };
  20174. return QuarticEase;
  20175. })(EasingFunction);
  20176. BABYLON.QuarticEase = QuarticEase;
  20177. var QuinticEase = (function (_super) {
  20178. __extends(QuinticEase, _super);
  20179. function QuinticEase() {
  20180. _super.apply(this, arguments);
  20181. }
  20182. QuinticEase.prototype.easeInCore = function (gradient) {
  20183. return (gradient * gradient * gradient * gradient * gradient);
  20184. };
  20185. return QuinticEase;
  20186. })(EasingFunction);
  20187. BABYLON.QuinticEase = QuinticEase;
  20188. var SineEase = (function (_super) {
  20189. __extends(SineEase, _super);
  20190. function SineEase() {
  20191. _super.apply(this, arguments);
  20192. }
  20193. SineEase.prototype.easeInCore = function (gradient) {
  20194. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  20195. };
  20196. return SineEase;
  20197. })(EasingFunction);
  20198. BABYLON.SineEase = SineEase;
  20199. var BezierCurveEase = (function (_super) {
  20200. __extends(BezierCurveEase, _super);
  20201. function BezierCurveEase(x1, y1, x2, y2) {
  20202. if (x1 === void 0) { x1 = 0; }
  20203. if (y1 === void 0) { y1 = 0; }
  20204. if (x2 === void 0) { x2 = 1; }
  20205. if (y2 === void 0) { y2 = 1; }
  20206. _super.call(this);
  20207. this.x1 = x1;
  20208. this.y1 = y1;
  20209. this.x2 = x2;
  20210. this.y2 = y2;
  20211. }
  20212. BezierCurveEase.prototype.easeInCore = function (gradient) {
  20213. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  20214. };
  20215. return BezierCurveEase;
  20216. })(EasingFunction);
  20217. BABYLON.BezierCurveEase = BezierCurveEase;
  20218. })(BABYLON || (BABYLON = {}));
  20219. //# sourceMappingURL=babylon.easing.js.map
  20220. var BABYLON;
  20221. (function (BABYLON) {
  20222. var Octree = (function () {
  20223. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  20224. if (maxDepth === void 0) { maxDepth = 2; }
  20225. this.maxDepth = maxDepth;
  20226. this.dynamicContent = new Array();
  20227. this._maxBlockCapacity = maxBlockCapacity || 64;
  20228. this._selectionContent = new BABYLON.SmartArray(1024);
  20229. this._creationFunc = creationFunc;
  20230. }
  20231. // Methods
  20232. Octree.prototype.update = function (worldMin, worldMax, entries) {
  20233. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  20234. };
  20235. Octree.prototype.addMesh = function (entry) {
  20236. for (var index = 0; index < this.blocks.length; index++) {
  20237. var block = this.blocks[index];
  20238. block.addEntry(entry);
  20239. }
  20240. };
  20241. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  20242. this._selectionContent.reset();
  20243. for (var index = 0; index < this.blocks.length; index++) {
  20244. var block = this.blocks[index];
  20245. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  20246. }
  20247. if (allowDuplicate) {
  20248. this._selectionContent.concat(this.dynamicContent);
  20249. }
  20250. else {
  20251. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  20252. }
  20253. return this._selectionContent;
  20254. };
  20255. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  20256. this._selectionContent.reset();
  20257. for (var index = 0; index < this.blocks.length; index++) {
  20258. var block = this.blocks[index];
  20259. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  20260. }
  20261. if (allowDuplicate) {
  20262. this._selectionContent.concat(this.dynamicContent);
  20263. }
  20264. else {
  20265. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  20266. }
  20267. return this._selectionContent;
  20268. };
  20269. Octree.prototype.intersectsRay = function (ray) {
  20270. this._selectionContent.reset();
  20271. for (var index = 0; index < this.blocks.length; index++) {
  20272. var block = this.blocks[index];
  20273. block.intersectsRay(ray, this._selectionContent);
  20274. }
  20275. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  20276. return this._selectionContent;
  20277. };
  20278. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  20279. target.blocks = new Array();
  20280. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  20281. for (var x = 0; x < 2; x++) {
  20282. for (var y = 0; y < 2; y++) {
  20283. for (var z = 0; z < 2; z++) {
  20284. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  20285. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  20286. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  20287. block.addEntries(entries);
  20288. target.blocks.push(block);
  20289. }
  20290. }
  20291. }
  20292. };
  20293. Octree.CreationFuncForMeshes = function (entry, block) {
  20294. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  20295. block.entries.push(entry);
  20296. }
  20297. };
  20298. Octree.CreationFuncForSubMeshes = function (entry, block) {
  20299. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  20300. block.entries.push(entry);
  20301. }
  20302. };
  20303. return Octree;
  20304. })();
  20305. BABYLON.Octree = Octree;
  20306. })(BABYLON || (BABYLON = {}));
  20307. //# sourceMappingURL=babylon.octree.js.map
  20308. var BABYLON;
  20309. (function (BABYLON) {
  20310. var OctreeBlock = (function () {
  20311. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  20312. this.entries = new Array();
  20313. this._boundingVectors = new Array();
  20314. this._capacity = capacity;
  20315. this._depth = depth;
  20316. this._maxDepth = maxDepth;
  20317. this._creationFunc = creationFunc;
  20318. this._minPoint = minPoint;
  20319. this._maxPoint = maxPoint;
  20320. this._boundingVectors.push(minPoint.clone());
  20321. this._boundingVectors.push(maxPoint.clone());
  20322. this._boundingVectors.push(minPoint.clone());
  20323. this._boundingVectors[2].x = maxPoint.x;
  20324. this._boundingVectors.push(minPoint.clone());
  20325. this._boundingVectors[3].y = maxPoint.y;
  20326. this._boundingVectors.push(minPoint.clone());
  20327. this._boundingVectors[4].z = maxPoint.z;
  20328. this._boundingVectors.push(maxPoint.clone());
  20329. this._boundingVectors[5].z = minPoint.z;
  20330. this._boundingVectors.push(maxPoint.clone());
  20331. this._boundingVectors[6].x = minPoint.x;
  20332. this._boundingVectors.push(maxPoint.clone());
  20333. this._boundingVectors[7].y = minPoint.y;
  20334. }
  20335. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  20336. // Property
  20337. get: function () {
  20338. return this._capacity;
  20339. },
  20340. enumerable: true,
  20341. configurable: true
  20342. });
  20343. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  20344. get: function () {
  20345. return this._minPoint;
  20346. },
  20347. enumerable: true,
  20348. configurable: true
  20349. });
  20350. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  20351. get: function () {
  20352. return this._maxPoint;
  20353. },
  20354. enumerable: true,
  20355. configurable: true
  20356. });
  20357. // Methods
  20358. OctreeBlock.prototype.addEntry = function (entry) {
  20359. if (this.blocks) {
  20360. for (var index = 0; index < this.blocks.length; index++) {
  20361. var block = this.blocks[index];
  20362. block.addEntry(entry);
  20363. }
  20364. return;
  20365. }
  20366. this._creationFunc(entry, this);
  20367. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  20368. this.createInnerBlocks();
  20369. }
  20370. };
  20371. OctreeBlock.prototype.addEntries = function (entries) {
  20372. for (var index = 0; index < entries.length; index++) {
  20373. var mesh = entries[index];
  20374. this.addEntry(mesh);
  20375. }
  20376. };
  20377. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  20378. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  20379. if (this.blocks) {
  20380. for (var index = 0; index < this.blocks.length; index++) {
  20381. var block = this.blocks[index];
  20382. block.select(frustumPlanes, 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.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  20395. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  20396. if (this.blocks) {
  20397. for (var index = 0; index < this.blocks.length; index++) {
  20398. var block = this.blocks[index];
  20399. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  20400. }
  20401. return;
  20402. }
  20403. if (allowDuplicate) {
  20404. selection.concat(this.entries);
  20405. }
  20406. else {
  20407. selection.concatWithNoDuplicate(this.entries);
  20408. }
  20409. }
  20410. };
  20411. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  20412. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  20413. if (this.blocks) {
  20414. for (var index = 0; index < this.blocks.length; index++) {
  20415. var block = this.blocks[index];
  20416. block.intersectsRay(ray, selection);
  20417. }
  20418. return;
  20419. }
  20420. selection.concatWithNoDuplicate(this.entries);
  20421. }
  20422. };
  20423. OctreeBlock.prototype.createInnerBlocks = function () {
  20424. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  20425. };
  20426. return OctreeBlock;
  20427. })();
  20428. BABYLON.OctreeBlock = OctreeBlock;
  20429. })(BABYLON || (BABYLON = {}));
  20430. //# sourceMappingURL=babylon.octreeBlock.js.map
  20431. var BABYLON;
  20432. (function (BABYLON) {
  20433. var Bone = (function () {
  20434. function Bone(name, skeleton, parentBone, matrix) {
  20435. this.name = name;
  20436. this.children = new Array();
  20437. this.animations = new Array();
  20438. this._worldTransform = new BABYLON.Matrix();
  20439. this._absoluteTransform = new BABYLON.Matrix();
  20440. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  20441. this._skeleton = skeleton;
  20442. this._matrix = matrix;
  20443. this._baseMatrix = matrix;
  20444. skeleton.bones.push(this);
  20445. if (parentBone) {
  20446. this._parent = parentBone;
  20447. parentBone.children.push(this);
  20448. }
  20449. else {
  20450. this._parent = null;
  20451. }
  20452. this._updateDifferenceMatrix();
  20453. }
  20454. // Members
  20455. Bone.prototype.getParent = function () {
  20456. return this._parent;
  20457. };
  20458. Bone.prototype.getLocalMatrix = function () {
  20459. return this._matrix;
  20460. };
  20461. Bone.prototype.getBaseMatrix = function () {
  20462. return this._baseMatrix;
  20463. };
  20464. Bone.prototype.getWorldMatrix = function () {
  20465. return this._worldTransform;
  20466. };
  20467. Bone.prototype.getInvertedAbsoluteTransform = function () {
  20468. return this._invertedAbsoluteTransform;
  20469. };
  20470. Bone.prototype.getAbsoluteMatrix = function () {
  20471. var matrix = this._matrix.clone();
  20472. var parent = this._parent;
  20473. while (parent) {
  20474. matrix = matrix.multiply(parent.getLocalMatrix());
  20475. parent = parent.getParent();
  20476. }
  20477. return matrix;
  20478. };
  20479. // Methods
  20480. Bone.prototype.updateMatrix = function (matrix) {
  20481. this._matrix = matrix;
  20482. this._skeleton._markAsDirty();
  20483. this._updateDifferenceMatrix();
  20484. };
  20485. Bone.prototype._updateDifferenceMatrix = function () {
  20486. if (this._parent) {
  20487. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  20488. }
  20489. else {
  20490. this._absoluteTransform.copyFrom(this._matrix);
  20491. }
  20492. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  20493. for (var index = 0; index < this.children.length; index++) {
  20494. this.children[index]._updateDifferenceMatrix();
  20495. }
  20496. };
  20497. Bone.prototype.markAsDirty = function () {
  20498. this._skeleton._markAsDirty();
  20499. };
  20500. return Bone;
  20501. })();
  20502. BABYLON.Bone = Bone;
  20503. })(BABYLON || (BABYLON = {}));
  20504. //# sourceMappingURL=babylon.bone.js.map
  20505. var BABYLON;
  20506. (function (BABYLON) {
  20507. var Skeleton = (function () {
  20508. function Skeleton(name, id, scene) {
  20509. this.name = name;
  20510. this.id = id;
  20511. this.bones = new Array();
  20512. this._isDirty = true;
  20513. this._identity = BABYLON.Matrix.Identity();
  20514. this.bones = [];
  20515. this._scene = scene;
  20516. scene.skeletons.push(this);
  20517. this.prepare();
  20518. //make sure it will recalculate the matrix next time prepare is called.
  20519. this._isDirty = true;
  20520. }
  20521. // Members
  20522. Skeleton.prototype.getTransformMatrices = function () {
  20523. return this._transformMatrices;
  20524. };
  20525. // Methods
  20526. Skeleton.prototype._markAsDirty = function () {
  20527. this._isDirty = true;
  20528. };
  20529. Skeleton.prototype.prepare = function () {
  20530. if (!this._isDirty) {
  20531. return;
  20532. }
  20533. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  20534. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  20535. }
  20536. for (var index = 0; index < this.bones.length; index++) {
  20537. var bone = this.bones[index];
  20538. var parentBone = bone.getParent();
  20539. if (parentBone) {
  20540. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  20541. }
  20542. else {
  20543. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  20544. }
  20545. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  20546. }
  20547. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  20548. this._isDirty = false;
  20549. this._scene._activeBones += this.bones.length;
  20550. };
  20551. Skeleton.prototype.getAnimatables = function () {
  20552. if (!this._animatables || this._animatables.length !== this.bones.length) {
  20553. this._animatables = [];
  20554. for (var index = 0; index < this.bones.length; index++) {
  20555. this._animatables.push(this.bones[index]);
  20556. }
  20557. }
  20558. return this._animatables;
  20559. };
  20560. Skeleton.prototype.clone = function (name, id) {
  20561. var result = new Skeleton(name, id || name, this._scene);
  20562. for (var index = 0; index < this.bones.length; index++) {
  20563. var source = this.bones[index];
  20564. var parentBone = null;
  20565. if (source.getParent()) {
  20566. var parentIndex = this.bones.indexOf(source.getParent());
  20567. parentBone = result.bones[parentIndex];
  20568. }
  20569. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  20570. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  20571. }
  20572. return result;
  20573. };
  20574. return Skeleton;
  20575. })();
  20576. BABYLON.Skeleton = Skeleton;
  20577. })(BABYLON || (BABYLON = {}));
  20578. //# sourceMappingURL=babylon.skeleton.js.map
  20579. var BABYLON;
  20580. (function (BABYLON) {
  20581. var PostProcess = (function () {
  20582. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  20583. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  20584. this.name = name;
  20585. this.width = -1;
  20586. this.height = -1;
  20587. this._reusable = false;
  20588. this._textures = new BABYLON.SmartArray(2);
  20589. this._currentRenderTextureInd = 0;
  20590. if (camera != null) {
  20591. this._camera = camera;
  20592. this._scene = camera.getScene();
  20593. camera.attachPostProcess(this);
  20594. this._engine = this._scene.getEngine();
  20595. }
  20596. else {
  20597. this._engine = engine;
  20598. }
  20599. this._renderRatio = ratio;
  20600. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  20601. this._reusable = reusable || false;
  20602. samplers = samplers || [];
  20603. samplers.push("textureSampler");
  20604. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  20605. }
  20606. PostProcess.prototype.isReusable = function () {
  20607. return this._reusable;
  20608. };
  20609. PostProcess.prototype.activate = function (camera, sourceTexture) {
  20610. camera = camera || this._camera;
  20611. var scene = camera.getScene();
  20612. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  20613. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  20614. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  20615. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  20616. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  20617. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  20618. if (this._textures.length > 0) {
  20619. for (var i = 0; i < this._textures.length; i++) {
  20620. this._engine._releaseTexture(this._textures.data[i]);
  20621. }
  20622. this._textures.reset();
  20623. }
  20624. this.width = desiredWidth;
  20625. this.height = desiredHeight;
  20626. 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 }));
  20627. if (this._reusable) {
  20628. 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 }));
  20629. }
  20630. if (this.onSizeChanged) {
  20631. this.onSizeChanged();
  20632. }
  20633. }
  20634. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  20635. if (this.onActivate) {
  20636. this.onActivate(camera);
  20637. }
  20638. // Clear
  20639. if (this.clearColor) {
  20640. this._engine.clear(this.clearColor, true, true);
  20641. }
  20642. else {
  20643. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  20644. }
  20645. if (this._reusable) {
  20646. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  20647. }
  20648. };
  20649. PostProcess.prototype.apply = function () {
  20650. // Check
  20651. if (!this._effect.isReady())
  20652. return null;
  20653. // States
  20654. this._engine.enableEffect(this._effect);
  20655. this._engine.setState(false);
  20656. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20657. this._engine.setDepthBuffer(false);
  20658. this._engine.setDepthWrite(false);
  20659. // Texture
  20660. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  20661. // Parameters
  20662. if (this.onApply) {
  20663. this.onApply(this._effect);
  20664. }
  20665. return this._effect;
  20666. };
  20667. PostProcess.prototype.dispose = function (camera) {
  20668. camera = camera || this._camera;
  20669. if (this._textures.length > 0) {
  20670. for (var i = 0; i < this._textures.length; i++) {
  20671. this._engine._releaseTexture(this._textures.data[i]);
  20672. }
  20673. this._textures.reset();
  20674. }
  20675. if (!camera) {
  20676. return;
  20677. }
  20678. camera.detachPostProcess(this);
  20679. var index = camera._postProcesses.indexOf(this);
  20680. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  20681. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  20682. }
  20683. };
  20684. return PostProcess;
  20685. })();
  20686. BABYLON.PostProcess = PostProcess;
  20687. })(BABYLON || (BABYLON = {}));
  20688. //# sourceMappingURL=babylon.postProcess.js.map
  20689. var BABYLON;
  20690. (function (BABYLON) {
  20691. var PostProcessManager = (function () {
  20692. function PostProcessManager(scene) {
  20693. this._vertexDeclaration = [2];
  20694. this._vertexStrideSize = 2 * 4;
  20695. this._scene = scene;
  20696. }
  20697. PostProcessManager.prototype._prepareBuffers = function () {
  20698. if (this._vertexBuffer) {
  20699. return;
  20700. }
  20701. // VBO
  20702. var vertices = [];
  20703. vertices.push(1, 1);
  20704. vertices.push(-1, 1);
  20705. vertices.push(-1, -1);
  20706. vertices.push(1, -1);
  20707. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  20708. // Indices
  20709. var indices = [];
  20710. indices.push(0);
  20711. indices.push(1);
  20712. indices.push(2);
  20713. indices.push(0);
  20714. indices.push(2);
  20715. indices.push(3);
  20716. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  20717. };
  20718. // Methods
  20719. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  20720. var postProcesses = this._scene.activeCamera._postProcesses;
  20721. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  20722. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  20723. return false;
  20724. }
  20725. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  20726. return true;
  20727. };
  20728. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  20729. var engine = this._scene.getEngine();
  20730. for (var index = 0; index < postProcesses.length; index++) {
  20731. if (index < postProcesses.length - 1) {
  20732. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  20733. }
  20734. else {
  20735. if (targetTexture) {
  20736. engine.bindFramebuffer(targetTexture);
  20737. }
  20738. else {
  20739. engine.restoreDefaultFramebuffer();
  20740. }
  20741. }
  20742. var pp = postProcesses[index];
  20743. var effect = pp.apply();
  20744. if (effect) {
  20745. if (pp.onBeforeRender) {
  20746. pp.onBeforeRender(effect);
  20747. }
  20748. // VBOs
  20749. this._prepareBuffers();
  20750. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20751. // Draw order
  20752. engine.draw(true, 0, 6);
  20753. }
  20754. }
  20755. // Restore depth buffer
  20756. engine.setDepthBuffer(true);
  20757. engine.setDepthWrite(true);
  20758. };
  20759. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  20760. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  20761. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  20762. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  20763. return;
  20764. }
  20765. var engine = this._scene.getEngine();
  20766. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  20767. if (index < postProcessesTakenIndices.length - 1) {
  20768. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  20769. }
  20770. else {
  20771. if (targetTexture) {
  20772. engine.bindFramebuffer(targetTexture);
  20773. }
  20774. else {
  20775. engine.restoreDefaultFramebuffer();
  20776. }
  20777. }
  20778. if (doNotPresent) {
  20779. break;
  20780. }
  20781. var pp = postProcesses[postProcessesTakenIndices[index]];
  20782. var effect = pp.apply();
  20783. if (effect) {
  20784. if (pp.onBeforeRender) {
  20785. pp.onBeforeRender(effect);
  20786. }
  20787. // VBOs
  20788. this._prepareBuffers();
  20789. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20790. // Draw order
  20791. engine.draw(true, 0, 6);
  20792. }
  20793. }
  20794. // Restore depth buffer
  20795. engine.setDepthBuffer(true);
  20796. engine.setDepthWrite(true);
  20797. };
  20798. PostProcessManager.prototype.dispose = function () {
  20799. if (this._vertexBuffer) {
  20800. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20801. this._vertexBuffer = null;
  20802. }
  20803. if (this._indexBuffer) {
  20804. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20805. this._indexBuffer = null;
  20806. }
  20807. };
  20808. return PostProcessManager;
  20809. })();
  20810. BABYLON.PostProcessManager = PostProcessManager;
  20811. })(BABYLON || (BABYLON = {}));
  20812. //# sourceMappingURL=babylon.postProcessManager.js.map
  20813. var __extends = this.__extends || function (d, b) {
  20814. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20815. function __() { this.constructor = d; }
  20816. __.prototype = b.prototype;
  20817. d.prototype = new __();
  20818. };
  20819. var BABYLON;
  20820. (function (BABYLON) {
  20821. var PassPostProcess = (function (_super) {
  20822. __extends(PassPostProcess, _super);
  20823. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20824. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  20825. }
  20826. return PassPostProcess;
  20827. })(BABYLON.PostProcess);
  20828. BABYLON.PassPostProcess = PassPostProcess;
  20829. })(BABYLON || (BABYLON = {}));
  20830. //# sourceMappingURL=babylon.passPostProcess.js.map
  20831. var __extends = this.__extends || function (d, b) {
  20832. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20833. function __() { this.constructor = d; }
  20834. __.prototype = b.prototype;
  20835. d.prototype = new __();
  20836. };
  20837. var BABYLON;
  20838. (function (BABYLON) {
  20839. var BlurPostProcess = (function (_super) {
  20840. __extends(BlurPostProcess, _super);
  20841. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  20842. var _this = this;
  20843. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  20844. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  20845. this.direction = direction;
  20846. this.blurWidth = blurWidth;
  20847. this.onApply = function (effect) {
  20848. effect.setFloat2("screenSize", _this.width, _this.height);
  20849. effect.setVector2("direction", _this.direction);
  20850. effect.setFloat("blurWidth", _this.blurWidth);
  20851. };
  20852. }
  20853. return BlurPostProcess;
  20854. })(BABYLON.PostProcess);
  20855. BABYLON.BlurPostProcess = BlurPostProcess;
  20856. })(BABYLON || (BABYLON = {}));
  20857. //# sourceMappingURL=babylon.blurPostProcess.js.map
  20858. var __extends = this.__extends || function (d, b) {
  20859. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20860. function __() { this.constructor = d; }
  20861. __.prototype = b.prototype;
  20862. d.prototype = new __();
  20863. };
  20864. var BABYLON;
  20865. (function (BABYLON) {
  20866. var RefractionPostProcess = (function (_super) {
  20867. __extends(RefractionPostProcess, _super);
  20868. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  20869. var _this = this;
  20870. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  20871. this.color = color;
  20872. this.depth = depth;
  20873. this.colorLevel = colorLevel;
  20874. this.onActivate = function (cam) {
  20875. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  20876. };
  20877. this.onApply = function (effect) {
  20878. effect.setColor3("baseColor", _this.color);
  20879. effect.setFloat("depth", _this.depth);
  20880. effect.setFloat("colorLevel", _this.colorLevel);
  20881. effect.setTexture("refractionSampler", _this._refRexture);
  20882. };
  20883. }
  20884. // Methods
  20885. RefractionPostProcess.prototype.dispose = function (camera) {
  20886. if (this._refRexture) {
  20887. this._refRexture.dispose();
  20888. }
  20889. _super.prototype.dispose.call(this, camera);
  20890. };
  20891. return RefractionPostProcess;
  20892. })(BABYLON.PostProcess);
  20893. BABYLON.RefractionPostProcess = RefractionPostProcess;
  20894. })(BABYLON || (BABYLON = {}));
  20895. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  20896. var __extends = this.__extends || function (d, b) {
  20897. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20898. function __() { this.constructor = d; }
  20899. __.prototype = b.prototype;
  20900. d.prototype = new __();
  20901. };
  20902. var BABYLON;
  20903. (function (BABYLON) {
  20904. var BlackAndWhitePostProcess = (function (_super) {
  20905. __extends(BlackAndWhitePostProcess, _super);
  20906. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20907. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  20908. }
  20909. return BlackAndWhitePostProcess;
  20910. })(BABYLON.PostProcess);
  20911. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  20912. })(BABYLON || (BABYLON = {}));
  20913. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  20914. var __extends = this.__extends || function (d, b) {
  20915. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20916. function __() { this.constructor = d; }
  20917. __.prototype = b.prototype;
  20918. d.prototype = new __();
  20919. };
  20920. var BABYLON;
  20921. (function (BABYLON) {
  20922. var ConvolutionPostProcess = (function (_super) {
  20923. __extends(ConvolutionPostProcess, _super);
  20924. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  20925. var _this = this;
  20926. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  20927. this.kernel = kernel;
  20928. this.onApply = function (effect) {
  20929. effect.setFloat2("screenSize", _this.width, _this.height);
  20930. effect.setArray("kernel", _this.kernel);
  20931. };
  20932. }
  20933. // Statics
  20934. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  20935. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  20936. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  20937. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  20938. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  20939. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  20940. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  20941. return ConvolutionPostProcess;
  20942. })(BABYLON.PostProcess);
  20943. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  20944. })(BABYLON || (BABYLON = {}));
  20945. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  20946. var __extends = this.__extends || function (d, b) {
  20947. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20948. function __() { this.constructor = d; }
  20949. __.prototype = b.prototype;
  20950. d.prototype = new __();
  20951. };
  20952. var BABYLON;
  20953. (function (BABYLON) {
  20954. var FilterPostProcess = (function (_super) {
  20955. __extends(FilterPostProcess, _super);
  20956. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  20957. var _this = this;
  20958. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  20959. this.kernelMatrix = kernelMatrix;
  20960. this.onApply = function (effect) {
  20961. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  20962. };
  20963. }
  20964. return FilterPostProcess;
  20965. })(BABYLON.PostProcess);
  20966. BABYLON.FilterPostProcess = FilterPostProcess;
  20967. })(BABYLON || (BABYLON = {}));
  20968. //# sourceMappingURL=babylon.filterPostProcess.js.map
  20969. var __extends = this.__extends || function (d, b) {
  20970. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20971. function __() { this.constructor = d; }
  20972. __.prototype = b.prototype;
  20973. d.prototype = new __();
  20974. };
  20975. var BABYLON;
  20976. (function (BABYLON) {
  20977. var FxaaPostProcess = (function (_super) {
  20978. __extends(FxaaPostProcess, _super);
  20979. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20980. var _this = this;
  20981. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  20982. this.onSizeChanged = function () {
  20983. _this.texelWidth = 1.0 / _this.width;
  20984. _this.texelHeight = 1.0 / _this.height;
  20985. };
  20986. this.onApply = function (effect) {
  20987. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  20988. };
  20989. }
  20990. return FxaaPostProcess;
  20991. })(BABYLON.PostProcess);
  20992. BABYLON.FxaaPostProcess = FxaaPostProcess;
  20993. })(BABYLON || (BABYLON = {}));
  20994. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  20995. var BABYLON;
  20996. (function (BABYLON) {
  20997. var LensFlare = (function () {
  20998. function LensFlare(size, position, color, imgUrl, system) {
  20999. this.size = size;
  21000. this.position = position;
  21001. this.dispose = function () {
  21002. if (this.texture) {
  21003. this.texture.dispose();
  21004. }
  21005. // Remove from scene
  21006. var index = this._system.lensFlares.indexOf(this);
  21007. this._system.lensFlares.splice(index, 1);
  21008. };
  21009. this.color = color || new BABYLON.Color3(1, 1, 1);
  21010. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  21011. this._system = system;
  21012. system.lensFlares.push(this);
  21013. }
  21014. return LensFlare;
  21015. })();
  21016. BABYLON.LensFlare = LensFlare;
  21017. })(BABYLON || (BABYLON = {}));
  21018. //# sourceMappingURL=babylon.lensFlare.js.map
  21019. var BABYLON;
  21020. (function (BABYLON) {
  21021. var LensFlareSystem = (function () {
  21022. function LensFlareSystem(name, emitter, scene) {
  21023. this.name = name;
  21024. this.lensFlares = new Array();
  21025. this.borderLimit = 300;
  21026. this._vertexDeclaration = [2];
  21027. this._vertexStrideSize = 2 * 4;
  21028. this._isEnabled = true;
  21029. this._scene = scene;
  21030. this._emitter = emitter;
  21031. scene.lensFlareSystems.push(this);
  21032. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  21033. // VBO
  21034. var vertices = [];
  21035. vertices.push(1, 1);
  21036. vertices.push(-1, 1);
  21037. vertices.push(-1, -1);
  21038. vertices.push(1, -1);
  21039. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21040. // Indices
  21041. var indices = [];
  21042. indices.push(0);
  21043. indices.push(1);
  21044. indices.push(2);
  21045. indices.push(0);
  21046. indices.push(2);
  21047. indices.push(3);
  21048. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21049. // Effects
  21050. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  21051. }
  21052. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  21053. get: function () {
  21054. return this._isEnabled;
  21055. },
  21056. set: function (value) {
  21057. this._isEnabled = value;
  21058. },
  21059. enumerable: true,
  21060. configurable: true
  21061. });
  21062. LensFlareSystem.prototype.getScene = function () {
  21063. return this._scene;
  21064. };
  21065. LensFlareSystem.prototype.getEmitter = function () {
  21066. return this._emitter;
  21067. };
  21068. LensFlareSystem.prototype.getEmitterPosition = function () {
  21069. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  21070. };
  21071. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  21072. var position = this.getEmitterPosition();
  21073. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  21074. this._positionX = position.x;
  21075. this._positionY = position.y;
  21076. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  21077. if (position.z > 0) {
  21078. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  21079. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  21080. return true;
  21081. }
  21082. }
  21083. return false;
  21084. };
  21085. LensFlareSystem.prototype._isVisible = function () {
  21086. if (!this._isEnabled) {
  21087. return false;
  21088. }
  21089. var emitterPosition = this.getEmitterPosition();
  21090. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  21091. var distance = direction.length();
  21092. direction.normalize();
  21093. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  21094. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  21095. return !pickInfo.hit || pickInfo.distance > distance;
  21096. };
  21097. LensFlareSystem.prototype.render = function () {
  21098. if (!this._effect.isReady())
  21099. return false;
  21100. var engine = this._scene.getEngine();
  21101. var viewport = this._scene.activeCamera.viewport;
  21102. var globalViewport = viewport.toGlobal(engine);
  21103. // Position
  21104. if (!this.computeEffectivePosition(globalViewport)) {
  21105. return false;
  21106. }
  21107. // Visibility
  21108. if (!this._isVisible()) {
  21109. return false;
  21110. }
  21111. // Intensity
  21112. var awayX;
  21113. var awayY;
  21114. if (this._positionX < this.borderLimit + globalViewport.x) {
  21115. awayX = this.borderLimit + globalViewport.x - this._positionX;
  21116. }
  21117. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  21118. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  21119. }
  21120. else {
  21121. awayX = 0;
  21122. }
  21123. if (this._positionY < this.borderLimit + globalViewport.y) {
  21124. awayY = this.borderLimit + globalViewport.y - this._positionY;
  21125. }
  21126. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  21127. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  21128. }
  21129. else {
  21130. awayY = 0;
  21131. }
  21132. var away = (awayX > awayY) ? awayX : awayY;
  21133. if (away > this.borderLimit) {
  21134. away = this.borderLimit;
  21135. }
  21136. var intensity = 1.0 - (away / this.borderLimit);
  21137. if (intensity < 0) {
  21138. return false;
  21139. }
  21140. if (intensity > 1.0) {
  21141. intensity = 1.0;
  21142. }
  21143. // Position
  21144. var centerX = globalViewport.x + globalViewport.width / 2;
  21145. var centerY = globalViewport.y + globalViewport.height / 2;
  21146. var distX = centerX - this._positionX;
  21147. var distY = centerY - this._positionY;
  21148. // Effects
  21149. engine.enableEffect(this._effect);
  21150. engine.setState(false);
  21151. engine.setDepthBuffer(false);
  21152. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  21153. // VBOs
  21154. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21155. for (var index = 0; index < this.lensFlares.length; index++) {
  21156. var flare = this.lensFlares[index];
  21157. var x = centerX - (distX * flare.position);
  21158. var y = centerY - (distY * flare.position);
  21159. var cw = flare.size;
  21160. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  21161. var cx = 2 * (x / globalViewport.width) - 1.0;
  21162. var cy = 1.0 - 2 * (y / globalViewport.height);
  21163. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  21164. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  21165. // Texture
  21166. this._effect.setTexture("textureSampler", flare.texture);
  21167. // Color
  21168. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  21169. // Draw order
  21170. engine.draw(true, 0, 6);
  21171. }
  21172. engine.setDepthBuffer(true);
  21173. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21174. return true;
  21175. };
  21176. LensFlareSystem.prototype.dispose = function () {
  21177. if (this._vertexBuffer) {
  21178. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21179. this._vertexBuffer = null;
  21180. }
  21181. if (this._indexBuffer) {
  21182. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21183. this._indexBuffer = null;
  21184. }
  21185. while (this.lensFlares.length) {
  21186. this.lensFlares[0].dispose();
  21187. }
  21188. // Remove from scene
  21189. var index = this._scene.lensFlareSystems.indexOf(this);
  21190. this._scene.lensFlareSystems.splice(index, 1);
  21191. };
  21192. return LensFlareSystem;
  21193. })();
  21194. BABYLON.LensFlareSystem = LensFlareSystem;
  21195. })(BABYLON || (BABYLON = {}));
  21196. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  21197. var BABYLON;
  21198. (function (BABYLON) {
  21199. var CannonJSPlugin = (function () {
  21200. function CannonJSPlugin() {
  21201. this._registeredMeshes = [];
  21202. this._physicsMaterials = [];
  21203. this.updateBodyPosition = function (mesh) {
  21204. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21205. var registeredMesh = this._registeredMeshes[index];
  21206. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21207. var body = registeredMesh.body;
  21208. var center = mesh.getBoundingInfo().boundingBox.center;
  21209. body.position.set(center.x, center.z, center.y);
  21210. body.quaternion.x = mesh.rotationQuaternion.x;
  21211. body.quaternion.z = mesh.rotationQuaternion.y;
  21212. body.quaternion.y = mesh.rotationQuaternion.z;
  21213. body.quaternion.w = -mesh.rotationQuaternion.w;
  21214. return;
  21215. }
  21216. }
  21217. };
  21218. }
  21219. CannonJSPlugin.prototype.initialize = function (iterations) {
  21220. if (iterations === void 0) { iterations = 10; }
  21221. this._world = new CANNON.World();
  21222. this._world.broadphase = new CANNON.NaiveBroadphase();
  21223. this._world.solver.iterations = iterations;
  21224. };
  21225. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  21226. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21227. };
  21228. CannonJSPlugin.prototype.runOneStep = function (delta) {
  21229. this._world.step(delta);
  21230. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21231. var registeredMesh = this._registeredMeshes[index];
  21232. if (registeredMesh.isChild) {
  21233. continue;
  21234. }
  21235. // Body position
  21236. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  21237. var deltaPos = registeredMesh.delta;
  21238. if (deltaPos) {
  21239. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  21240. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  21241. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  21242. }
  21243. else {
  21244. registeredMesh.mesh.position.x = bodyX;
  21245. registeredMesh.mesh.position.y = bodyZ;
  21246. registeredMesh.mesh.position.z = bodyY;
  21247. }
  21248. if (!registeredMesh.mesh.rotationQuaternion) {
  21249. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21250. }
  21251. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  21252. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  21253. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  21254. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  21255. }
  21256. };
  21257. CannonJSPlugin.prototype.setGravity = function (gravity) {
  21258. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  21259. };
  21260. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21261. this.unregisterMesh(mesh);
  21262. mesh.computeWorldMatrix(true);
  21263. switch (impostor) {
  21264. case BABYLON.PhysicsEngine.SphereImpostor:
  21265. var bbox = mesh.getBoundingInfo().boundingBox;
  21266. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21267. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21268. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21269. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  21270. case BABYLON.PhysicsEngine.BoxImpostor:
  21271. bbox = mesh.getBoundingInfo().boundingBox;
  21272. var min = bbox.minimumWorld;
  21273. var max = bbox.maximumWorld;
  21274. var box = max.subtract(min).scale(0.5);
  21275. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  21276. case BABYLON.PhysicsEngine.PlaneImpostor:
  21277. return this._createPlane(mesh, options);
  21278. case BABYLON.PhysicsEngine.MeshImpostor:
  21279. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21280. var rawFaces = mesh.getIndices();
  21281. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  21282. }
  21283. return null;
  21284. };
  21285. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  21286. var shape = new CANNON.Sphere(radius);
  21287. if (!options) {
  21288. return shape;
  21289. }
  21290. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21291. };
  21292. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  21293. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  21294. if (!options) {
  21295. return shape;
  21296. }
  21297. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21298. };
  21299. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  21300. var shape = new CANNON.Plane();
  21301. if (!options) {
  21302. return shape;
  21303. }
  21304. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21305. };
  21306. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  21307. var verts = [], faces = [];
  21308. mesh.computeWorldMatrix(true);
  21309. for (var i = 0; i < rawVerts.length; i += 3) {
  21310. var transformed = BABYLON.Vector3.Zero();
  21311. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  21312. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  21313. }
  21314. for (var j = 0; j < rawFaces.length; j += 3) {
  21315. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  21316. }
  21317. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  21318. if (!options) {
  21319. return shape;
  21320. }
  21321. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21322. };
  21323. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  21324. var index;
  21325. var mat;
  21326. for (index = 0; index < this._physicsMaterials.length; index++) {
  21327. mat = this._physicsMaterials[index];
  21328. if (mat.friction === friction && mat.restitution === restitution) {
  21329. return mat;
  21330. }
  21331. }
  21332. var currentMat = new CANNON.Material();
  21333. currentMat.friction = friction;
  21334. currentMat.restitution = restitution;
  21335. this._physicsMaterials.push(currentMat);
  21336. for (index = 0; index < this._physicsMaterials.length; index++) {
  21337. mat = this._physicsMaterials[index];
  21338. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  21339. contactMaterial.contactEquationStiffness = 1e10;
  21340. contactMaterial.contactEquationRegularizationTime = 10;
  21341. this._world.addContactMaterial(contactMaterial);
  21342. }
  21343. return currentMat;
  21344. };
  21345. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  21346. var initialRotation = null;
  21347. if (mesh.rotationQuaternion) {
  21348. initialRotation = mesh.rotationQuaternion.clone();
  21349. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21350. }
  21351. // The delta between the mesh position and the mesh bounding box center
  21352. var bbox = mesh.getBoundingInfo().boundingBox;
  21353. var deltaPosition = mesh.position.subtract(bbox.center);
  21354. var material = this._addMaterial(friction, restitution);
  21355. var body = new CANNON.RigidBody(mass, shape, material);
  21356. if (initialRotation) {
  21357. body.quaternion.x = initialRotation.x;
  21358. body.quaternion.z = initialRotation.y;
  21359. body.quaternion.y = initialRotation.z;
  21360. body.quaternion.w = -initialRotation.w;
  21361. }
  21362. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  21363. this._world.add(body);
  21364. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  21365. return body;
  21366. };
  21367. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21368. var compoundShape = new CANNON.Compound();
  21369. for (var index = 0; index < parts.length; index++) {
  21370. var mesh = parts[index].mesh;
  21371. var shape = this.registerMesh(mesh, parts[index].impostor);
  21372. if (index == 0) {
  21373. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  21374. }
  21375. else {
  21376. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  21377. }
  21378. }
  21379. var initialMesh = parts[0].mesh;
  21380. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  21381. body.parts = parts;
  21382. return body;
  21383. };
  21384. CannonJSPlugin.prototype._unbindBody = function (body) {
  21385. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21386. var registeredMesh = this._registeredMeshes[index];
  21387. if (registeredMesh.body === body) {
  21388. registeredMesh.body = null;
  21389. registeredMesh.delta = 0;
  21390. }
  21391. }
  21392. };
  21393. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  21394. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21395. var registeredMesh = this._registeredMeshes[index];
  21396. if (registeredMesh.mesh === mesh) {
  21397. // Remove body
  21398. if (registeredMesh.body) {
  21399. this._world.remove(registeredMesh.body);
  21400. this._unbindBody(registeredMesh.body);
  21401. }
  21402. this._registeredMeshes.splice(index, 1);
  21403. return;
  21404. }
  21405. }
  21406. };
  21407. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21408. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  21409. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  21410. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21411. var registeredMesh = this._registeredMeshes[index];
  21412. if (registeredMesh.mesh === mesh) {
  21413. registeredMesh.body.applyImpulse(impulse, worldPoint);
  21414. return;
  21415. }
  21416. }
  21417. };
  21418. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  21419. var body1 = null, body2 = null;
  21420. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21421. var registeredMesh = this._registeredMeshes[index];
  21422. if (registeredMesh.mesh === mesh1) {
  21423. body1 = registeredMesh.body;
  21424. }
  21425. else if (registeredMesh.mesh === mesh2) {
  21426. body2 = registeredMesh.body;
  21427. }
  21428. }
  21429. if (!body1 || !body2) {
  21430. return false;
  21431. }
  21432. 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));
  21433. this._world.addConstraint(constraint);
  21434. return true;
  21435. };
  21436. CannonJSPlugin.prototype.dispose = function () {
  21437. while (this._registeredMeshes.length) {
  21438. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21439. }
  21440. };
  21441. CannonJSPlugin.prototype.isSupported = function () {
  21442. return window.CANNON !== undefined;
  21443. };
  21444. return CannonJSPlugin;
  21445. })();
  21446. BABYLON.CannonJSPlugin = CannonJSPlugin;
  21447. })(BABYLON || (BABYLON = {}));
  21448. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  21449. var BABYLON;
  21450. (function (BABYLON) {
  21451. var OimoJSPlugin = (function () {
  21452. function OimoJSPlugin() {
  21453. this._registeredMeshes = [];
  21454. /**
  21455. * Update the body position according to the mesh position
  21456. * @param mesh
  21457. */
  21458. this.updateBodyPosition = function (mesh) {
  21459. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21460. var registeredMesh = this._registeredMeshes[index];
  21461. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21462. var body = registeredMesh.body.body;
  21463. mesh.computeWorldMatrix(true);
  21464. var center = mesh.getBoundingInfo().boundingBox.center;
  21465. body.setPosition(center.x, center.y, center.z);
  21466. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  21467. return;
  21468. }
  21469. // Case where the parent has been updated
  21470. if (registeredMesh.mesh.parent === mesh) {
  21471. mesh.computeWorldMatrix(true);
  21472. registeredMesh.mesh.computeWorldMatrix(true);
  21473. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  21474. var absoluteRotation = mesh.rotation;
  21475. body = registeredMesh.body.body;
  21476. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  21477. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  21478. return;
  21479. }
  21480. }
  21481. };
  21482. }
  21483. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  21484. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21485. };
  21486. OimoJSPlugin.prototype.initialize = function (iterations) {
  21487. this._world = new OIMO.World();
  21488. this._world.clear();
  21489. };
  21490. OimoJSPlugin.prototype.setGravity = function (gravity) {
  21491. this._world.gravity = gravity;
  21492. };
  21493. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21494. var body = null;
  21495. this.unregisterMesh(mesh);
  21496. mesh.computeWorldMatrix(true);
  21497. var initialRotation = null;
  21498. if (mesh.rotationQuaternion) {
  21499. initialRotation = mesh.rotationQuaternion.clone();
  21500. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21501. mesh.computeWorldMatrix(true);
  21502. }
  21503. var bbox = mesh.getBoundingInfo().boundingBox;
  21504. // The delta between the mesh position and the mesh bounding box center
  21505. var deltaPosition = mesh.position.subtract(bbox.center);
  21506. // Transform delta position with the rotation
  21507. if (initialRotation) {
  21508. var m = new BABYLON.Matrix();
  21509. initialRotation.toRotationMatrix(m);
  21510. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  21511. }
  21512. switch (impostor) {
  21513. case BABYLON.PhysicsEngine.SphereImpostor:
  21514. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21515. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21516. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21517. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  21518. body = new OIMO.Body({
  21519. type: 'sphere',
  21520. size: [size],
  21521. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  21522. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  21523. move: options.mass != 0,
  21524. config: [options.mass, options.friction, options.restitution],
  21525. world: this._world
  21526. });
  21527. break;
  21528. case BABYLON.PhysicsEngine.PlaneImpostor:
  21529. case BABYLON.PhysicsEngine.CylinderImpostor:
  21530. case BABYLON.PhysicsEngine.BoxImpostor:
  21531. var min = bbox.minimumWorld;
  21532. var max = bbox.maximumWorld;
  21533. var box = max.subtract(min);
  21534. var sizeX = this._checkWithEpsilon(box.x);
  21535. var sizeY = this._checkWithEpsilon(box.y);
  21536. var sizeZ = this._checkWithEpsilon(box.z);
  21537. body = new OIMO.Body({
  21538. type: 'box',
  21539. size: [sizeX, sizeY, sizeZ],
  21540. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  21541. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  21542. move: options.mass != 0,
  21543. config: [options.mass, options.friction, options.restitution],
  21544. world: this._world
  21545. });
  21546. break;
  21547. }
  21548. //If quaternion was set as the rotation of the object
  21549. if (initialRotation) {
  21550. //We have to access the rigid body's properties to set the quaternion.
  21551. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  21552. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  21553. //update the internal rotation matrix
  21554. body.body.syncShapes();
  21555. }
  21556. this._registeredMeshes.push({
  21557. mesh: mesh,
  21558. body: body,
  21559. delta: deltaPosition
  21560. });
  21561. return body;
  21562. };
  21563. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21564. var types = [], sizes = [], positions = [], rotations = [];
  21565. var initialMesh = parts[0].mesh;
  21566. for (var index = 0; index < parts.length; index++) {
  21567. var part = parts[index];
  21568. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  21569. types.push(bodyParameters.type);
  21570. sizes.push.apply(sizes, bodyParameters.size);
  21571. positions.push.apply(positions, bodyParameters.pos);
  21572. rotations.push.apply(rotations, bodyParameters.rot);
  21573. }
  21574. var body = new OIMO.Body({
  21575. type: types,
  21576. size: sizes,
  21577. pos: positions,
  21578. rot: rotations,
  21579. move: options.mass != 0,
  21580. config: [options.mass, options.friction, options.restitution],
  21581. world: this._world
  21582. });
  21583. this._registeredMeshes.push({
  21584. mesh: initialMesh,
  21585. body: body
  21586. });
  21587. return body;
  21588. };
  21589. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  21590. var bodyParameters = null;
  21591. var mesh = part.mesh;
  21592. // We need the bounding box/sphere info to compute the physics body
  21593. mesh.computeWorldMatrix();
  21594. switch (part.impostor) {
  21595. case BABYLON.PhysicsEngine.SphereImpostor:
  21596. var bbox = mesh.getBoundingInfo().boundingBox;
  21597. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21598. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21599. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21600. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  21601. bodyParameters = {
  21602. type: 'sphere',
  21603. /* bug with oimo : sphere needs 3 sizes in this case */
  21604. size: [size, -1, -1],
  21605. pos: [mesh.position.x, mesh.position.y, mesh.position.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. case BABYLON.PhysicsEngine.PlaneImpostor:
  21610. case BABYLON.PhysicsEngine.BoxImpostor:
  21611. bbox = mesh.getBoundingInfo().boundingBox;
  21612. var min = bbox.minimumWorld;
  21613. var max = bbox.maximumWorld;
  21614. var box = max.subtract(min);
  21615. var sizeX = this._checkWithEpsilon(box.x);
  21616. var sizeY = this._checkWithEpsilon(box.y);
  21617. var sizeZ = this._checkWithEpsilon(box.z);
  21618. var relativePosition = mesh.position;
  21619. bodyParameters = {
  21620. type: 'box',
  21621. size: [sizeX, sizeY, sizeZ],
  21622. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  21623. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  21624. };
  21625. break;
  21626. }
  21627. return bodyParameters;
  21628. };
  21629. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  21630. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21631. var registeredMesh = this._registeredMeshes[index];
  21632. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21633. if (registeredMesh.body) {
  21634. this._world.removeRigidBody(registeredMesh.body.body);
  21635. this._unbindBody(registeredMesh.body);
  21636. }
  21637. this._registeredMeshes.splice(index, 1);
  21638. return;
  21639. }
  21640. }
  21641. };
  21642. OimoJSPlugin.prototype._unbindBody = function (body) {
  21643. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21644. var registeredMesh = this._registeredMeshes[index];
  21645. if (registeredMesh.body === body) {
  21646. registeredMesh.body = null;
  21647. }
  21648. }
  21649. };
  21650. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21651. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21652. var registeredMesh = this._registeredMeshes[index];
  21653. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21654. // Get object mass to have a behaviour similar to cannon.js
  21655. var mass = registeredMesh.body.body.massInfo.mass;
  21656. // The force is scaled with the mass of object
  21657. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  21658. return;
  21659. }
  21660. }
  21661. };
  21662. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  21663. var body1 = null, body2 = null;
  21664. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21665. var registeredMesh = this._registeredMeshes[index];
  21666. if (registeredMesh.mesh === mesh1) {
  21667. body1 = registeredMesh.body.body;
  21668. }
  21669. else if (registeredMesh.mesh === mesh2) {
  21670. body2 = registeredMesh.body.body;
  21671. }
  21672. }
  21673. if (!body1 || !body2) {
  21674. return false;
  21675. }
  21676. if (!options) {
  21677. options = {};
  21678. }
  21679. new OIMO.Link({
  21680. type: options.type,
  21681. body1: body1,
  21682. body2: body2,
  21683. min: options.min,
  21684. max: options.max,
  21685. axe1: options.axe1,
  21686. axe2: options.axe2,
  21687. pos1: [pivot1.x, pivot1.y, pivot1.z],
  21688. pos2: [pivot2.x, pivot2.y, pivot2.z],
  21689. collision: options.collision,
  21690. spring: options.spring,
  21691. world: this._world
  21692. });
  21693. return true;
  21694. };
  21695. OimoJSPlugin.prototype.dispose = function () {
  21696. this._world.clear();
  21697. while (this._registeredMeshes.length) {
  21698. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21699. }
  21700. };
  21701. OimoJSPlugin.prototype.isSupported = function () {
  21702. return OIMO !== undefined;
  21703. };
  21704. OimoJSPlugin.prototype._getLastShape = function (body) {
  21705. var lastShape = body.shapes;
  21706. while (lastShape.next) {
  21707. lastShape = lastShape.next;
  21708. }
  21709. return lastShape;
  21710. };
  21711. OimoJSPlugin.prototype.runOneStep = function (time) {
  21712. this._world.step();
  21713. // Update the position of all registered meshes
  21714. var i = this._registeredMeshes.length;
  21715. var m;
  21716. while (i--) {
  21717. var body = this._registeredMeshes[i].body.body;
  21718. var mesh = this._registeredMeshes[i].mesh;
  21719. var delta = this._registeredMeshes[i].delta;
  21720. if (!body.sleeping) {
  21721. if (body.shapes.next) {
  21722. var parentShape = this._getLastShape(body);
  21723. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  21724. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  21725. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  21726. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  21727. if (!mesh.rotationQuaternion) {
  21728. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21729. }
  21730. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  21731. mesh.computeWorldMatrix();
  21732. }
  21733. else {
  21734. m = body.getMatrix();
  21735. mtx = BABYLON.Matrix.FromArray(m);
  21736. // Body position
  21737. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  21738. if (!delta) {
  21739. mesh.position.x = bodyX;
  21740. mesh.position.y = bodyY;
  21741. mesh.position.z = bodyZ;
  21742. }
  21743. else {
  21744. mesh.position.x = bodyX + delta.x;
  21745. mesh.position.y = bodyY + delta.y;
  21746. mesh.position.z = bodyZ + delta.z;
  21747. }
  21748. if (!mesh.rotationQuaternion) {
  21749. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21750. }
  21751. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  21752. mesh.computeWorldMatrix();
  21753. }
  21754. }
  21755. }
  21756. };
  21757. return OimoJSPlugin;
  21758. })();
  21759. BABYLON.OimoJSPlugin = OimoJSPlugin;
  21760. })(BABYLON || (BABYLON = {}));
  21761. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  21762. var BABYLON;
  21763. (function (BABYLON) {
  21764. var PhysicsEngine = (function () {
  21765. function PhysicsEngine(plugin) {
  21766. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  21767. }
  21768. PhysicsEngine.prototype._initialize = function (gravity) {
  21769. this._currentPlugin.initialize();
  21770. this._setGravity(gravity);
  21771. };
  21772. PhysicsEngine.prototype._runOneStep = function (delta) {
  21773. if (delta > 0.1) {
  21774. delta = 0.1;
  21775. }
  21776. else if (delta <= 0) {
  21777. delta = 1.0 / 60.0;
  21778. }
  21779. this._currentPlugin.runOneStep(delta);
  21780. };
  21781. PhysicsEngine.prototype._setGravity = function (gravity) {
  21782. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  21783. this._currentPlugin.setGravity(this.gravity);
  21784. };
  21785. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  21786. return this._currentPlugin.registerMesh(mesh, impostor, options);
  21787. };
  21788. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  21789. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  21790. };
  21791. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  21792. this._currentPlugin.unregisterMesh(mesh);
  21793. };
  21794. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  21795. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  21796. };
  21797. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  21798. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  21799. };
  21800. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  21801. this._currentPlugin.updateBodyPosition(mesh);
  21802. };
  21803. PhysicsEngine.prototype.dispose = function () {
  21804. this._currentPlugin.dispose();
  21805. };
  21806. PhysicsEngine.prototype.isSupported = function () {
  21807. return this._currentPlugin.isSupported();
  21808. };
  21809. // Statics
  21810. PhysicsEngine.NoImpostor = 0;
  21811. PhysicsEngine.SphereImpostor = 1;
  21812. PhysicsEngine.BoxImpostor = 2;
  21813. PhysicsEngine.PlaneImpostor = 3;
  21814. PhysicsEngine.MeshImpostor = 4;
  21815. PhysicsEngine.CapsuleImpostor = 5;
  21816. PhysicsEngine.ConeImpostor = 6;
  21817. PhysicsEngine.CylinderImpostor = 7;
  21818. PhysicsEngine.ConvexHullImpostor = 8;
  21819. PhysicsEngine.Epsilon = 0.001;
  21820. return PhysicsEngine;
  21821. })();
  21822. BABYLON.PhysicsEngine = PhysicsEngine;
  21823. })(BABYLON || (BABYLON = {}));
  21824. //# sourceMappingURL=babylon.physicsEngine.js.map
  21825. var BABYLON;
  21826. (function (BABYLON) {
  21827. var serializeLight = function (light) {
  21828. var serializationObject = {};
  21829. serializationObject.name = light.name;
  21830. serializationObject.id = light.id;
  21831. serializationObject.tags = BABYLON.Tags.GetTags(light);
  21832. if (light instanceof BABYLON.PointLight) {
  21833. serializationObject.type = 0;
  21834. serializationObject.position = light.position.asArray();
  21835. }
  21836. else if (light instanceof BABYLON.DirectionalLight) {
  21837. serializationObject.type = 1;
  21838. var directionalLight = light;
  21839. serializationObject.position = directionalLight.position.asArray();
  21840. serializationObject.direction = directionalLight.direction.asArray();
  21841. }
  21842. else if (light instanceof BABYLON.SpotLight) {
  21843. serializationObject.type = 2;
  21844. var spotLight = light;
  21845. serializationObject.position = spotLight.position.asArray();
  21846. serializationObject.direction = spotLight.position.asArray();
  21847. serializationObject.angle = spotLight.angle;
  21848. serializationObject.exponent = spotLight.exponent;
  21849. }
  21850. else if (light instanceof BABYLON.HemisphericLight) {
  21851. serializationObject.type = 3;
  21852. var hemisphericLight = light;
  21853. serializationObject.direction = hemisphericLight.direction.asArray();
  21854. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  21855. }
  21856. if (light.intensity) {
  21857. serializationObject.intensity = light.intensity;
  21858. }
  21859. serializationObject.range = light.range;
  21860. serializationObject.diffuse = light.diffuse.asArray();
  21861. serializationObject.specular = light.specular.asArray();
  21862. return serializationObject;
  21863. };
  21864. var serializeFresnelParameter = function (fresnelParameter) {
  21865. var serializationObject = {};
  21866. serializationObject.isEnabled = fresnelParameter.isEnabled;
  21867. serializationObject.leftColor = fresnelParameter.leftColor;
  21868. serializationObject.rightColor = fresnelParameter.rightColor;
  21869. serializationObject.bias = fresnelParameter.bias;
  21870. serializationObject.power = fresnelParameter.power;
  21871. return serializationObject;
  21872. };
  21873. var appendAnimations = function (source, destination) {
  21874. if (source.animations) {
  21875. destination.animations = [];
  21876. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  21877. var animation = source.animations[animationIndex];
  21878. destination.animations.push(serializeAnimation(animation));
  21879. }
  21880. }
  21881. };
  21882. var serializeCamera = function (camera) {
  21883. var serializationObject = {};
  21884. serializationObject.name = camera.name;
  21885. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  21886. serializationObject.id = camera.id;
  21887. serializationObject.position = camera.position.asArray();
  21888. // Parent
  21889. if (camera.parent) {
  21890. serializationObject.parentId = camera.parent.id;
  21891. }
  21892. serializationObject.fov = camera.fov;
  21893. serializationObject.minZ = camera.minZ;
  21894. serializationObject.maxZ = camera.maxZ;
  21895. serializationObject.inertia = camera.inertia;
  21896. //setting the type
  21897. if (camera instanceof BABYLON.FreeCamera) {
  21898. serializationObject.type = "FreeCamera";
  21899. }
  21900. else if (camera instanceof BABYLON.ArcRotateCamera) {
  21901. serializationObject.type = "ArcRotateCamera";
  21902. }
  21903. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  21904. serializationObject.type = "AnaglyphArcRotateCamera";
  21905. }
  21906. else if (camera instanceof BABYLON.GamepadCamera) {
  21907. serializationObject.type = "GamepadCamera";
  21908. }
  21909. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  21910. serializationObject.type = "AnaglyphFreeCamera";
  21911. }
  21912. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  21913. serializationObject.type = "DeviceOrientationCamera";
  21914. }
  21915. else if (camera instanceof BABYLON.FollowCamera) {
  21916. serializationObject.type = "FollowCamera";
  21917. }
  21918. else if (camera instanceof BABYLON.OculusCamera) {
  21919. serializationObject.type = "OculusCamera";
  21920. }
  21921. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  21922. serializationObject.type = "OculusGamepadCamera";
  21923. }
  21924. else if (camera instanceof BABYLON.TouchCamera) {
  21925. serializationObject.type = "TouchCamera";
  21926. }
  21927. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  21928. serializationObject.type = "VirtualJoysticksCamera";
  21929. }
  21930. else if (camera instanceof BABYLON.WebVRCamera) {
  21931. serializationObject.type = "WebVRCamera";
  21932. }
  21933. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  21934. serializationObject.type = "VRDeviceOrientationCamera";
  21935. }
  21936. //special properties of specific cameras
  21937. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  21938. var arcCamera = camera;
  21939. serializationObject.alpha = arcCamera.alpha;
  21940. serializationObject.beta = arcCamera.beta;
  21941. serializationObject.radius = arcCamera.radius;
  21942. if (arcCamera.target && arcCamera.target.id) {
  21943. serializationObject.lockedTargetId = arcCamera.target.id;
  21944. }
  21945. }
  21946. else if (camera instanceof BABYLON.FollowCamera) {
  21947. var followCam = camera;
  21948. serializationObject.radius = followCam.radius;
  21949. serializationObject.heightOffset = followCam.heightOffset;
  21950. serializationObject.rotationOffset = followCam.rotationOffset;
  21951. }
  21952. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  21953. //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.
  21954. if (camera['_eyeSpace'] !== undefined) {
  21955. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  21956. }
  21957. }
  21958. //general properties that not all cameras have. The [] is due to typescript's type safety
  21959. if (camera['speed'] !== undefined) {
  21960. serializationObject.speed = camera['speed'];
  21961. }
  21962. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  21963. serializationObject.target = camera['target'].asArray();
  21964. }
  21965. // Target
  21966. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  21967. serializationObject.rotation = camera['rotation'].asArray();
  21968. }
  21969. // Locked target
  21970. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  21971. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  21972. }
  21973. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  21974. serializationObject.applyGravity = camera['applyGravity'] || false;
  21975. if (camera['ellipsoid']) {
  21976. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  21977. }
  21978. // Animations
  21979. appendAnimations(camera, serializationObject);
  21980. // Layer mask
  21981. serializationObject.layerMask = camera.layerMask;
  21982. return serializationObject;
  21983. };
  21984. var serializeAnimation = function (animation) {
  21985. var serializationObject = {};
  21986. serializationObject.name = animation.name;
  21987. serializationObject.property = animation.targetProperty;
  21988. serializationObject.framePerSecond = animation.framePerSecond;
  21989. serializationObject.dataType = animation.dataType;
  21990. serializationObject.loopBehavior = animation.loopMode;
  21991. var dataType = animation.dataType;
  21992. serializationObject.keys = [];
  21993. var keys = animation.getKeys();
  21994. for (var index = 0; index < keys.length; index++) {
  21995. var animationKey = keys[index];
  21996. var key = {};
  21997. key.frame = animationKey.frame;
  21998. switch (dataType) {
  21999. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  22000. key.values = [animationKey.value];
  22001. break;
  22002. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  22003. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  22004. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  22005. key.values = animationKey.value.asArray();
  22006. break;
  22007. }
  22008. serializationObject.keys.push(key);
  22009. }
  22010. return serializationObject;
  22011. };
  22012. var serializeMultiMaterial = function (material) {
  22013. var serializationObject = {};
  22014. serializationObject.name = material.name;
  22015. serializationObject.id = material.id;
  22016. serializationObject.tags = BABYLON.Tags.GetTags(material);
  22017. serializationObject.materials = [];
  22018. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  22019. var subMat = material.subMaterials[matIndex];
  22020. if (subMat) {
  22021. serializationObject.materials.push(subMat.id);
  22022. }
  22023. else {
  22024. serializationObject.materials.push(null);
  22025. }
  22026. }
  22027. return serializationObject;
  22028. };
  22029. var serializeMaterial = function (material) {
  22030. var serializationObject = {};
  22031. serializationObject.name = material.name;
  22032. serializationObject.ambient = material.ambientColor.asArray();
  22033. serializationObject.diffuse = material.diffuseColor.asArray();
  22034. serializationObject.specular = material.specularColor.asArray();
  22035. serializationObject.specularPower = material.specularPower;
  22036. serializationObject.emissive = material.emissiveColor.asArray();
  22037. serializationObject.alpha = material.alpha;
  22038. serializationObject.id = material.id;
  22039. serializationObject.tags = BABYLON.Tags.GetTags(material);
  22040. serializationObject.backFaceCulling = material.backFaceCulling;
  22041. if (material.diffuseTexture) {
  22042. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  22043. }
  22044. if (material.diffuseFresnelParameters) {
  22045. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  22046. }
  22047. if (material.ambientTexture) {
  22048. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  22049. }
  22050. if (material.opacityTexture) {
  22051. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  22052. }
  22053. if (material.opacityFresnelParameters) {
  22054. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  22055. }
  22056. if (material.reflectionTexture) {
  22057. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  22058. }
  22059. if (material.reflectionFresnelParameters) {
  22060. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  22061. }
  22062. if (material.emissiveTexture) {
  22063. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  22064. }
  22065. if (material.emissiveFresnelParameters) {
  22066. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  22067. }
  22068. if (material.specularTexture) {
  22069. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  22070. }
  22071. if (material.bumpTexture) {
  22072. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  22073. }
  22074. return serializationObject;
  22075. };
  22076. var serializeTexture = function (texture) {
  22077. var serializationObject = {};
  22078. if (!texture.name) {
  22079. return null;
  22080. }
  22081. if (texture instanceof BABYLON.CubeTexture) {
  22082. serializationObject.name = texture.name;
  22083. serializationObject.hasAlpha = texture.hasAlpha;
  22084. serializationObject.level = texture.level;
  22085. serializationObject.coordinatesMode = texture.coordinatesMode;
  22086. return serializationObject;
  22087. }
  22088. if (texture instanceof BABYLON.MirrorTexture) {
  22089. var mirrorTexture = texture;
  22090. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  22091. serializationObject.renderList = [];
  22092. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  22093. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  22094. }
  22095. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  22096. }
  22097. else if (texture instanceof BABYLON.RenderTargetTexture) {
  22098. var renderTargetTexture = texture;
  22099. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  22100. serializationObject.renderList = [];
  22101. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  22102. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  22103. }
  22104. }
  22105. var regularTexture = texture;
  22106. serializationObject.name = texture.name;
  22107. serializationObject.hasAlpha = texture.hasAlpha;
  22108. serializationObject.level = texture.level;
  22109. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  22110. serializationObject.coordinatesMode = texture.coordinatesMode;
  22111. serializationObject.uOffset = regularTexture.uOffset;
  22112. serializationObject.vOffset = regularTexture.vOffset;
  22113. serializationObject.uScale = regularTexture.uScale;
  22114. serializationObject.vScale = regularTexture.vScale;
  22115. serializationObject.uAng = regularTexture.uAng;
  22116. serializationObject.vAng = regularTexture.vAng;
  22117. serializationObject.wAng = regularTexture.wAng;
  22118. serializationObject.wrapU = texture.wrapU;
  22119. serializationObject.wrapV = texture.wrapV;
  22120. // Animations
  22121. appendAnimations(texture, serializationObject);
  22122. return serializationObject;
  22123. };
  22124. var serializeSkeleton = function (skeleton) {
  22125. var serializationObject = {};
  22126. serializationObject.name = skeleton.name;
  22127. serializationObject.id = skeleton.id;
  22128. serializationObject.bones = [];
  22129. for (var index = 0; index < skeleton.bones.length; index++) {
  22130. var bone = skeleton.bones[index];
  22131. var serializedBone = {
  22132. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  22133. name: bone.name,
  22134. matrix: bone.getLocalMatrix().toArray()
  22135. };
  22136. serializationObject.bones.push(serializedBone);
  22137. if (bone.animations && bone.animations.length > 0) {
  22138. serializedBone.animation = serializeAnimation(bone.animations[0]);
  22139. }
  22140. }
  22141. return serializationObject;
  22142. };
  22143. var serializeParticleSystem = function (particleSystem) {
  22144. var serializationObject = {};
  22145. serializationObject.emitterId = particleSystem.emitter.id;
  22146. serializationObject.capacity = particleSystem.getCapacity();
  22147. if (particleSystem.particleTexture) {
  22148. serializationObject.textureName = particleSystem.particleTexture.name;
  22149. }
  22150. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  22151. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  22152. serializationObject.minSize = particleSystem.minSize;
  22153. serializationObject.maxSize = particleSystem.maxSize;
  22154. serializationObject.minLifeTime = particleSystem.minLifeTime;
  22155. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  22156. serializationObject.emitRate = particleSystem.emitRate;
  22157. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  22158. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  22159. serializationObject.gravity = particleSystem.gravity.asArray();
  22160. serializationObject.direction1 = particleSystem.direction1.asArray();
  22161. serializationObject.direction2 = particleSystem.direction2.asArray();
  22162. serializationObject.color1 = particleSystem.color1.asArray();
  22163. serializationObject.color2 = particleSystem.color2.asArray();
  22164. serializationObject.colorDead = particleSystem.colorDead.asArray();
  22165. serializationObject.updateSpeed = particleSystem.updateSpeed;
  22166. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  22167. serializationObject.textureMask = particleSystem.textureMask.asArray();
  22168. serializationObject.blendMode = particleSystem.blendMode;
  22169. return serializationObject;
  22170. };
  22171. var serializeLensFlareSystem = function (lensFlareSystem) {
  22172. var serializationObject = {};
  22173. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  22174. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  22175. serializationObject.flares = [];
  22176. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  22177. var flare = lensFlareSystem.lensFlares[index];
  22178. serializationObject.flares.push({
  22179. size: flare.size,
  22180. position: flare.position,
  22181. color: flare.color.asArray(),
  22182. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  22183. });
  22184. }
  22185. return serializationObject;
  22186. };
  22187. var serializeShadowGenerator = function (light) {
  22188. var serializationObject = {};
  22189. var shadowGenerator = light.getShadowGenerator();
  22190. serializationObject.lightId = light.id;
  22191. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  22192. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  22193. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  22194. serializationObject.renderList = [];
  22195. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  22196. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  22197. serializationObject.renderList.push(mesh.id);
  22198. }
  22199. return serializationObject;
  22200. };
  22201. var serializedGeometries = [];
  22202. var serializeGeometry = function (geometry, serializationGeometries) {
  22203. if (serializedGeometries[geometry.id]) {
  22204. return;
  22205. }
  22206. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  22207. serializationGeometries.boxes.push(serializeBox(geometry));
  22208. }
  22209. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  22210. serializationGeometries.spheres.push(serializeSphere(geometry));
  22211. }
  22212. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  22213. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  22214. }
  22215. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  22216. serializationGeometries.toruses.push(serializeTorus(geometry));
  22217. }
  22218. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  22219. serializationGeometries.grounds.push(serializeGround(geometry));
  22220. }
  22221. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  22222. serializationGeometries.planes.push(serializePlane(geometry));
  22223. }
  22224. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  22225. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  22226. }
  22227. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  22228. throw new Error("Unknow primitive type");
  22229. }
  22230. else {
  22231. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  22232. }
  22233. serializedGeometries[geometry.id] = true;
  22234. };
  22235. var serializeGeometryBase = function (geometry) {
  22236. var serializationObject = {};
  22237. serializationObject.id = geometry.id;
  22238. if (BABYLON.Tags.HasTags(geometry)) {
  22239. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  22240. }
  22241. return serializationObject;
  22242. };
  22243. var serializeVertexData = function (vertexData) {
  22244. var serializationObject = serializeGeometryBase(vertexData);
  22245. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22246. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22247. }
  22248. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22249. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22250. }
  22251. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22252. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22253. }
  22254. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22255. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  22256. }
  22257. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22258. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  22259. }
  22260. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22261. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22262. serializationObject.matricesIndices._isExpanded = true;
  22263. }
  22264. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22265. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22266. }
  22267. serializationObject.indices = vertexData.getIndices();
  22268. return serializationObject;
  22269. };
  22270. var serializePrimitive = function (primitive) {
  22271. var serializationObject = serializeGeometryBase(primitive);
  22272. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  22273. return serializationObject;
  22274. };
  22275. var serializeBox = function (box) {
  22276. var serializationObject = serializePrimitive(box);
  22277. serializationObject.size = box.size;
  22278. return serializationObject;
  22279. };
  22280. var serializeSphere = function (sphere) {
  22281. var serializationObject = serializePrimitive(sphere);
  22282. serializationObject.segments = sphere.segments;
  22283. serializationObject.diameter = sphere.diameter;
  22284. return serializationObject;
  22285. };
  22286. var serializeCylinder = function (cylinder) {
  22287. var serializationObject = serializePrimitive(cylinder);
  22288. serializationObject.height = cylinder.height;
  22289. serializationObject.diameterTop = cylinder.diameterTop;
  22290. serializationObject.diameterBottom = cylinder.diameterBottom;
  22291. serializationObject.tessellation = cylinder.tessellation;
  22292. return serializationObject;
  22293. };
  22294. var serializeTorus = function (torus) {
  22295. var serializationObject = serializePrimitive(torus);
  22296. serializationObject.diameter = torus.diameter;
  22297. serializationObject.thickness = torus.thickness;
  22298. serializationObject.tessellation = torus.tessellation;
  22299. return serializationObject;
  22300. };
  22301. var serializeGround = function (ground) {
  22302. var serializationObject = serializePrimitive(ground);
  22303. serializationObject.width = ground.width;
  22304. serializationObject.height = ground.height;
  22305. serializationObject.subdivisions = ground.subdivisions;
  22306. return serializationObject;
  22307. };
  22308. var serializePlane = function (plane) {
  22309. var serializationObject = serializePrimitive(plane);
  22310. serializationObject.size = plane.size;
  22311. return serializationObject;
  22312. };
  22313. var serializeTorusKnot = function (torusKnot) {
  22314. var serializationObject = serializePrimitive(torusKnot);
  22315. serializationObject.radius = torusKnot.radius;
  22316. serializationObject.tube = torusKnot.tube;
  22317. serializationObject.radialSegments = torusKnot.radialSegments;
  22318. serializationObject.tubularSegments = torusKnot.tubularSegments;
  22319. serializationObject.p = torusKnot.p;
  22320. serializationObject.q = torusKnot.q;
  22321. return serializationObject;
  22322. };
  22323. var serializeMesh = function (mesh, serializationScene) {
  22324. var serializationObject = {};
  22325. serializationObject.name = mesh.name;
  22326. serializationObject.id = mesh.id;
  22327. if (BABYLON.Tags.HasTags(mesh)) {
  22328. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  22329. }
  22330. serializationObject.position = mesh.position.asArray();
  22331. if (mesh.rotationQuaternion) {
  22332. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  22333. }
  22334. else if (mesh.rotation) {
  22335. serializationObject.rotation = mesh.rotation.asArray();
  22336. }
  22337. serializationObject.scaling = mesh.scaling.asArray();
  22338. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  22339. serializationObject.isEnabled = mesh.isEnabled();
  22340. serializationObject.isVisible = mesh.isVisible;
  22341. serializationObject.infiniteDistance = mesh.infiniteDistance;
  22342. serializationObject.pickable = mesh.isPickable;
  22343. serializationObject.receiveShadows = mesh.receiveShadows;
  22344. serializationObject.billboardMode = mesh.billboardMode;
  22345. serializationObject.visibility = mesh.visibility;
  22346. serializationObject.checkCollisions = mesh.checkCollisions;
  22347. // Parent
  22348. if (mesh.parent) {
  22349. serializationObject.parentId = mesh.parent.id;
  22350. }
  22351. // Geometry
  22352. var geometry = mesh._geometry;
  22353. if (geometry) {
  22354. var geometryId = geometry.id;
  22355. serializationObject.geometryId = geometryId;
  22356. if (!mesh.getScene().getGeometryByID(geometryId)) {
  22357. // 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
  22358. serializeGeometry(geometry, serializationScene.geometries);
  22359. }
  22360. // SubMeshes
  22361. serializationObject.subMeshes = [];
  22362. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  22363. var subMesh = mesh.subMeshes[subIndex];
  22364. serializationObject.subMeshes.push({
  22365. materialIndex: subMesh.materialIndex,
  22366. verticesStart: subMesh.verticesStart,
  22367. verticesCount: subMesh.verticesCount,
  22368. indexStart: subMesh.indexStart,
  22369. indexCount: subMesh.indexCount
  22370. });
  22371. }
  22372. }
  22373. // Material
  22374. if (mesh.material) {
  22375. serializationObject.materialId = mesh.material.id;
  22376. }
  22377. else {
  22378. mesh.material = null;
  22379. }
  22380. // Skeleton
  22381. if (mesh.skeleton) {
  22382. serializationObject.skeletonId = mesh.skeleton.id;
  22383. }
  22384. // Physics
  22385. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  22386. serializationObject.physicsMass = mesh.getPhysicsMass();
  22387. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  22388. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  22389. switch (mesh.getPhysicsImpostor()) {
  22390. case BABYLON.PhysicsEngine.BoxImpostor:
  22391. serializationObject.physicsImpostor = 1;
  22392. break;
  22393. case BABYLON.PhysicsEngine.SphereImpostor:
  22394. serializationObject.physicsImpostor = 2;
  22395. break;
  22396. }
  22397. }
  22398. // Instances
  22399. serializationObject.instances = [];
  22400. for (var index = 0; index < mesh.instances.length; index++) {
  22401. var instance = mesh.instances[index];
  22402. var serializationInstance = {
  22403. name: instance.name,
  22404. position: instance.position,
  22405. rotation: instance.rotation,
  22406. rotationQuaternion: instance.rotationQuaternion,
  22407. scaling: instance.scaling
  22408. };
  22409. serializationObject.instances.push(serializationInstance);
  22410. // Animations
  22411. appendAnimations(instance, serializationInstance);
  22412. }
  22413. // Animations
  22414. appendAnimations(mesh, serializationObject);
  22415. // Layer mask
  22416. serializationObject.layerMask = mesh.layerMask;
  22417. return serializationObject;
  22418. };
  22419. var SceneSerializer = (function () {
  22420. function SceneSerializer() {
  22421. }
  22422. SceneSerializer.Serialize = function (scene) {
  22423. var serializationObject = {};
  22424. // Scene
  22425. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  22426. serializationObject.autoClear = scene.autoClear;
  22427. serializationObject.clearColor = scene.clearColor.asArray();
  22428. serializationObject.ambientColor = scene.ambientColor.asArray();
  22429. serializationObject.gravity = scene.gravity.asArray();
  22430. // Fog
  22431. if (scene.fogMode && scene.fogMode !== 0) {
  22432. serializationObject.fogMode = scene.fogMode;
  22433. serializationObject.fogColor = scene.fogColor.asArray();
  22434. serializationObject.fogStart = scene.fogStart;
  22435. serializationObject.fogEnd = scene.fogEnd;
  22436. serializationObject.fogDensity = scene.fogDensity;
  22437. }
  22438. // Lights
  22439. serializationObject.lights = [];
  22440. for (var index = 0; index < scene.lights.length; index++) {
  22441. var light = scene.lights[index];
  22442. serializationObject.lights.push(serializeLight(light));
  22443. }
  22444. // Cameras
  22445. serializationObject.cameras = [];
  22446. for (index = 0; index < scene.cameras.length; index++) {
  22447. var camera = scene.cameras[index];
  22448. serializationObject.cameras.push(serializeCamera(camera));
  22449. }
  22450. if (scene.activeCamera) {
  22451. serializationObject.activeCameraID = scene.activeCamera.id;
  22452. }
  22453. // Materials
  22454. serializationObject.materials = [];
  22455. serializationObject.multiMaterials = [];
  22456. for (index = 0; index < scene.materials.length; index++) {
  22457. var material = scene.materials[index];
  22458. if (material instanceof BABYLON.StandardMaterial) {
  22459. serializationObject.materials.push(serializeMaterial(material));
  22460. }
  22461. else if (material instanceof BABYLON.MultiMaterial) {
  22462. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  22463. }
  22464. }
  22465. // Skeletons
  22466. serializationObject.skeletons = [];
  22467. for (index = 0; index < scene.skeletons.length; index++) {
  22468. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  22469. }
  22470. // Geometries
  22471. serializationObject.geometries = {};
  22472. serializationObject.geometries.boxes = [];
  22473. serializationObject.geometries.spheres = [];
  22474. serializationObject.geometries.cylinders = [];
  22475. serializationObject.geometries.toruses = [];
  22476. serializationObject.geometries.grounds = [];
  22477. serializationObject.geometries.planes = [];
  22478. serializationObject.geometries.torusKnots = [];
  22479. serializationObject.geometries.vertexData = [];
  22480. serializedGeometries = [];
  22481. var geometries = scene.getGeometries();
  22482. for (index = 0; index < geometries.length; index++) {
  22483. var geometry = geometries[index];
  22484. if (geometry.isReady()) {
  22485. serializeGeometry(geometry, serializationObject.geometries);
  22486. }
  22487. }
  22488. // Meshes
  22489. serializationObject.meshes = [];
  22490. for (index = 0; index < scene.meshes.length; index++) {
  22491. var abstractMesh = scene.meshes[index];
  22492. if (abstractMesh instanceof BABYLON.Mesh) {
  22493. var mesh = abstractMesh;
  22494. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  22495. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  22496. }
  22497. }
  22498. }
  22499. // Particles Systems
  22500. serializationObject.particleSystems = [];
  22501. for (index = 0; index < scene.particleSystems.length; index++) {
  22502. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  22503. }
  22504. // Lens flares
  22505. serializationObject.lensFlareSystems = [];
  22506. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  22507. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  22508. }
  22509. // Shadows
  22510. serializationObject.shadowGenerators = [];
  22511. for (index = 0; index < scene.lights.length; index++) {
  22512. light = scene.lights[index];
  22513. if (light.getShadowGenerator()) {
  22514. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  22515. }
  22516. }
  22517. return serializationObject;
  22518. };
  22519. return SceneSerializer;
  22520. })();
  22521. BABYLON.SceneSerializer = SceneSerializer;
  22522. })(BABYLON || (BABYLON = {}));
  22523. //# sourceMappingURL=babylon.sceneSerializer.js.map
  22524. var BABYLON;
  22525. (function (BABYLON) {
  22526. // Unique ID when we import meshes from Babylon to CSG
  22527. var currentCSGMeshId = 0;
  22528. // # class Vertex
  22529. // Represents a vertex of a polygon. Use your own vertex class instead of this
  22530. // one to provide additional features like texture coordinates and vertex
  22531. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  22532. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  22533. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  22534. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  22535. // is not used anywhere else.
  22536. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  22537. var Vertex = (function () {
  22538. function Vertex(pos, normal, uv) {
  22539. this.pos = pos;
  22540. this.normal = normal;
  22541. this.uv = uv;
  22542. }
  22543. Vertex.prototype.clone = function () {
  22544. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  22545. };
  22546. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  22547. // orientation of a polygon is flipped.
  22548. Vertex.prototype.flip = function () {
  22549. this.normal = this.normal.scale(-1);
  22550. };
  22551. // Create a new vertex between this vertex and `other` by linearly
  22552. // interpolating all properties using a parameter of `t`. Subclasses should
  22553. // override this to interpolate additional properties.
  22554. Vertex.prototype.interpolate = function (other, t) {
  22555. 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));
  22556. };
  22557. return Vertex;
  22558. })();
  22559. // # class Plane
  22560. // Represents a plane in 3D space.
  22561. var Plane = (function () {
  22562. function Plane(normal, w) {
  22563. this.normal = normal;
  22564. this.w = w;
  22565. }
  22566. Plane.FromPoints = function (a, b, c) {
  22567. var v0 = c.subtract(a);
  22568. var v1 = b.subtract(a);
  22569. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  22570. return null;
  22571. }
  22572. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  22573. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  22574. };
  22575. Plane.prototype.clone = function () {
  22576. return new Plane(this.normal.clone(), this.w);
  22577. };
  22578. Plane.prototype.flip = function () {
  22579. this.normal.scaleInPlace(-1);
  22580. this.w = -this.w;
  22581. };
  22582. // Split `polygon` by this plane if needed, then put the polygon or polygon
  22583. // fragments in the appropriate lists. Coplanar polygons go into either
  22584. // `coplanarFront` or `coplanarBack` depending on their orientation with
  22585. // respect to this plane. Polygons in front or in back of this plane go into
  22586. // either `front` or `back`.
  22587. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  22588. var COPLANAR = 0;
  22589. var FRONT = 1;
  22590. var BACK = 2;
  22591. var SPANNING = 3;
  22592. // Classify each point as well as the entire polygon into one of the above
  22593. // four classes.
  22594. var polygonType = 0;
  22595. var types = [];
  22596. for (var i = 0; i < polygon.vertices.length; i++) {
  22597. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  22598. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  22599. polygonType |= type;
  22600. types.push(type);
  22601. }
  22602. switch (polygonType) {
  22603. case COPLANAR:
  22604. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  22605. break;
  22606. case FRONT:
  22607. front.push(polygon);
  22608. break;
  22609. case BACK:
  22610. back.push(polygon);
  22611. break;
  22612. case SPANNING:
  22613. var f = [], b = [];
  22614. for (i = 0; i < polygon.vertices.length; i++) {
  22615. var j = (i + 1) % polygon.vertices.length;
  22616. var ti = types[i], tj = types[j];
  22617. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  22618. if (ti != BACK)
  22619. f.push(vi);
  22620. if (ti != FRONT)
  22621. b.push(ti != BACK ? vi.clone() : vi);
  22622. if ((ti | tj) == SPANNING) {
  22623. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  22624. var v = vi.interpolate(vj, t);
  22625. f.push(v);
  22626. b.push(v.clone());
  22627. }
  22628. }
  22629. if (f.length >= 3) {
  22630. var poly = new Polygon(f, polygon.shared);
  22631. if (poly.plane)
  22632. front.push(poly);
  22633. }
  22634. if (b.length >= 3) {
  22635. poly = new Polygon(b, polygon.shared);
  22636. if (poly.plane)
  22637. back.push(poly);
  22638. }
  22639. break;
  22640. }
  22641. };
  22642. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  22643. // point is on the plane.
  22644. Plane.EPSILON = 1e-5;
  22645. return Plane;
  22646. })();
  22647. // # class Polygon
  22648. // Represents a convex polygon. The vertices used to initialize a polygon must
  22649. // be coplanar and form a convex loop.
  22650. //
  22651. // Each convex polygon has a `shared` property, which is shared between all
  22652. // polygons that are clones of each other or were split from the same polygon.
  22653. // This can be used to define per-polygon properties (such as surface color).
  22654. var Polygon = (function () {
  22655. function Polygon(vertices, shared) {
  22656. this.vertices = vertices;
  22657. this.shared = shared;
  22658. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  22659. }
  22660. Polygon.prototype.clone = function () {
  22661. var vertices = this.vertices.map(function (v) { return v.clone(); });
  22662. return new Polygon(vertices, this.shared);
  22663. };
  22664. Polygon.prototype.flip = function () {
  22665. this.vertices.reverse().map(function (v) {
  22666. v.flip();
  22667. });
  22668. this.plane.flip();
  22669. };
  22670. return Polygon;
  22671. })();
  22672. // # class Node
  22673. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  22674. // by picking a polygon to split along. That polygon (and all other coplanar
  22675. // polygons) are added directly to that node and the other polygons are added to
  22676. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  22677. // no distinction between internal and leaf nodes.
  22678. var Node = (function () {
  22679. function Node(polygons) {
  22680. this.plane = null;
  22681. this.front = null;
  22682. this.back = null;
  22683. this.polygons = [];
  22684. if (polygons) {
  22685. this.build(polygons);
  22686. }
  22687. }
  22688. Node.prototype.clone = function () {
  22689. var node = new Node();
  22690. node.plane = this.plane && this.plane.clone();
  22691. node.front = this.front && this.front.clone();
  22692. node.back = this.back && this.back.clone();
  22693. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  22694. return node;
  22695. };
  22696. // Convert solid space to empty space and empty space to solid space.
  22697. Node.prototype.invert = function () {
  22698. for (var i = 0; i < this.polygons.length; i++) {
  22699. this.polygons[i].flip();
  22700. }
  22701. if (this.plane) {
  22702. this.plane.flip();
  22703. }
  22704. if (this.front) {
  22705. this.front.invert();
  22706. }
  22707. if (this.back) {
  22708. this.back.invert();
  22709. }
  22710. var temp = this.front;
  22711. this.front = this.back;
  22712. this.back = temp;
  22713. };
  22714. // Recursively remove all polygons in `polygons` that are inside this BSP
  22715. // tree.
  22716. Node.prototype.clipPolygons = function (polygons) {
  22717. if (!this.plane)
  22718. return polygons.slice();
  22719. var front = [], back = [];
  22720. for (var i = 0; i < polygons.length; i++) {
  22721. this.plane.splitPolygon(polygons[i], front, back, front, back);
  22722. }
  22723. if (this.front) {
  22724. front = this.front.clipPolygons(front);
  22725. }
  22726. if (this.back) {
  22727. back = this.back.clipPolygons(back);
  22728. }
  22729. else {
  22730. back = [];
  22731. }
  22732. return front.concat(back);
  22733. };
  22734. // Remove all polygons in this BSP tree that are inside the other BSP tree
  22735. // `bsp`.
  22736. Node.prototype.clipTo = function (bsp) {
  22737. this.polygons = bsp.clipPolygons(this.polygons);
  22738. if (this.front)
  22739. this.front.clipTo(bsp);
  22740. if (this.back)
  22741. this.back.clipTo(bsp);
  22742. };
  22743. // Return a list of all polygons in this BSP tree.
  22744. Node.prototype.allPolygons = function () {
  22745. var polygons = this.polygons.slice();
  22746. if (this.front)
  22747. polygons = polygons.concat(this.front.allPolygons());
  22748. if (this.back)
  22749. polygons = polygons.concat(this.back.allPolygons());
  22750. return polygons;
  22751. };
  22752. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  22753. // new polygons are filtered down to the bottom of the tree and become new
  22754. // nodes there. Each set of polygons is partitioned using the first polygon
  22755. // (no heuristic is used to pick a good split).
  22756. Node.prototype.build = function (polygons) {
  22757. if (!polygons.length)
  22758. return;
  22759. if (!this.plane)
  22760. this.plane = polygons[0].plane.clone();
  22761. var front = [], back = [];
  22762. for (var i = 0; i < polygons.length; i++) {
  22763. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  22764. }
  22765. if (front.length) {
  22766. if (!this.front)
  22767. this.front = new Node();
  22768. this.front.build(front);
  22769. }
  22770. if (back.length) {
  22771. if (!this.back)
  22772. this.back = new Node();
  22773. this.back.build(back);
  22774. }
  22775. };
  22776. return Node;
  22777. })();
  22778. var CSG = (function () {
  22779. function CSG() {
  22780. this.polygons = new Array();
  22781. }
  22782. // Convert BABYLON.Mesh to BABYLON.CSG
  22783. CSG.FromMesh = function (mesh) {
  22784. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  22785. if (mesh instanceof BABYLON.Mesh) {
  22786. mesh.computeWorldMatrix(true);
  22787. var matrix = mesh.getWorldMatrix();
  22788. var meshPosition = mesh.position.clone();
  22789. var meshRotation = mesh.rotation.clone();
  22790. var meshScaling = mesh.scaling.clone();
  22791. }
  22792. else {
  22793. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  22794. }
  22795. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22796. var subMeshes = mesh.subMeshes;
  22797. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  22798. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  22799. vertices = [];
  22800. for (var j = 0; j < 3; j++) {
  22801. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  22802. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  22803. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  22804. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  22805. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  22806. vertex = new Vertex(position, normal, uv);
  22807. vertices.push(vertex);
  22808. }
  22809. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  22810. // To handle the case of degenerated triangle
  22811. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  22812. if (polygon.plane)
  22813. polygons.push(polygon);
  22814. }
  22815. }
  22816. var csg = CSG.FromPolygons(polygons);
  22817. csg.matrix = matrix;
  22818. csg.position = meshPosition;
  22819. csg.rotation = meshRotation;
  22820. csg.scaling = meshScaling;
  22821. currentCSGMeshId++;
  22822. return csg;
  22823. };
  22824. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  22825. CSG.FromPolygons = function (polygons) {
  22826. var csg = new BABYLON.CSG();
  22827. csg.polygons = polygons;
  22828. return csg;
  22829. };
  22830. CSG.prototype.clone = function () {
  22831. var csg = new BABYLON.CSG();
  22832. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  22833. csg.copyTransformAttributes(this);
  22834. return csg;
  22835. };
  22836. CSG.prototype.toPolygons = function () {
  22837. return this.polygons;
  22838. };
  22839. CSG.prototype.union = function (csg) {
  22840. var a = new Node(this.clone().polygons);
  22841. var b = new Node(csg.clone().polygons);
  22842. a.clipTo(b);
  22843. b.clipTo(a);
  22844. b.invert();
  22845. b.clipTo(a);
  22846. b.invert();
  22847. a.build(b.allPolygons());
  22848. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  22849. };
  22850. CSG.prototype.unionInPlace = function (csg) {
  22851. var a = new Node(this.polygons);
  22852. var b = new Node(csg.polygons);
  22853. a.clipTo(b);
  22854. b.clipTo(a);
  22855. b.invert();
  22856. b.clipTo(a);
  22857. b.invert();
  22858. a.build(b.allPolygons());
  22859. this.polygons = a.allPolygons();
  22860. };
  22861. CSG.prototype.subtract = function (csg) {
  22862. var a = new Node(this.clone().polygons);
  22863. var b = new Node(csg.clone().polygons);
  22864. a.invert();
  22865. a.clipTo(b);
  22866. b.clipTo(a);
  22867. b.invert();
  22868. b.clipTo(a);
  22869. b.invert();
  22870. a.build(b.allPolygons());
  22871. a.invert();
  22872. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  22873. };
  22874. CSG.prototype.subtractInPlace = function (csg) {
  22875. var a = new Node(this.polygons);
  22876. var b = new Node(csg.polygons);
  22877. a.invert();
  22878. a.clipTo(b);
  22879. b.clipTo(a);
  22880. b.invert();
  22881. b.clipTo(a);
  22882. b.invert();
  22883. a.build(b.allPolygons());
  22884. a.invert();
  22885. this.polygons = a.allPolygons();
  22886. };
  22887. CSG.prototype.intersect = function (csg) {
  22888. var a = new Node(this.clone().polygons);
  22889. var b = new Node(csg.clone().polygons);
  22890. a.invert();
  22891. b.clipTo(a);
  22892. b.invert();
  22893. a.clipTo(b);
  22894. b.clipTo(a);
  22895. a.build(b.allPolygons());
  22896. a.invert();
  22897. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  22898. };
  22899. CSG.prototype.intersectInPlace = function (csg) {
  22900. var a = new Node(this.polygons);
  22901. var b = new Node(csg.polygons);
  22902. a.invert();
  22903. b.clipTo(a);
  22904. b.invert();
  22905. a.clipTo(b);
  22906. b.clipTo(a);
  22907. a.build(b.allPolygons());
  22908. a.invert();
  22909. this.polygons = a.allPolygons();
  22910. };
  22911. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  22912. // not modified.
  22913. CSG.prototype.inverse = function () {
  22914. var csg = this.clone();
  22915. csg.inverseInPlace();
  22916. return csg;
  22917. };
  22918. CSG.prototype.inverseInPlace = function () {
  22919. this.polygons.map(function (p) {
  22920. p.flip();
  22921. });
  22922. };
  22923. // This is used to keep meshes transformations so they can be restored
  22924. // when we build back a Babylon Mesh
  22925. // NB : All CSG operations are performed in world coordinates
  22926. CSG.prototype.copyTransformAttributes = function (csg) {
  22927. this.matrix = csg.matrix;
  22928. this.position = csg.position;
  22929. this.rotation = csg.rotation;
  22930. this.scaling = csg.scaling;
  22931. return this;
  22932. };
  22933. // Build Raw mesh from CSG
  22934. // Coordinates here are in world space
  22935. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  22936. var matrix = this.matrix.clone();
  22937. matrix.invert();
  22938. 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;
  22939. if (keepSubMeshes) {
  22940. // Sort Polygons, since subMeshes are indices range
  22941. polygons.sort(function (a, b) {
  22942. if (a.shared.meshId === b.shared.meshId) {
  22943. return a.shared.subMeshId - b.shared.subMeshId;
  22944. }
  22945. else {
  22946. return a.shared.meshId - b.shared.meshId;
  22947. }
  22948. });
  22949. }
  22950. for (var i = 0, il = polygons.length; i < il; i++) {
  22951. polygon = polygons[i];
  22952. // Building SubMeshes
  22953. if (!subMesh_dict[polygon.shared.meshId]) {
  22954. subMesh_dict[polygon.shared.meshId] = {};
  22955. }
  22956. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  22957. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  22958. indexStart: +Infinity,
  22959. indexEnd: -Infinity,
  22960. materialIndex: polygon.shared.materialIndex
  22961. };
  22962. }
  22963. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  22964. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  22965. polygonIndices[0] = 0;
  22966. polygonIndices[1] = j - 1;
  22967. polygonIndices[2] = j;
  22968. for (var k = 0; k < 3; k++) {
  22969. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  22970. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  22971. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  22972. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  22973. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  22974. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  22975. // Check if 2 points can be merged
  22976. 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)) {
  22977. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  22978. uvs.push(uv.x, uv.y);
  22979. normals.push(normal.x, normal.y, normal.z);
  22980. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  22981. }
  22982. indices.push(vertex_idx);
  22983. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  22984. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  22985. currentIndex++;
  22986. }
  22987. }
  22988. }
  22989. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  22990. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22991. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  22992. mesh.setIndices(indices);
  22993. if (keepSubMeshes) {
  22994. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  22995. var materialIndexOffset = 0, materialMaxIndex;
  22996. mesh.subMeshes.length = 0;
  22997. for (var m in subMesh_dict) {
  22998. materialMaxIndex = -1;
  22999. for (var sm in subMesh_dict[m]) {
  23000. subMesh_obj = subMesh_dict[m][sm];
  23001. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  23002. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  23003. }
  23004. materialIndexOffset += ++materialMaxIndex;
  23005. }
  23006. }
  23007. return mesh;
  23008. };
  23009. // Build Mesh from CSG taking material and transforms into account
  23010. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  23011. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  23012. mesh.material = material;
  23013. mesh.position.copyFrom(this.position);
  23014. mesh.rotation.copyFrom(this.rotation);
  23015. mesh.scaling.copyFrom(this.scaling);
  23016. mesh.computeWorldMatrix(true);
  23017. return mesh;
  23018. };
  23019. return CSG;
  23020. })();
  23021. BABYLON.CSG = CSG;
  23022. })(BABYLON || (BABYLON = {}));
  23023. //# sourceMappingURL=babylon.csg.js.map
  23024. var __extends = this.__extends || function (d, b) {
  23025. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23026. function __() { this.constructor = d; }
  23027. __.prototype = b.prototype;
  23028. d.prototype = new __();
  23029. };
  23030. var BABYLON;
  23031. (function (BABYLON) {
  23032. var OculusDistortionCorrectionPostProcess = (function (_super) {
  23033. __extends(OculusDistortionCorrectionPostProcess, _super);
  23034. //ANY
  23035. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  23036. var _this = this;
  23037. _super.call(this, name, "oculusDistortionCorrection", [
  23038. 'LensCenter',
  23039. 'Scale',
  23040. 'ScaleIn',
  23041. 'HmdWarpParam'
  23042. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  23043. this._isRightEye = isRightEye;
  23044. this._distortionFactors = cameraSettings.DistortionK;
  23045. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  23046. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  23047. this.onSizeChanged = function () {
  23048. _this.aspectRatio = _this.width * .5 / _this.height;
  23049. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  23050. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  23051. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  23052. };
  23053. this.onApply = function (effect) {
  23054. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  23055. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  23056. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  23057. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  23058. };
  23059. }
  23060. return OculusDistortionCorrectionPostProcess;
  23061. })(BABYLON.PostProcess);
  23062. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  23063. })(BABYLON || (BABYLON = {}));
  23064. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map
  23065. // Mainly based on these 2 articles :
  23066. // 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
  23067. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  23068. var BABYLON;
  23069. (function (BABYLON) {
  23070. (function (JoystickAxis) {
  23071. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  23072. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  23073. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  23074. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  23075. var JoystickAxis = BABYLON.JoystickAxis;
  23076. var VirtualJoystick = (function () {
  23077. function VirtualJoystick(leftJoystick) {
  23078. var _this = this;
  23079. if (leftJoystick) {
  23080. this._leftJoystick = true;
  23081. }
  23082. else {
  23083. this._leftJoystick = false;
  23084. }
  23085. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  23086. VirtualJoystick._globalJoystickIndex++;
  23087. // By default left & right arrow keys are moving the X
  23088. // and up & down keys are moving the Y
  23089. this._axisTargetedByLeftAndRight = 0 /* X */;
  23090. this._axisTargetedByUpAndDown = 1 /* Y */;
  23091. this.reverseLeftRight = false;
  23092. this.reverseUpDown = false;
  23093. // collections of pointers
  23094. this._touches = new BABYLON.SmartCollection();
  23095. this.deltaPosition = BABYLON.Vector3.Zero();
  23096. this._joystickSensibility = 25;
  23097. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  23098. this._rotationSpeed = 25;
  23099. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  23100. this._rotateOnAxisRelativeToMesh = false;
  23101. // injecting a canvas element on top of the canvas 3D game
  23102. if (!VirtualJoystick.vjCanvas) {
  23103. window.addEventListener("resize", function () {
  23104. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  23105. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  23106. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  23107. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  23108. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  23109. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  23110. }, false);
  23111. VirtualJoystick.vjCanvas = document.createElement("canvas");
  23112. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  23113. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  23114. VirtualJoystick.vjCanvas.width = window.innerWidth;
  23115. VirtualJoystick.vjCanvas.height = window.innerHeight;
  23116. VirtualJoystick.vjCanvas.style.width = "100%";
  23117. VirtualJoystick.vjCanvas.style.height = "100%";
  23118. VirtualJoystick.vjCanvas.style.position = "absolute";
  23119. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  23120. VirtualJoystick.vjCanvas.style.top = "0px";
  23121. VirtualJoystick.vjCanvas.style.left = "0px";
  23122. VirtualJoystick.vjCanvas.style.zIndex = "5";
  23123. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  23124. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  23125. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  23126. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  23127. document.body.appendChild(VirtualJoystick.vjCanvas);
  23128. }
  23129. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  23130. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  23131. this.pressed = false;
  23132. // default joystick color
  23133. this._joystickColor = "cyan";
  23134. this._joystickPointerID = -1;
  23135. // current joystick position
  23136. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  23137. // origin joystick position
  23138. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  23139. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  23140. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  23141. _this._onPointerDown(evt);
  23142. }, false);
  23143. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  23144. _this._onPointerMove(evt);
  23145. }, false);
  23146. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  23147. _this._onPointerUp(evt);
  23148. }, false);
  23149. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  23150. _this._onPointerUp(evt);
  23151. }, false);
  23152. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  23153. evt.preventDefault(); // Disables system menu
  23154. }, false);
  23155. requestAnimationFrame(function () {
  23156. _this._drawVirtualJoystick();
  23157. });
  23158. }
  23159. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  23160. this._joystickSensibility = newJoystickSensibility;
  23161. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  23162. };
  23163. VirtualJoystick.prototype._onPointerDown = function (e) {
  23164. var positionOnScreenCondition;
  23165. e.preventDefault();
  23166. if (this._leftJoystick === true) {
  23167. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  23168. }
  23169. else {
  23170. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  23171. }
  23172. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  23173. // First contact will be dedicated to the virtual joystick
  23174. this._joystickPointerID = e.pointerId;
  23175. this._joystickPointerStartPos.x = e.clientX;
  23176. this._joystickPointerStartPos.y = e.clientY;
  23177. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  23178. this._deltaJoystickVector.x = 0;
  23179. this._deltaJoystickVector.y = 0;
  23180. this.pressed = true;
  23181. this._touches.add(e.pointerId.toString(), e);
  23182. }
  23183. else {
  23184. // You can only trigger the action buttons with a joystick declared
  23185. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  23186. this._action();
  23187. this._touches.add(e.pointerId.toString(), e);
  23188. }
  23189. }
  23190. };
  23191. VirtualJoystick.prototype._onPointerMove = function (e) {
  23192. // If the current pointer is the one associated to the joystick (first touch contact)
  23193. if (this._joystickPointerID == e.pointerId) {
  23194. this._joystickPointerPos.x = e.clientX;
  23195. this._joystickPointerPos.y = e.clientY;
  23196. this._deltaJoystickVector = this._joystickPointerPos.clone();
  23197. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  23198. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  23199. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  23200. switch (this._axisTargetedByLeftAndRight) {
  23201. case 0 /* X */:
  23202. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  23203. break;
  23204. case 1 /* Y */:
  23205. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  23206. break;
  23207. case 2 /* Z */:
  23208. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  23209. break;
  23210. }
  23211. var directionUpDown = this.reverseUpDown ? 1 : -1;
  23212. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  23213. switch (this._axisTargetedByUpAndDown) {
  23214. case 0 /* X */:
  23215. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  23216. break;
  23217. case 1 /* Y */:
  23218. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  23219. break;
  23220. case 2 /* Z */:
  23221. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  23222. break;
  23223. }
  23224. }
  23225. else {
  23226. if (this._touches.item(e.pointerId.toString())) {
  23227. this._touches.item(e.pointerId.toString()).x = e.clientX;
  23228. this._touches.item(e.pointerId.toString()).y = e.clientY;
  23229. }
  23230. }
  23231. };
  23232. VirtualJoystick.prototype._onPointerUp = function (e) {
  23233. this._clearCanvas();
  23234. if (this._joystickPointerID == e.pointerId) {
  23235. this._joystickPointerID = -1;
  23236. this.pressed = false;
  23237. }
  23238. this._deltaJoystickVector.x = 0;
  23239. this._deltaJoystickVector.y = 0;
  23240. this._touches.remove(e.pointerId.toString());
  23241. };
  23242. /**
  23243. * Change the color of the virtual joystick
  23244. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  23245. */
  23246. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  23247. this._joystickColor = newColor;
  23248. };
  23249. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  23250. this._action = action;
  23251. };
  23252. // Define which axis you'd like to control for left & right
  23253. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  23254. switch (axis) {
  23255. case 0 /* X */:
  23256. case 1 /* Y */:
  23257. case 2 /* Z */:
  23258. this._axisTargetedByLeftAndRight = axis;
  23259. break;
  23260. default:
  23261. this._axisTargetedByLeftAndRight = 0 /* X */;
  23262. break;
  23263. }
  23264. };
  23265. // Define which axis you'd like to control for up & down
  23266. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  23267. switch (axis) {
  23268. case 0 /* X */:
  23269. case 1 /* Y */:
  23270. case 2 /* Z */:
  23271. this._axisTargetedByUpAndDown = axis;
  23272. break;
  23273. default:
  23274. this._axisTargetedByUpAndDown = 1 /* Y */;
  23275. break;
  23276. }
  23277. };
  23278. VirtualJoystick.prototype._clearCanvas = function () {
  23279. if (this._leftJoystick) {
  23280. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  23281. }
  23282. else {
  23283. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  23284. }
  23285. };
  23286. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  23287. var _this = this;
  23288. if (this.pressed) {
  23289. this._clearCanvas();
  23290. this._touches.forEach(function (touch) {
  23291. if (touch.pointerId === _this._joystickPointerID) {
  23292. VirtualJoystick.vjCanvasContext.beginPath();
  23293. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  23294. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  23295. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  23296. VirtualJoystick.vjCanvasContext.stroke();
  23297. VirtualJoystick.vjCanvasContext.beginPath();
  23298. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  23299. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  23300. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  23301. VirtualJoystick.vjCanvasContext.stroke();
  23302. VirtualJoystick.vjCanvasContext.beginPath();
  23303. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  23304. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  23305. VirtualJoystick.vjCanvasContext.stroke();
  23306. }
  23307. else {
  23308. VirtualJoystick.vjCanvasContext.beginPath();
  23309. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  23310. VirtualJoystick.vjCanvasContext.beginPath();
  23311. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  23312. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  23313. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  23314. VirtualJoystick.vjCanvasContext.stroke();
  23315. }
  23316. ;
  23317. });
  23318. }
  23319. requestAnimationFrame(function () {
  23320. _this._drawVirtualJoystick();
  23321. });
  23322. };
  23323. VirtualJoystick.prototype.releaseCanvas = function () {
  23324. if (VirtualJoystick.vjCanvas) {
  23325. document.body.removeChild(VirtualJoystick.vjCanvas);
  23326. VirtualJoystick.vjCanvas = null;
  23327. }
  23328. };
  23329. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  23330. VirtualJoystick._globalJoystickIndex = 0;
  23331. return VirtualJoystick;
  23332. })();
  23333. BABYLON.VirtualJoystick = VirtualJoystick;
  23334. })(BABYLON || (BABYLON = {}));
  23335. //# sourceMappingURL=babylon.virtualJoystick.js.map
  23336. var __extends = this.__extends || function (d, b) {
  23337. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23338. function __() { this.constructor = d; }
  23339. __.prototype = b.prototype;
  23340. d.prototype = new __();
  23341. };
  23342. var BABYLON;
  23343. (function (BABYLON) {
  23344. var OculusRiftDevKit2013_Metric = {
  23345. HResolution: 1280,
  23346. VResolution: 800,
  23347. HScreenSize: 0.149759993,
  23348. VScreenSize: 0.0935999975,
  23349. VScreenCenter: 0.0467999987,
  23350. EyeToScreenDistance: 0.0410000011,
  23351. LensSeparationDistance: 0.0635000020,
  23352. InterpupillaryDistance: 0.0640000030,
  23353. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  23354. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  23355. PostProcessScaleFactor: 1.714605507808412,
  23356. LensCenterOffset: 0.151976421
  23357. };
  23358. var _OculusInnerCamera = (function (_super) {
  23359. __extends(_OculusInnerCamera, _super);
  23360. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  23361. _super.call(this, name, position, scene);
  23362. this._workMatrix = new BABYLON.Matrix();
  23363. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  23364. // Constants
  23365. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  23366. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  23367. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  23368. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  23369. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  23370. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  23371. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  23372. // Postprocess
  23373. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  23374. }
  23375. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  23376. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  23377. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  23378. return this._projectionMatrix;
  23379. };
  23380. _OculusInnerCamera.prototype._getViewMatrix = function () {
  23381. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  23382. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  23383. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  23384. // Computing target and final matrix
  23385. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  23386. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  23387. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  23388. return this._viewMatrix;
  23389. };
  23390. return _OculusInnerCamera;
  23391. })(BABYLON.FreeCamera);
  23392. var OculusCamera = (function (_super) {
  23393. __extends(OculusCamera, _super);
  23394. function OculusCamera(name, position, scene) {
  23395. _super.call(this, name, position, scene);
  23396. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  23397. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  23398. this.subCameras.push(this._leftCamera);
  23399. this.subCameras.push(this._rightCamera);
  23400. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  23401. }
  23402. OculusCamera.prototype._update = function () {
  23403. this._leftCamera.position.copyFrom(this.position);
  23404. this._rightCamera.position.copyFrom(this.position);
  23405. this._updateCamera(this._leftCamera);
  23406. this._updateCamera(this._rightCamera);
  23407. _super.prototype._update.call(this);
  23408. };
  23409. OculusCamera.prototype._updateCamera = function (camera) {
  23410. camera.minZ = this.minZ;
  23411. camera.maxZ = this.maxZ;
  23412. camera.rotation.x = this.rotation.x;
  23413. camera.rotation.y = this.rotation.y;
  23414. camera.rotation.z = this.rotation.z;
  23415. };
  23416. // Oculus events
  23417. OculusCamera.prototype._onOrientationEvent = function (evt) {
  23418. var yaw = evt.alpha / 180 * Math.PI;
  23419. var pitch = evt.beta / 180 * Math.PI;
  23420. var roll = evt.gamma / 180 * Math.PI;
  23421. if (!this._offsetOrientation) {
  23422. this._offsetOrientation = {
  23423. yaw: yaw,
  23424. pitch: pitch,
  23425. roll: roll
  23426. };
  23427. return;
  23428. }
  23429. else {
  23430. this.rotation.y += yaw - this._offsetOrientation.yaw;
  23431. this.rotation.x += pitch - this._offsetOrientation.pitch;
  23432. this.rotation.z += this._offsetOrientation.roll - roll;
  23433. this._offsetOrientation.yaw = yaw;
  23434. this._offsetOrientation.pitch = pitch;
  23435. this._offsetOrientation.roll = roll;
  23436. }
  23437. };
  23438. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  23439. _super.prototype.attachControl.call(this, element, noPreventDefault);
  23440. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  23441. };
  23442. OculusCamera.prototype.detachControl = function (element) {
  23443. _super.prototype.detachControl.call(this, element);
  23444. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  23445. };
  23446. return OculusCamera;
  23447. })(BABYLON.FreeCamera);
  23448. BABYLON.OculusCamera = OculusCamera;
  23449. })(BABYLON || (BABYLON = {}));
  23450. //# sourceMappingURL=babylon.oculusCamera.js.map
  23451. var __extends = this.__extends || function (d, b) {
  23452. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23453. function __() { this.constructor = d; }
  23454. __.prototype = b.prototype;
  23455. d.prototype = new __();
  23456. };
  23457. var BABYLON;
  23458. (function (BABYLON) {
  23459. var OculusRiftDevKit2013_Metric = {
  23460. HResolution: 1280,
  23461. VResolution: 800,
  23462. HScreenSize: 0.149759993,
  23463. VScreenSize: 0.0935999975,
  23464. VScreenCenter: 0.0467999987,
  23465. EyeToScreenDistance: 0.0410000011,
  23466. LensSeparationDistance: 0.0635000020,
  23467. InterpupillaryDistance: 0.0640000030,
  23468. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  23469. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  23470. PostProcessScaleFactor: 1.714605507808412,
  23471. LensCenterOffset: 0.151976421
  23472. };
  23473. var _OculusInnerGamepadCamera = (function (_super) {
  23474. __extends(_OculusInnerGamepadCamera, _super);
  23475. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  23476. _super.call(this, name, position, scene);
  23477. this._workMatrix = new BABYLON.Matrix();
  23478. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  23479. // Constants
  23480. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  23481. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  23482. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  23483. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  23484. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  23485. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  23486. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  23487. // Postprocess
  23488. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  23489. }
  23490. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  23491. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  23492. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  23493. return this._projectionMatrix;
  23494. };
  23495. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  23496. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  23497. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  23498. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  23499. // Computing target and final matrix
  23500. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  23501. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  23502. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  23503. return this._viewMatrix;
  23504. };
  23505. return _OculusInnerGamepadCamera;
  23506. })(BABYLON.FreeCamera);
  23507. var OculusGamepadCamera = (function (_super) {
  23508. __extends(OculusGamepadCamera, _super);
  23509. function OculusGamepadCamera(name, position, scene) {
  23510. var _this = this;
  23511. _super.call(this, name, position, scene);
  23512. this.angularSensibility = 200;
  23513. this.moveSensibility = 75;
  23514. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  23515. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  23516. this.subCameras.push(this._leftCamera);
  23517. this.subCameras.push(this._rightCamera);
  23518. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  23519. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  23520. _this._onNewGameConnected(gamepad);
  23521. });
  23522. }
  23523. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  23524. // Only the first gamepad can control the camera
  23525. if (gamepad.index === 0) {
  23526. this._gamepad = gamepad;
  23527. }
  23528. };
  23529. OculusGamepadCamera.prototype._update = function () {
  23530. this._leftCamera.position.copyFrom(this.position);
  23531. this._rightCamera.position.copyFrom(this.position);
  23532. this._updateCamera(this._leftCamera);
  23533. this._updateCamera(this._rightCamera);
  23534. _super.prototype._update.call(this);
  23535. };
  23536. OculusGamepadCamera.prototype._checkInputs = function () {
  23537. if (!this._gamepad) {
  23538. return;
  23539. }
  23540. var LSValues = this._gamepad.leftStick;
  23541. var normalizedLX = LSValues.x / this.moveSensibility;
  23542. var normalizedLY = LSValues.y / this.moveSensibility;
  23543. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  23544. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  23545. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23546. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  23547. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23548. };
  23549. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  23550. camera.minZ = this.minZ;
  23551. camera.maxZ = this.maxZ;
  23552. camera.rotation.x = this.rotation.x;
  23553. camera.rotation.y = this.rotation.y;
  23554. camera.rotation.z = this.rotation.z;
  23555. };
  23556. // Oculus events
  23557. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  23558. var yaw = evt.alpha / 180 * Math.PI;
  23559. var pitch = evt.beta / 180 * Math.PI;
  23560. var roll = evt.gamma / 180 * Math.PI;
  23561. if (!this._offsetOrientation) {
  23562. this._offsetOrientation = {
  23563. yaw: yaw,
  23564. pitch: pitch,
  23565. roll: roll
  23566. };
  23567. return;
  23568. }
  23569. else {
  23570. this.rotation.y += yaw - this._offsetOrientation.yaw;
  23571. this.rotation.x += pitch - this._offsetOrientation.pitch;
  23572. this.rotation.z += this._offsetOrientation.roll - roll;
  23573. this._offsetOrientation.yaw = yaw;
  23574. this._offsetOrientation.pitch = pitch;
  23575. this._offsetOrientation.roll = roll;
  23576. }
  23577. };
  23578. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  23579. _super.prototype.attachControl.call(this, element, noPreventDefault);
  23580. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  23581. };
  23582. OculusGamepadCamera.prototype.detachControl = function (element) {
  23583. _super.prototype.detachControl.call(this, element);
  23584. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  23585. };
  23586. OculusGamepadCamera.prototype.dispose = function () {
  23587. this._gamepads.dispose();
  23588. _super.prototype.dispose.call(this);
  23589. };
  23590. return OculusGamepadCamera;
  23591. })(BABYLON.FreeCamera);
  23592. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  23593. })(BABYLON || (BABYLON = {}));
  23594. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  23595. var __extends = this.__extends || function (d, b) {
  23596. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23597. function __() { this.constructor = d; }
  23598. __.prototype = b.prototype;
  23599. d.prototype = new __();
  23600. };
  23601. var BABYLON;
  23602. (function (BABYLON) {
  23603. // We're mainly based on the logic defined into the FreeCamera code
  23604. var VirtualJoysticksCamera = (function (_super) {
  23605. __extends(VirtualJoysticksCamera, _super);
  23606. function VirtualJoysticksCamera(name, position, scene) {
  23607. _super.call(this, name, position, scene);
  23608. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  23609. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  23610. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  23611. this._leftjoystick.setJoystickSensibility(0.15);
  23612. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  23613. this._rightjoystick.setAxisForUpDown(0 /* X */);
  23614. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  23615. this._rightjoystick.reverseUpDown = true;
  23616. this._rightjoystick.setJoystickSensibility(0.05);
  23617. this._rightjoystick.setJoystickColor("yellow");
  23618. }
  23619. VirtualJoysticksCamera.prototype._checkInputs = function () {
  23620. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23621. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  23622. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23623. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  23624. if (!this._leftjoystick.pressed) {
  23625. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  23626. }
  23627. if (!this._rightjoystick.pressed) {
  23628. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  23629. }
  23630. };
  23631. VirtualJoysticksCamera.prototype.dispose = function () {
  23632. this._leftjoystick.releaseCanvas();
  23633. _super.prototype.dispose.call(this);
  23634. };
  23635. return VirtualJoysticksCamera;
  23636. })(BABYLON.FreeCamera);
  23637. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  23638. })(BABYLON || (BABYLON = {}));
  23639. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  23640. var __extends = this.__extends || function (d, b) {
  23641. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23642. function __() { this.constructor = d; }
  23643. __.prototype = b.prototype;
  23644. d.prototype = new __();
  23645. };
  23646. var BABYLON;
  23647. (function (BABYLON) {
  23648. var ShaderMaterial = (function (_super) {
  23649. __extends(ShaderMaterial, _super);
  23650. function ShaderMaterial(name, scene, shaderPath, options) {
  23651. _super.call(this, name, scene);
  23652. this._textures = new Array();
  23653. this._floats = new Array();
  23654. this._floatsArrays = {};
  23655. this._colors3 = new Array();
  23656. this._colors4 = new Array();
  23657. this._vectors2 = new Array();
  23658. this._vectors3 = new Array();
  23659. this._matrices = new Array();
  23660. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  23661. this._shaderPath = shaderPath;
  23662. options.needAlphaBlending = options.needAlphaBlending || false;
  23663. options.needAlphaTesting = options.needAlphaTesting || false;
  23664. options.attributes = options.attributes || ["position", "normal", "uv"];
  23665. options.uniforms = options.uniforms || ["worldViewProjection"];
  23666. options.samplers = options.samplers || [];
  23667. this._options = options;
  23668. }
  23669. ShaderMaterial.prototype.needAlphaBlending = function () {
  23670. return this._options.needAlphaBlending;
  23671. };
  23672. ShaderMaterial.prototype.needAlphaTesting = function () {
  23673. return this._options.needAlphaTesting;
  23674. };
  23675. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  23676. if (this._options.uniforms.indexOf(uniformName) === -1) {
  23677. this._options.uniforms.push(uniformName);
  23678. }
  23679. };
  23680. ShaderMaterial.prototype.setTexture = function (name, texture) {
  23681. if (this._options.samplers.indexOf(name) === -1) {
  23682. this._options.samplers.push(name);
  23683. }
  23684. this._textures[name] = texture;
  23685. return this;
  23686. };
  23687. ShaderMaterial.prototype.setFloat = function (name, value) {
  23688. this._checkUniform(name);
  23689. this._floats[name] = value;
  23690. return this;
  23691. };
  23692. ShaderMaterial.prototype.setFloats = function (name, value) {
  23693. this._checkUniform(name);
  23694. this._floatsArrays[name] = value;
  23695. return this;
  23696. };
  23697. ShaderMaterial.prototype.setColor3 = function (name, value) {
  23698. this._checkUniform(name);
  23699. this._colors3[name] = value;
  23700. return this;
  23701. };
  23702. ShaderMaterial.prototype.setColor4 = function (name, value) {
  23703. this._checkUniform(name);
  23704. this._colors4[name] = value;
  23705. return this;
  23706. };
  23707. ShaderMaterial.prototype.setVector2 = function (name, value) {
  23708. this._checkUniform(name);
  23709. this._vectors2[name] = value;
  23710. return this;
  23711. };
  23712. ShaderMaterial.prototype.setVector3 = function (name, value) {
  23713. this._checkUniform(name);
  23714. this._vectors3[name] = value;
  23715. return this;
  23716. };
  23717. ShaderMaterial.prototype.setMatrix = function (name, value) {
  23718. this._checkUniform(name);
  23719. this._matrices[name] = value;
  23720. return this;
  23721. };
  23722. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  23723. var scene = this.getScene();
  23724. var engine = scene.getEngine();
  23725. if (!this.checkReadyOnEveryCall) {
  23726. if (this._renderId === scene.getRenderId()) {
  23727. return true;
  23728. }
  23729. }
  23730. // Instances
  23731. var defines = [];
  23732. var fallbacks = new BABYLON.EffectFallbacks();
  23733. if (useInstances) {
  23734. defines.push("#define INSTANCES");
  23735. }
  23736. // Bones
  23737. if (mesh && mesh.useBones) {
  23738. defines.push("#define BONES");
  23739. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  23740. defines.push("#define BONES4");
  23741. fallbacks.addFallback(0, "BONES4");
  23742. }
  23743. // Alpha test
  23744. if (engine.getAlphaTesting()) {
  23745. defines.push("#define ALPHATEST");
  23746. }
  23747. var previousEffect = this._effect;
  23748. var join = defines.join("\n");
  23749. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  23750. if (!this._effect.isReady()) {
  23751. return false;
  23752. }
  23753. if (previousEffect !== this._effect) {
  23754. scene.resetCachedMaterial();
  23755. }
  23756. this._renderId = scene.getRenderId();
  23757. return true;
  23758. };
  23759. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23760. var scene = this.getScene();
  23761. if (this._options.uniforms.indexOf("world") !== -1) {
  23762. this._effect.setMatrix("world", world);
  23763. }
  23764. if (this._options.uniforms.indexOf("worldView") !== -1) {
  23765. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  23766. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  23767. }
  23768. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  23769. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  23770. }
  23771. };
  23772. ShaderMaterial.prototype.bind = function (world, mesh) {
  23773. // Std values
  23774. this.bindOnlyWorldMatrix(world);
  23775. if (this.getScene().getCachedMaterial() !== this) {
  23776. if (this._options.uniforms.indexOf("view") !== -1) {
  23777. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  23778. }
  23779. if (this._options.uniforms.indexOf("projection") !== -1) {
  23780. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  23781. }
  23782. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  23783. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  23784. }
  23785. // Bones
  23786. if (mesh && mesh.useBones) {
  23787. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  23788. }
  23789. for (var name in this._textures) {
  23790. this._effect.setTexture(name, this._textures[name]);
  23791. }
  23792. for (name in this._floats) {
  23793. this._effect.setFloat(name, this._floats[name]);
  23794. }
  23795. for (name in this._floatsArrays) {
  23796. this._effect.setArray(name, this._floatsArrays[name]);
  23797. }
  23798. for (name in this._colors3) {
  23799. this._effect.setColor3(name, this._colors3[name]);
  23800. }
  23801. for (name in this._colors4) {
  23802. var color = this._colors4[name];
  23803. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23804. }
  23805. for (name in this._vectors2) {
  23806. this._effect.setVector2(name, this._vectors2[name]);
  23807. }
  23808. for (name in this._vectors3) {
  23809. this._effect.setVector3(name, this._vectors3[name]);
  23810. }
  23811. for (name in this._matrices) {
  23812. this._effect.setMatrix(name, this._matrices[name]);
  23813. }
  23814. }
  23815. _super.prototype.bind.call(this, world, mesh);
  23816. };
  23817. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  23818. for (var name in this._textures) {
  23819. this._textures[name].dispose();
  23820. }
  23821. this._textures = [];
  23822. _super.prototype.dispose.call(this, forceDisposeEffect);
  23823. };
  23824. return ShaderMaterial;
  23825. })(BABYLON.Material);
  23826. BABYLON.ShaderMaterial = ShaderMaterial;
  23827. })(BABYLON || (BABYLON = {}));
  23828. //# sourceMappingURL=babylon.shaderMaterial.js.map
  23829. var BABYLON;
  23830. (function (BABYLON) {
  23831. var VertexData = (function () {
  23832. function VertexData() {
  23833. }
  23834. VertexData.prototype.set = function (data, kind) {
  23835. switch (kind) {
  23836. case BABYLON.VertexBuffer.PositionKind:
  23837. this.positions = data;
  23838. break;
  23839. case BABYLON.VertexBuffer.NormalKind:
  23840. this.normals = data;
  23841. break;
  23842. case BABYLON.VertexBuffer.UVKind:
  23843. this.uvs = data;
  23844. break;
  23845. case BABYLON.VertexBuffer.UV2Kind:
  23846. this.uv2s = data;
  23847. break;
  23848. case BABYLON.VertexBuffer.ColorKind:
  23849. this.colors = data;
  23850. break;
  23851. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23852. this.matricesIndices = data;
  23853. break;
  23854. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23855. this.matricesWeights = data;
  23856. break;
  23857. }
  23858. };
  23859. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23860. this._applyTo(mesh, updatable);
  23861. };
  23862. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23863. this._applyTo(geometry, updatable);
  23864. };
  23865. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23866. this._update(mesh);
  23867. };
  23868. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23869. this._update(geometry);
  23870. };
  23871. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23872. if (this.positions) {
  23873. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23874. }
  23875. if (this.normals) {
  23876. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23877. }
  23878. if (this.uvs) {
  23879. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23880. }
  23881. if (this.uv2s) {
  23882. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  23883. }
  23884. if (this.colors) {
  23885. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23886. }
  23887. if (this.matricesIndices) {
  23888. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23889. }
  23890. if (this.matricesWeights) {
  23891. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23892. }
  23893. if (this.indices) {
  23894. meshOrGeometry.setIndices(this.indices);
  23895. }
  23896. };
  23897. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23898. if (this.positions) {
  23899. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23900. }
  23901. if (this.normals) {
  23902. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23903. }
  23904. if (this.uvs) {
  23905. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23906. }
  23907. if (this.uv2s) {
  23908. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  23909. }
  23910. if (this.colors) {
  23911. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23912. }
  23913. if (this.matricesIndices) {
  23914. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23915. }
  23916. if (this.matricesWeights) {
  23917. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23918. }
  23919. if (this.indices) {
  23920. meshOrGeometry.setIndices(this.indices);
  23921. }
  23922. };
  23923. VertexData.prototype.transform = function (matrix) {
  23924. var transformed = BABYLON.Vector3.Zero();
  23925. if (this.positions) {
  23926. var position = BABYLON.Vector3.Zero();
  23927. for (var index = 0; index < this.positions.length; index += 3) {
  23928. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23929. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23930. this.positions[index] = transformed.x;
  23931. this.positions[index + 1] = transformed.y;
  23932. this.positions[index + 2] = transformed.z;
  23933. }
  23934. }
  23935. if (this.normals) {
  23936. var normal = BABYLON.Vector3.Zero();
  23937. for (index = 0; index < this.normals.length; index += 3) {
  23938. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23939. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23940. this.normals[index] = transformed.x;
  23941. this.normals[index + 1] = transformed.y;
  23942. this.normals[index + 2] = transformed.z;
  23943. }
  23944. }
  23945. };
  23946. VertexData.prototype.merge = function (other) {
  23947. if (other.indices) {
  23948. if (!this.indices) {
  23949. this.indices = [];
  23950. }
  23951. var offset = this.positions ? this.positions.length / 3 : 0;
  23952. for (var index = 0; index < other.indices.length; index++) {
  23953. this.indices.push(other.indices[index] + offset);
  23954. }
  23955. }
  23956. if (other.positions) {
  23957. if (!this.positions) {
  23958. this.positions = [];
  23959. }
  23960. for (index = 0; index < other.positions.length; index++) {
  23961. this.positions.push(other.positions[index]);
  23962. }
  23963. }
  23964. if (other.normals) {
  23965. if (!this.normals) {
  23966. this.normals = [];
  23967. }
  23968. for (index = 0; index < other.normals.length; index++) {
  23969. this.normals.push(other.normals[index]);
  23970. }
  23971. }
  23972. if (other.uvs) {
  23973. if (!this.uvs) {
  23974. this.uvs = [];
  23975. }
  23976. for (index = 0; index < other.uvs.length; index++) {
  23977. this.uvs.push(other.uvs[index]);
  23978. }
  23979. }
  23980. if (other.uv2s) {
  23981. if (!this.uv2s) {
  23982. this.uv2s = [];
  23983. }
  23984. for (index = 0; index < other.uv2s.length; index++) {
  23985. this.uv2s.push(other.uv2s[index]);
  23986. }
  23987. }
  23988. if (other.matricesIndices) {
  23989. if (!this.matricesIndices) {
  23990. this.matricesIndices = [];
  23991. }
  23992. for (index = 0; index < other.matricesIndices.length; index++) {
  23993. this.matricesIndices.push(other.matricesIndices[index]);
  23994. }
  23995. }
  23996. if (other.matricesWeights) {
  23997. if (!this.matricesWeights) {
  23998. this.matricesWeights = [];
  23999. }
  24000. for (index = 0; index < other.matricesWeights.length; index++) {
  24001. this.matricesWeights.push(other.matricesWeights[index]);
  24002. }
  24003. }
  24004. if (other.colors) {
  24005. if (!this.colors) {
  24006. this.colors = [];
  24007. }
  24008. for (index = 0; index < other.colors.length; index++) {
  24009. this.colors.push(other.colors[index]);
  24010. }
  24011. }
  24012. };
  24013. // Statics
  24014. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24015. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24016. };
  24017. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24018. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24019. };
  24020. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24021. var result = new VertexData();
  24022. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24023. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24024. }
  24025. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24026. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24027. }
  24028. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24029. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24030. }
  24031. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24032. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24033. }
  24034. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24035. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24036. }
  24037. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24038. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24039. }
  24040. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24041. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24042. }
  24043. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24044. return result;
  24045. };
  24046. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  24047. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24048. closeArray = closeArray || false;
  24049. closePath = closePath || false;
  24050. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24051. offset = offset || defaultOffset;
  24052. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24053. var positions = [];
  24054. var indices = [];
  24055. var normals = [];
  24056. var uvs = [];
  24057. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24058. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24059. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24060. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24061. var minlg; // minimal length among all paths from pathArray
  24062. var lg = []; // array of path lengths : nb of vertex per path
  24063. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  24064. var p; // path iterator
  24065. var i; // point iterator
  24066. var j; // point iterator
  24067. // if single path in pathArray
  24068. if (pathArray.length < 2) {
  24069. var ar1 = [];
  24070. var ar2 = [];
  24071. for (i = 0; i < pathArray[0].length - offset; i++) {
  24072. ar1.push(pathArray[0][i]);
  24073. ar2.push(pathArray[0][i + offset]);
  24074. }
  24075. pathArray = [ar1, ar2];
  24076. }
  24077. // positions and horizontal distances (u)
  24078. var idc = 0;
  24079. minlg = pathArray[0].length;
  24080. for (p = 0; p < pathArray.length; p++) {
  24081. uTotalDistance[p] = 0;
  24082. us[p] = [0];
  24083. var path = pathArray[p];
  24084. var l = path.length;
  24085. minlg = (minlg < l) ? minlg : l;
  24086. lg[p] = l;
  24087. idx[p] = idc;
  24088. j = 0;
  24089. while (j < l) {
  24090. positions.push(path[j].x, path[j].y, path[j].z);
  24091. if (j > 0) {
  24092. var vectlg = path[j].subtract(path[j - 1]).length();
  24093. var dist = vectlg + uTotalDistance[p];
  24094. us[p].push(dist);
  24095. uTotalDistance[p] = dist;
  24096. }
  24097. j++;
  24098. }
  24099. if (closePath) {
  24100. vectlg = path[0].subtract(path[j - 1]).length();
  24101. dist = vectlg + uTotalDistance[p];
  24102. uTotalDistance[p] = dist;
  24103. }
  24104. idc += l;
  24105. }
  24106. for (i = 0; i < minlg; i++) {
  24107. vTotalDistance[i] = 0;
  24108. vs[i] = [0];
  24109. var path1;
  24110. var path2;
  24111. for (p = 0; p < pathArray.length - 1; p++) {
  24112. path1 = pathArray[p];
  24113. path2 = pathArray[p + 1];
  24114. vectlg = path2[i].subtract(path1[i]).length();
  24115. dist = vectlg + vTotalDistance[i];
  24116. vs[i].push(dist);
  24117. vTotalDistance[i] = dist;
  24118. }
  24119. if (closeArray) {
  24120. path1 = pathArray[p];
  24121. path2 = pathArray[0];
  24122. vectlg = path2[i].subtract(path1[i]).length();
  24123. dist = vectlg + vTotalDistance[i];
  24124. vTotalDistance[i] = dist;
  24125. }
  24126. }
  24127. // uvs
  24128. var u;
  24129. var v;
  24130. for (p = 0; p < pathArray.length; p++) {
  24131. for (i = 0; i < minlg; i++) {
  24132. u = us[p][i] / uTotalDistance[p];
  24133. v = vs[i][p] / vTotalDistance[i];
  24134. uvs.push(u, v);
  24135. }
  24136. }
  24137. // indices
  24138. p = 0; // path index
  24139. var pi = 0; // positions array index
  24140. var l1 = lg[p] - 1; // path1 length
  24141. var l2 = lg[p + 1] - 1; // path2 length
  24142. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24143. var shft = idx[1] - idx[0]; // shift
  24144. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  24145. var t1; // two consecutive triangles, so 4 points : point1
  24146. var t2; // point2
  24147. var t3; // point3
  24148. var t4; // point4
  24149. while (pi <= min && p < path1nb) {
  24150. // 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
  24151. t1 = pi;
  24152. t2 = pi + shft;
  24153. t3 = pi + 1;
  24154. t4 = pi + shft + 1;
  24155. indices.push(pi, pi + shft, pi + 1);
  24156. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24157. pi += 1;
  24158. if (pi === min) {
  24159. if (closePath) {
  24160. indices.push(pi, pi + shft, idx[p]);
  24161. indices.push(idx[p] + shft, idx[p], pi + shft);
  24162. t3 = idx[p];
  24163. t4 = idx[p] + shft;
  24164. }
  24165. p++;
  24166. if (p === lg.length - 1) {
  24167. shft = idx[0] - idx[p];
  24168. l1 = lg[p] - 1;
  24169. l2 = lg[0] - 1;
  24170. }
  24171. else {
  24172. shft = idx[p + 1] - idx[p];
  24173. l1 = lg[p] - 1;
  24174. l2 = lg[p + 1] - 1;
  24175. }
  24176. pi = idx[p];
  24177. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24178. }
  24179. }
  24180. // normals
  24181. VertexData.ComputeNormals(positions, indices, normals);
  24182. // sides
  24183. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24184. // Result
  24185. var vertexData = new VertexData();
  24186. vertexData.indices = indices;
  24187. vertexData.positions = positions;
  24188. vertexData.normals = normals;
  24189. vertexData.uvs = uvs;
  24190. return vertexData;
  24191. };
  24192. VertexData.CreateBox = function (size, sideOrientation) {
  24193. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24194. var normalsSource = [
  24195. new BABYLON.Vector3(0, 0, 1),
  24196. new BABYLON.Vector3(0, 0, -1),
  24197. new BABYLON.Vector3(1, 0, 0),
  24198. new BABYLON.Vector3(-1, 0, 0),
  24199. new BABYLON.Vector3(0, 1, 0),
  24200. new BABYLON.Vector3(0, -1, 0)
  24201. ];
  24202. var indices = [];
  24203. var positions = [];
  24204. var normals = [];
  24205. var uvs = [];
  24206. size = size || 1;
  24207. for (var index = 0; index < normalsSource.length; index++) {
  24208. var normal = normalsSource[index];
  24209. // Get two vectors perpendicular to the face normal and to each other.
  24210. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24211. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24212. // Six indices (two triangles) per face.
  24213. var verticesLength = positions.length / 3;
  24214. indices.push(verticesLength);
  24215. indices.push(verticesLength + 1);
  24216. indices.push(verticesLength + 2);
  24217. indices.push(verticesLength);
  24218. indices.push(verticesLength + 2);
  24219. indices.push(verticesLength + 3);
  24220. // Four vertices per face.
  24221. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  24222. positions.push(vertex.x, vertex.y, vertex.z);
  24223. normals.push(normal.x, normal.y, normal.z);
  24224. uvs.push(1.0, 1.0);
  24225. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  24226. positions.push(vertex.x, vertex.y, vertex.z);
  24227. normals.push(normal.x, normal.y, normal.z);
  24228. uvs.push(0.0, 1.0);
  24229. vertex = normal.add(side1).add(side2).scale(size / 2);
  24230. positions.push(vertex.x, vertex.y, vertex.z);
  24231. normals.push(normal.x, normal.y, normal.z);
  24232. uvs.push(0.0, 0.0);
  24233. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  24234. positions.push(vertex.x, vertex.y, vertex.z);
  24235. normals.push(normal.x, normal.y, normal.z);
  24236. uvs.push(1.0, 0.0);
  24237. }
  24238. // sides
  24239. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24240. // Result
  24241. var vertexData = new VertexData();
  24242. vertexData.indices = indices;
  24243. vertexData.positions = positions;
  24244. vertexData.normals = normals;
  24245. vertexData.uvs = uvs;
  24246. return vertexData;
  24247. };
  24248. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  24249. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24250. segments = segments || 32;
  24251. diameter = diameter || 1;
  24252. var radius = diameter / 2;
  24253. var totalZRotationSteps = 2 + segments;
  24254. var totalYRotationSteps = 2 * totalZRotationSteps;
  24255. var indices = [];
  24256. var positions = [];
  24257. var normals = [];
  24258. var uvs = [];
  24259. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24260. var normalizedZ = zRotationStep / totalZRotationSteps;
  24261. var angleZ = (normalizedZ * Math.PI);
  24262. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24263. var normalizedY = yRotationStep / totalYRotationSteps;
  24264. var angleY = normalizedY * Math.PI * 2;
  24265. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24266. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24267. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24268. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24269. var vertex = complete.scale(radius);
  24270. var normal = BABYLON.Vector3.Normalize(vertex);
  24271. positions.push(vertex.x, vertex.y, vertex.z);
  24272. normals.push(normal.x, normal.y, normal.z);
  24273. uvs.push(normalizedZ, normalizedY);
  24274. }
  24275. if (zRotationStep > 0) {
  24276. var verticesCount = positions.length / 3;
  24277. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24278. indices.push((firstIndex));
  24279. indices.push((firstIndex + 1));
  24280. indices.push(firstIndex + totalYRotationSteps + 1);
  24281. indices.push((firstIndex + totalYRotationSteps + 1));
  24282. indices.push((firstIndex + 1));
  24283. indices.push((firstIndex + totalYRotationSteps + 2));
  24284. }
  24285. }
  24286. }
  24287. // Sides
  24288. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24289. // Result
  24290. var vertexData = new VertexData();
  24291. vertexData.indices = indices;
  24292. vertexData.positions = positions;
  24293. vertexData.normals = normals;
  24294. vertexData.uvs = uvs;
  24295. return vertexData;
  24296. };
  24297. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  24298. if (subdivisions === void 0) { subdivisions = 1; }
  24299. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24300. var radiusTop = diameterTop / 2;
  24301. var radiusBottom = diameterBottom / 2;
  24302. var indices = [];
  24303. var positions = [];
  24304. var normals = [];
  24305. var uvs = [];
  24306. height = height || 1;
  24307. diameterTop = diameterTop || 0.5;
  24308. diameterBottom = diameterBottom || 1;
  24309. tessellation = tessellation || 16;
  24310. subdivisions = subdivisions || 1;
  24311. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  24312. var getCircleVector = function (i) {
  24313. var angle = (i * 2.0 * Math.PI / tessellation);
  24314. var dx = Math.cos(angle);
  24315. var dz = Math.sin(angle);
  24316. return new BABYLON.Vector3(dx, 0, dz);
  24317. };
  24318. var createCylinderCap = function (isTop) {
  24319. var radius = isTop ? radiusTop : radiusBottom;
  24320. if (radius === 0) {
  24321. return;
  24322. }
  24323. var vbase = positions.length / 3;
  24324. var offset = new BABYLON.Vector3(0, height / 2, 0);
  24325. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  24326. if (!isTop) {
  24327. offset.scaleInPlace(-1);
  24328. textureScale.x = -textureScale.x;
  24329. }
  24330. for (var i = 0; i < tessellation; i++) {
  24331. var circleVector = getCircleVector(i);
  24332. var position = circleVector.scale(radius).add(offset);
  24333. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  24334. positions.push(position.x, position.y, position.z);
  24335. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24336. }
  24337. for (i = 0; i < tessellation - 2; i++) {
  24338. if (!isTop) {
  24339. indices.push(vbase);
  24340. indices.push(vbase + (i + 2) % tessellation);
  24341. indices.push(vbase + (i + 1) % tessellation);
  24342. }
  24343. else {
  24344. indices.push(vbase);
  24345. indices.push(vbase + (i + 1) % tessellation);
  24346. indices.push(vbase + (i + 2) % tessellation);
  24347. }
  24348. }
  24349. };
  24350. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  24351. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  24352. var stride = tessellation + 1;
  24353. for (var i = 0; i <= tessellation; i++) {
  24354. var circleVector = getCircleVector(i);
  24355. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  24356. var position, radius = radiusBottom;
  24357. for (var s = 0; s <= subdivisions; s++) {
  24358. // Update variables
  24359. position = circleVector.scale(radius);
  24360. position.addInPlace(base.add(offset.scale(s)));
  24361. textureCoordinate.y += 1 / subdivisions;
  24362. radius += (radiusTop - radiusBottom) / subdivisions;
  24363. // Push in arrays
  24364. positions.push(position.x, position.y, position.z);
  24365. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24366. }
  24367. }
  24368. subdivisions += 1;
  24369. for (s = 0; s < subdivisions - 1; s++) {
  24370. for (i = 0; i <= tessellation; i++) {
  24371. indices.push(i * subdivisions + s);
  24372. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  24373. indices.push(i * subdivisions + (s + 1));
  24374. indices.push(i * subdivisions + (s + 1));
  24375. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  24376. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  24377. }
  24378. }
  24379. // Create flat triangle fan caps to seal the top and bottom.
  24380. createCylinderCap(true);
  24381. createCylinderCap(false);
  24382. // Normals
  24383. VertexData.ComputeNormals(positions, indices, normals);
  24384. // Sides
  24385. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24386. // Result
  24387. var vertexData = new VertexData();
  24388. vertexData.indices = indices;
  24389. vertexData.positions = positions;
  24390. vertexData.normals = normals;
  24391. vertexData.uvs = uvs;
  24392. return vertexData;
  24393. };
  24394. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  24395. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24396. var indices = [];
  24397. var positions = [];
  24398. var normals = [];
  24399. var uvs = [];
  24400. diameter = diameter || 1;
  24401. thickness = thickness || 0.5;
  24402. tessellation = tessellation || 16;
  24403. var stride = tessellation + 1;
  24404. for (var i = 0; i <= tessellation; i++) {
  24405. var u = i / tessellation;
  24406. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24407. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24408. for (var j = 0; j <= tessellation; j++) {
  24409. var v = 1 - j / tessellation;
  24410. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24411. var dx = Math.cos(innerAngle);
  24412. var dy = Math.sin(innerAngle);
  24413. // Create a vertex.
  24414. var normal = new BABYLON.Vector3(dx, dy, 0);
  24415. var position = normal.scale(thickness / 2);
  24416. var textureCoordinate = new BABYLON.Vector2(u, v);
  24417. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24418. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24419. positions.push(position.x, position.y, position.z);
  24420. normals.push(normal.x, normal.y, normal.z);
  24421. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24422. // And create indices for two triangles.
  24423. var nextI = (i + 1) % stride;
  24424. var nextJ = (j + 1) % stride;
  24425. indices.push(i * stride + j);
  24426. indices.push(i * stride + nextJ);
  24427. indices.push(nextI * stride + j);
  24428. indices.push(i * stride + nextJ);
  24429. indices.push(nextI * stride + nextJ);
  24430. indices.push(nextI * stride + j);
  24431. }
  24432. }
  24433. // Sides
  24434. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24435. // Result
  24436. var vertexData = new VertexData();
  24437. vertexData.indices = indices;
  24438. vertexData.positions = positions;
  24439. vertexData.normals = normals;
  24440. vertexData.uvs = uvs;
  24441. return vertexData;
  24442. };
  24443. VertexData.CreateLines = function (points) {
  24444. var indices = [];
  24445. var positions = [];
  24446. for (var index = 0; index < points.length; index++) {
  24447. positions.push(points[index].x, points[index].y, points[index].z);
  24448. if (index > 0) {
  24449. indices.push(index - 1);
  24450. indices.push(index);
  24451. }
  24452. }
  24453. // Result
  24454. var vertexData = new VertexData();
  24455. vertexData.indices = indices;
  24456. vertexData.positions = positions;
  24457. return vertexData;
  24458. };
  24459. VertexData.CreateGround = function (width, height, subdivisions) {
  24460. var indices = [];
  24461. var positions = [];
  24462. var normals = [];
  24463. var uvs = [];
  24464. var row, col;
  24465. width = width || 1;
  24466. height = height || 1;
  24467. subdivisions = subdivisions || 1;
  24468. for (row = 0; row <= subdivisions; row++) {
  24469. for (col = 0; col <= subdivisions; col++) {
  24470. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24471. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24472. positions.push(position.x, position.y, position.z);
  24473. normals.push(normal.x, normal.y, normal.z);
  24474. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24475. }
  24476. }
  24477. for (row = 0; row < subdivisions; row++) {
  24478. for (col = 0; col < subdivisions; col++) {
  24479. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24480. indices.push(col + 1 + row * (subdivisions + 1));
  24481. indices.push(col + row * (subdivisions + 1));
  24482. indices.push(col + (row + 1) * (subdivisions + 1));
  24483. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24484. indices.push(col + row * (subdivisions + 1));
  24485. }
  24486. }
  24487. // Result
  24488. var vertexData = new VertexData();
  24489. vertexData.indices = indices;
  24490. vertexData.positions = positions;
  24491. vertexData.normals = normals;
  24492. vertexData.uvs = uvs;
  24493. return vertexData;
  24494. };
  24495. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  24496. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  24497. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  24498. var indices = [];
  24499. var positions = [];
  24500. var normals = [];
  24501. var uvs = [];
  24502. var row, col, tileRow, tileCol;
  24503. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  24504. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24505. precision.w = (precision.w < 1) ? 1 : precision.w;
  24506. precision.h = (precision.h < 1) ? 1 : precision.h;
  24507. var tileSize = {
  24508. 'w': (xmax - xmin) / subdivisions.w,
  24509. 'h': (zmax - zmin) / subdivisions.h
  24510. };
  24511. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24512. // Indices
  24513. var base = positions.length / 3;
  24514. var rowLength = precision.w + 1;
  24515. for (row = 0; row < precision.h; row++) {
  24516. for (col = 0; col < precision.w; col++) {
  24517. var square = [
  24518. base + col + row * rowLength,
  24519. base + (col + 1) + row * rowLength,
  24520. base + (col + 1) + (row + 1) * rowLength,
  24521. base + col + (row + 1) * rowLength
  24522. ];
  24523. indices.push(square[1]);
  24524. indices.push(square[2]);
  24525. indices.push(square[3]);
  24526. indices.push(square[0]);
  24527. indices.push(square[1]);
  24528. indices.push(square[3]);
  24529. }
  24530. }
  24531. // Position, normals and uvs
  24532. var position = BABYLON.Vector3.Zero();
  24533. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24534. for (row = 0; row <= precision.h; row++) {
  24535. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24536. for (col = 0; col <= precision.w; col++) {
  24537. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24538. position.y = 0;
  24539. positions.push(position.x, position.y, position.z);
  24540. normals.push(normal.x, normal.y, normal.z);
  24541. uvs.push(col / precision.w, row / precision.h);
  24542. }
  24543. }
  24544. }
  24545. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24546. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24547. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24548. }
  24549. }
  24550. // Result
  24551. var vertexData = new VertexData();
  24552. vertexData.indices = indices;
  24553. vertexData.positions = positions;
  24554. vertexData.normals = normals;
  24555. vertexData.uvs = uvs;
  24556. return vertexData;
  24557. };
  24558. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  24559. var indices = [];
  24560. var positions = [];
  24561. var normals = [];
  24562. var uvs = [];
  24563. var row, col;
  24564. for (row = 0; row <= subdivisions; row++) {
  24565. for (col = 0; col <= subdivisions; col++) {
  24566. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24567. // Compute height
  24568. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  24569. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  24570. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  24571. var r = buffer[pos] / 255.0;
  24572. var g = buffer[pos + 1] / 255.0;
  24573. var b = buffer[pos + 2] / 255.0;
  24574. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24575. position.y = minHeight + (maxHeight - minHeight) * gradient;
  24576. // Add vertex
  24577. positions.push(position.x, position.y, position.z);
  24578. normals.push(0, 0, 0);
  24579. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24580. }
  24581. }
  24582. for (row = 0; row < subdivisions; row++) {
  24583. for (col = 0; col < subdivisions; col++) {
  24584. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24585. indices.push(col + 1 + row * (subdivisions + 1));
  24586. indices.push(col + row * (subdivisions + 1));
  24587. indices.push(col + (row + 1) * (subdivisions + 1));
  24588. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24589. indices.push(col + row * (subdivisions + 1));
  24590. }
  24591. }
  24592. // Normals
  24593. VertexData.ComputeNormals(positions, indices, normals);
  24594. // Result
  24595. var vertexData = new VertexData();
  24596. vertexData.indices = indices;
  24597. vertexData.positions = positions;
  24598. vertexData.normals = normals;
  24599. vertexData.uvs = uvs;
  24600. return vertexData;
  24601. };
  24602. VertexData.CreatePlane = function (size, sideOrientation) {
  24603. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24604. var indices = [];
  24605. var positions = [];
  24606. var normals = [];
  24607. var uvs = [];
  24608. size = size || 1;
  24609. // Vertices
  24610. var halfSize = size / 2.0;
  24611. positions.push(-halfSize, -halfSize, 0);
  24612. normals.push(0, 0, -1.0);
  24613. uvs.push(0.0, 0.0);
  24614. positions.push(halfSize, -halfSize, 0);
  24615. normals.push(0, 0, -1.0);
  24616. uvs.push(1.0, 0.0);
  24617. positions.push(halfSize, halfSize, 0);
  24618. normals.push(0, 0, -1.0);
  24619. uvs.push(1.0, 1.0);
  24620. positions.push(-halfSize, halfSize, 0);
  24621. normals.push(0, 0, -1.0);
  24622. uvs.push(0.0, 1.0);
  24623. // Indices
  24624. indices.push(0);
  24625. indices.push(1);
  24626. indices.push(2);
  24627. indices.push(0);
  24628. indices.push(2);
  24629. indices.push(3);
  24630. // Sides
  24631. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24632. // Result
  24633. var vertexData = new VertexData();
  24634. vertexData.indices = indices;
  24635. vertexData.positions = positions;
  24636. vertexData.normals = normals;
  24637. vertexData.uvs = uvs;
  24638. return vertexData;
  24639. };
  24640. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  24641. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24642. var positions = [];
  24643. var indices = [];
  24644. var normals = [];
  24645. var uvs = [];
  24646. // positions and uvs
  24647. positions.push(0, 0, 0); // disc center first
  24648. uvs.push(0.5, 0.5);
  24649. var step = Math.PI * 2 / tessellation;
  24650. for (var a = 0; a < Math.PI * 2; a += step) {
  24651. var x = Math.cos(a);
  24652. var y = Math.sin(a);
  24653. var u = (x + 1) / 2;
  24654. var v = (1 - y) / 2;
  24655. positions.push(radius * x, radius * y, 0);
  24656. uvs.push(u, v);
  24657. }
  24658. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24659. uvs.push(uvs[2], uvs[3]);
  24660. //indices
  24661. var vertexNb = positions.length / 3;
  24662. for (var i = 1; i < vertexNb - 1; i++) {
  24663. indices.push(i + 1, 0, i);
  24664. }
  24665. // result
  24666. VertexData.ComputeNormals(positions, indices, normals);
  24667. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24668. var vertexData = new VertexData();
  24669. vertexData.indices = indices;
  24670. vertexData.positions = positions;
  24671. vertexData.normals = normals;
  24672. vertexData.uvs = uvs;
  24673. return vertexData;
  24674. };
  24675. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24676. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  24677. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24678. var indices = [];
  24679. var positions = [];
  24680. var normals = [];
  24681. var uvs = [];
  24682. radius = radius || 2;
  24683. tube = tube || 0.5;
  24684. radialSegments = radialSegments || 32;
  24685. tubularSegments = tubularSegments || 32;
  24686. p = p || 2;
  24687. q = q || 3;
  24688. // Helper
  24689. var getPos = function (angle) {
  24690. var cu = Math.cos(angle);
  24691. var su = Math.sin(angle);
  24692. var quOverP = q / p * angle;
  24693. var cs = Math.cos(quOverP);
  24694. var tx = radius * (2 + cs) * 0.5 * cu;
  24695. var ty = radius * (2 + cs) * su * 0.5;
  24696. var tz = radius * Math.sin(quOverP) * 0.5;
  24697. return new BABYLON.Vector3(tx, ty, tz);
  24698. };
  24699. for (var i = 0; i <= radialSegments; i++) {
  24700. var modI = i % radialSegments;
  24701. var u = modI / radialSegments * 2 * p * Math.PI;
  24702. var p1 = getPos(u);
  24703. var p2 = getPos(u + 0.01);
  24704. var tang = p2.subtract(p1);
  24705. var n = p2.add(p1);
  24706. var bitan = BABYLON.Vector3.Cross(tang, n);
  24707. n = BABYLON.Vector3.Cross(bitan, tang);
  24708. bitan.normalize();
  24709. n.normalize();
  24710. for (var j = 0; j < tubularSegments; j++) {
  24711. var modJ = j % tubularSegments;
  24712. var v = modJ / tubularSegments * 2 * Math.PI;
  24713. var cx = -tube * Math.cos(v);
  24714. var cy = tube * Math.sin(v);
  24715. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24716. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24717. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24718. uvs.push(i / radialSegments);
  24719. uvs.push(j / tubularSegments);
  24720. }
  24721. }
  24722. for (i = 0; i < radialSegments; i++) {
  24723. for (j = 0; j < tubularSegments; j++) {
  24724. var jNext = (j + 1) % tubularSegments;
  24725. var a = i * tubularSegments + j;
  24726. var b = (i + 1) * tubularSegments + j;
  24727. var c = (i + 1) * tubularSegments + jNext;
  24728. var d = i * tubularSegments + jNext;
  24729. indices.push(d);
  24730. indices.push(b);
  24731. indices.push(a);
  24732. indices.push(d);
  24733. indices.push(c);
  24734. indices.push(b);
  24735. }
  24736. }
  24737. // Normals
  24738. VertexData.ComputeNormals(positions, indices, normals);
  24739. // Sides
  24740. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24741. // Result
  24742. var vertexData = new VertexData();
  24743. vertexData.indices = indices;
  24744. vertexData.positions = positions;
  24745. vertexData.normals = normals;
  24746. vertexData.uvs = uvs;
  24747. return vertexData;
  24748. };
  24749. // Tools
  24750. /**
  24751. * @param {any} - positions (number[] or Float32Array)
  24752. * @param {any} - indices (number[] or Uint16Array)
  24753. * @param {any} - normals (number[] or Float32Array)
  24754. */
  24755. VertexData.ComputeNormals = function (positions, indices, normals) {
  24756. var index = 0;
  24757. // temp Vector3
  24758. var p1 = BABYLON.Vector3.Zero();
  24759. var p2 = BABYLON.Vector3.Zero();
  24760. var p3 = BABYLON.Vector3.Zero();
  24761. var p1p2 = BABYLON.Vector3.Zero();
  24762. var p3p2 = BABYLON.Vector3.Zero();
  24763. var faceNormal = BABYLON.Vector3.Zero();
  24764. var vertexNormali1 = BABYLON.Vector3.Zero();
  24765. var vertexNormali2 = BABYLON.Vector3.Zero();
  24766. var vertexNormali3 = BABYLON.Vector3.Zero();
  24767. // indice triplet = 1 face
  24768. var nbFaces = indices.length / 3;
  24769. for (index = 0; index < nbFaces; index++) {
  24770. var i1 = indices[index * 3];
  24771. var i2 = indices[index * 3 + 1];
  24772. var i3 = indices[index * 3 + 2];
  24773. // setting the temp V3
  24774. BABYLON.Vector3.FromFloatsToRef(positions[i1 * 3], positions[i1 * 3 + 1], positions[i1 * 3 + 2], p1);
  24775. BABYLON.Vector3.FromFloatsToRef(positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2], p2);
  24776. BABYLON.Vector3.FromFloatsToRef(positions[i3 * 3], positions[i3 * 3 + 1], positions[i3 * 3 + 2], p3);
  24777. p1.subtractToRef(p2, p1p2);
  24778. p3.subtractToRef(p2, p3p2);
  24779. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  24780. faceNormal.normalize();
  24781. // All intermediate results are stored in the normals array :
  24782. // get the normals at i1, i2 and i3 indexes
  24783. normals[i1 * 3] = normals[i1 * 3] || 0.0;
  24784. normals[i1 * 3 + 1] = normals[i1 * 3 + 1] || 0.0;
  24785. normals[i1 * 3 + 2] = normals[i1 * 3 + 2] || 0.0;
  24786. normals[i2 * 3] = normals[i2 * 3] || 0.0;
  24787. normals[i2 * 3 + 1] = normals[i2 * 3 + 1] || 0.0;
  24788. normals[i2 * 3 + 2] = normals[i2 * 3 + 2] || 0.0;
  24789. normals[i3 * 3] = normals[i3 * 3] || 0.0;
  24790. normals[i3 * 3 + 1] = normals[i3 * 3 + 1] || 0.0;
  24791. normals[i3 * 3 + 2] = normals[i3 * 3 + 2] || 0.0;
  24792. // make intermediate vectors3 from normals values
  24793. BABYLON.Vector3.FromFloatsToRef(normals[i1 * 3], normals[i1 * 3 + 1], normals[i1 * 3 + 2], vertexNormali1);
  24794. BABYLON.Vector3.FromFloatsToRef(normals[i2 * 3], normals[i2 * 3 + 1], normals[i2 * 3 + 2], vertexNormali2);
  24795. BABYLON.Vector3.FromFloatsToRef(normals[i3 * 3], normals[i3 * 3 + 1], normals[i3 * 3 + 2], vertexNormali3);
  24796. // add the current face normals to these intermediate vectors3
  24797. vertexNormali1 = vertexNormali1.addInPlace(faceNormal);
  24798. vertexNormali2 = vertexNormali2.addInPlace(faceNormal);
  24799. vertexNormali3 = vertexNormali3.addInPlace(faceNormal);
  24800. // store back intermediate vectors3 into the normals array
  24801. normals[i1 * 3] = vertexNormali1.x;
  24802. normals[i1 * 3 + 1] = vertexNormali1.y;
  24803. normals[i1 * 3 + 2] = vertexNormali1.z;
  24804. normals[i2 * 3] = vertexNormali2.x;
  24805. normals[i2 * 3 + 1] = vertexNormali2.y;
  24806. normals[i2 * 3 + 2] = vertexNormali2.z;
  24807. normals[i3 * 3] = vertexNormali3.x;
  24808. normals[i3 * 3 + 1] = vertexNormali3.y;
  24809. normals[i3 * 3 + 2] = vertexNormali3.z;
  24810. }
  24811. for (index = 0; index < normals.length / 3; index++) {
  24812. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  24813. vertexNormali1.normalize();
  24814. normals[index * 3] = vertexNormali1.x;
  24815. normals[index * 3 + 1] = vertexNormali1.y;
  24816. normals[index * 3 + 2] = vertexNormali1.z;
  24817. }
  24818. };
  24819. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24820. var li = indices.length;
  24821. var ln = normals.length;
  24822. var i;
  24823. var n;
  24824. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24825. switch (sideOrientation) {
  24826. case BABYLON.Mesh.FRONTSIDE:
  24827. break;
  24828. case BABYLON.Mesh.BACKSIDE:
  24829. var tmp;
  24830. for (i = 0; i < li; i += 3) {
  24831. tmp = indices[i];
  24832. indices[i] = indices[i + 2];
  24833. indices[i + 2] = tmp;
  24834. }
  24835. for (n = 0; n < ln; n++) {
  24836. normals[n] = -normals[n];
  24837. }
  24838. break;
  24839. case BABYLON.Mesh.DOUBLESIDE:
  24840. // positions
  24841. var lp = positions.length;
  24842. var l = lp / 3;
  24843. for (var p = 0; p < lp; p++) {
  24844. positions[lp + p] = positions[p];
  24845. }
  24846. for (i = 0; i < li; i += 3) {
  24847. indices[i + li] = indices[i + 2] + l;
  24848. indices[i + 1 + li] = indices[i + 1] + l;
  24849. indices[i + 2 + li] = indices[i] + l;
  24850. }
  24851. for (n = 0; n < ln; n++) {
  24852. normals[ln + n] = -normals[n];
  24853. }
  24854. // uvs
  24855. var lu = uvs.length;
  24856. for (var u = 0; u < lu; u++) {
  24857. uvs[u + lu] = uvs[u];
  24858. }
  24859. break;
  24860. }
  24861. };
  24862. return VertexData;
  24863. })();
  24864. BABYLON.VertexData = VertexData;
  24865. })(BABYLON || (BABYLON = {}));
  24866. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  24867. var __extends = this.__extends || function (d, b) {
  24868. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24869. function __() { this.constructor = d; }
  24870. __.prototype = b.prototype;
  24871. d.prototype = new __();
  24872. };
  24873. var BABYLON;
  24874. (function (BABYLON) {
  24875. var buildCamera = function (that, name) {
  24876. that._leftCamera.isIntermediate = true;
  24877. that.subCameras.push(that._leftCamera);
  24878. that.subCameras.push(that._rightCamera);
  24879. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  24880. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  24881. that._anaglyphPostProcess.onApply = function (effect) {
  24882. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  24883. };
  24884. that._update();
  24885. };
  24886. var AnaglyphArcRotateCamera = (function (_super) {
  24887. __extends(AnaglyphArcRotateCamera, _super);
  24888. // ANY
  24889. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  24890. _super.call(this, name, alpha, beta, radius, target, scene);
  24891. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  24892. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  24893. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  24894. buildCamera(this, name);
  24895. }
  24896. AnaglyphArcRotateCamera.prototype._update = function () {
  24897. this._updateCamera(this._leftCamera);
  24898. this._updateCamera(this._rightCamera);
  24899. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  24900. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  24901. _super.prototype._update.call(this);
  24902. };
  24903. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  24904. camera.beta = this.beta;
  24905. camera.radius = this.radius;
  24906. camera.minZ = this.minZ;
  24907. camera.maxZ = this.maxZ;
  24908. camera.fov = this.fov;
  24909. camera.target = this.target;
  24910. };
  24911. return AnaglyphArcRotateCamera;
  24912. })(BABYLON.ArcRotateCamera);
  24913. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  24914. var AnaglyphFreeCamera = (function (_super) {
  24915. __extends(AnaglyphFreeCamera, _super);
  24916. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  24917. _super.call(this, name, position, scene);
  24918. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  24919. this._transformMatrix = new BABYLON.Matrix();
  24920. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  24921. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  24922. buildCamera(this, name);
  24923. }
  24924. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  24925. var target = this.getTarget();
  24926. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  24927. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  24928. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  24929. };
  24930. AnaglyphFreeCamera.prototype._update = function () {
  24931. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  24932. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  24933. this._updateCamera(this._leftCamera);
  24934. this._updateCamera(this._rightCamera);
  24935. _super.prototype._update.call(this);
  24936. };
  24937. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  24938. camera.minZ = this.minZ;
  24939. camera.maxZ = this.maxZ;
  24940. camera.fov = this.fov;
  24941. camera.viewport = this.viewport;
  24942. camera.setTarget(this.getTarget());
  24943. };
  24944. return AnaglyphFreeCamera;
  24945. })(BABYLON.FreeCamera);
  24946. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  24947. })(BABYLON || (BABYLON = {}));
  24948. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  24949. var __extends = this.__extends || function (d, b) {
  24950. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24951. function __() { this.constructor = d; }
  24952. __.prototype = b.prototype;
  24953. d.prototype = new __();
  24954. };
  24955. var BABYLON;
  24956. (function (BABYLON) {
  24957. var AnaglyphPostProcess = (function (_super) {
  24958. __extends(AnaglyphPostProcess, _super);
  24959. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  24960. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  24961. }
  24962. return AnaglyphPostProcess;
  24963. })(BABYLON.PostProcess);
  24964. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  24965. })(BABYLON || (BABYLON = {}));
  24966. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  24967. var BABYLON;
  24968. (function (BABYLON) {
  24969. var Tags = (function () {
  24970. function Tags() {
  24971. }
  24972. Tags.EnableFor = function (obj) {
  24973. obj._tags = obj._tags || {};
  24974. obj.hasTags = function () {
  24975. return Tags.HasTags(obj);
  24976. };
  24977. obj.addTags = function (tagsString) {
  24978. return Tags.AddTagsTo(obj, tagsString);
  24979. };
  24980. obj.removeTags = function (tagsString) {
  24981. return Tags.RemoveTagsFrom(obj, tagsString);
  24982. };
  24983. obj.matchesTagsQuery = function (tagsQuery) {
  24984. return Tags.MatchesQuery(obj, tagsQuery);
  24985. };
  24986. };
  24987. Tags.DisableFor = function (obj) {
  24988. delete obj._tags;
  24989. delete obj.hasTags;
  24990. delete obj.addTags;
  24991. delete obj.removeTags;
  24992. delete obj.matchesTagsQuery;
  24993. };
  24994. Tags.HasTags = function (obj) {
  24995. if (!obj._tags) {
  24996. return false;
  24997. }
  24998. return !BABYLON.Tools.IsEmpty(obj._tags);
  24999. };
  25000. Tags.GetTags = function (obj) {
  25001. if (!obj._tags) {
  25002. return null;
  25003. }
  25004. return obj._tags;
  25005. };
  25006. // the tags 'true' and 'false' are reserved and cannot be used as tags
  25007. // a tag cannot start with '||', '&&', and '!'
  25008. // it cannot contain whitespaces
  25009. Tags.AddTagsTo = function (obj, tagsString) {
  25010. if (!tagsString) {
  25011. return;
  25012. }
  25013. var tags = tagsString.split(" ");
  25014. for (var t in tags) {
  25015. Tags._AddTagTo(obj, tags[t]);
  25016. }
  25017. };
  25018. Tags._AddTagTo = function (obj, tag) {
  25019. tag = tag.trim();
  25020. if (tag === "" || tag === "true" || tag === "false") {
  25021. return;
  25022. }
  25023. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25024. return;
  25025. }
  25026. Tags.EnableFor(obj);
  25027. obj._tags[tag] = true;
  25028. };
  25029. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25030. if (!Tags.HasTags(obj)) {
  25031. return;
  25032. }
  25033. var tags = tagsString.split(" ");
  25034. for (var t in tags) {
  25035. Tags._RemoveTagFrom(obj, tags[t]);
  25036. }
  25037. };
  25038. Tags._RemoveTagFrom = function (obj, tag) {
  25039. delete obj._tags[tag];
  25040. };
  25041. Tags.MatchesQuery = function (obj, tagsQuery) {
  25042. if (tagsQuery === undefined) {
  25043. return true;
  25044. }
  25045. if (tagsQuery === "") {
  25046. return Tags.HasTags(obj);
  25047. }
  25048. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25049. };
  25050. return Tags;
  25051. })();
  25052. BABYLON.Tags = Tags;
  25053. })(BABYLON || (BABYLON = {}));
  25054. //# sourceMappingURL=babylon.tags.js.map
  25055. var BABYLON;
  25056. (function (BABYLON) {
  25057. var Internals;
  25058. (function (Internals) {
  25059. var AndOrNotEvaluator = (function () {
  25060. function AndOrNotEvaluator() {
  25061. }
  25062. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25063. if (!query.match(/\([^\(\)]*\)/g)) {
  25064. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25065. }
  25066. else {
  25067. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25068. // remove parenthesis
  25069. r = r.slice(1, r.length - 1);
  25070. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25071. });
  25072. }
  25073. if (query === "true") {
  25074. return true;
  25075. }
  25076. if (query === "false") {
  25077. return false;
  25078. }
  25079. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  25080. };
  25081. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  25082. evaluateCallback = evaluateCallback || (function (r) {
  25083. return r === "true" ? true : false;
  25084. });
  25085. var result;
  25086. var or = parenthesisContent.split("||");
  25087. for (var i in or) {
  25088. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  25089. var and = ori.split("&&");
  25090. if (and.length > 1) {
  25091. for (var j = 0; j < and.length; ++j) {
  25092. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  25093. if (andj !== "true" && andj !== "false") {
  25094. if (andj[0] === "!") {
  25095. result = !evaluateCallback(andj.substring(1));
  25096. }
  25097. else {
  25098. result = evaluateCallback(andj);
  25099. }
  25100. }
  25101. else {
  25102. result = andj === "true" ? true : false;
  25103. }
  25104. if (!result) {
  25105. ori = "false";
  25106. break;
  25107. }
  25108. }
  25109. }
  25110. if (result || ori === "true") {
  25111. result = true;
  25112. break;
  25113. }
  25114. // result equals false (or undefined)
  25115. if (ori !== "true" && ori !== "false") {
  25116. if (ori[0] === "!") {
  25117. result = !evaluateCallback(ori.substring(1));
  25118. }
  25119. else {
  25120. result = evaluateCallback(ori);
  25121. }
  25122. }
  25123. else {
  25124. result = ori === "true" ? true : false;
  25125. }
  25126. }
  25127. // the whole parenthesis scope is replaced by 'true' or 'false'
  25128. return result ? "true" : "false";
  25129. };
  25130. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  25131. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  25132. // remove whitespaces
  25133. r = r.replace(/[\s]/g, function () { return ""; });
  25134. return r.length % 2 ? "!" : "";
  25135. });
  25136. booleanString = booleanString.trim();
  25137. if (booleanString === "!true") {
  25138. booleanString = "false";
  25139. }
  25140. else if (booleanString === "!false") {
  25141. booleanString = "true";
  25142. }
  25143. return booleanString;
  25144. };
  25145. return AndOrNotEvaluator;
  25146. })();
  25147. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  25148. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25149. })(BABYLON || (BABYLON = {}));
  25150. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  25151. var BABYLON;
  25152. (function (BABYLON) {
  25153. var PostProcessRenderPass = (function () {
  25154. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  25155. this._enabled = true;
  25156. this._refCount = 0;
  25157. this._name = name;
  25158. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  25159. this.setRenderList(renderList);
  25160. this._renderTexture.onBeforeRender = beforeRender;
  25161. this._renderTexture.onAfterRender = afterRender;
  25162. this._scene = scene;
  25163. this._renderList = renderList;
  25164. }
  25165. // private
  25166. PostProcessRenderPass.prototype._incRefCount = function () {
  25167. if (this._refCount === 0) {
  25168. this._scene.customRenderTargets.push(this._renderTexture);
  25169. }
  25170. return ++this._refCount;
  25171. };
  25172. PostProcessRenderPass.prototype._decRefCount = function () {
  25173. this._refCount--;
  25174. if (this._refCount <= 0) {
  25175. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  25176. }
  25177. return this._refCount;
  25178. };
  25179. PostProcessRenderPass.prototype._update = function () {
  25180. this.setRenderList(this._renderList);
  25181. };
  25182. // public
  25183. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  25184. this._renderTexture.renderList = renderList;
  25185. };
  25186. PostProcessRenderPass.prototype.getRenderTexture = function () {
  25187. return this._renderTexture;
  25188. };
  25189. return PostProcessRenderPass;
  25190. })();
  25191. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  25192. })(BABYLON || (BABYLON = {}));
  25193. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  25194. var BABYLON;
  25195. (function (BABYLON) {
  25196. var PostProcessRenderEffect = (function () {
  25197. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  25198. this._engine = engine;
  25199. this._name = name;
  25200. this._singleInstance = singleInstance || true;
  25201. this._getPostProcess = getPostProcess;
  25202. this._cameras = [];
  25203. this._indicesForCamera = [];
  25204. this._postProcesses = {};
  25205. this._renderPasses = {};
  25206. this._renderEffectAsPasses = {};
  25207. }
  25208. PostProcessRenderEffect.prototype._update = function () {
  25209. for (var renderPassName in this._renderPasses) {
  25210. this._renderPasses[renderPassName]._update();
  25211. }
  25212. };
  25213. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  25214. this._renderPasses[renderPass._name] = renderPass;
  25215. this._linkParameters();
  25216. };
  25217. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  25218. delete this._renderPasses[renderPass._name];
  25219. this._linkParameters();
  25220. };
  25221. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  25222. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  25223. this._linkParameters();
  25224. };
  25225. PostProcessRenderEffect.prototype.getPass = function (passName) {
  25226. for (var renderPassName in this._renderPasses) {
  25227. if (renderPassName === passName) {
  25228. return this._renderPasses[passName];
  25229. }
  25230. }
  25231. };
  25232. PostProcessRenderEffect.prototype.emptyPasses = function () {
  25233. this._renderPasses = {};
  25234. this._linkParameters();
  25235. };
  25236. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  25237. var cameraKey;
  25238. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25239. for (var i = 0; i < _cam.length; i++) {
  25240. var camera = _cam[i];
  25241. var cameraName = camera.name;
  25242. if (this._singleInstance) {
  25243. cameraKey = 0;
  25244. }
  25245. else {
  25246. cameraKey = cameraName;
  25247. }
  25248. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  25249. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  25250. if (!this._indicesForCamera[cameraName]) {
  25251. this._indicesForCamera[cameraName] = [];
  25252. }
  25253. this._indicesForCamera[cameraName].push(index);
  25254. if (this._cameras.indexOf(camera) === -1) {
  25255. this._cameras[cameraName] = camera;
  25256. }
  25257. for (var passName in this._renderPasses) {
  25258. this._renderPasses[passName]._incRefCount();
  25259. }
  25260. }
  25261. this._linkParameters();
  25262. };
  25263. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  25264. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25265. for (var i = 0; i < _cam.length; i++) {
  25266. var camera = _cam[i];
  25267. var cameraName = camera.name;
  25268. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25269. var index = this._cameras.indexOf(cameraName);
  25270. this._indicesForCamera.splice(index, 1);
  25271. this._cameras.splice(index, 1);
  25272. for (var passName in this._renderPasses) {
  25273. this._renderPasses[passName]._decRefCount();
  25274. }
  25275. }
  25276. };
  25277. PostProcessRenderEffect.prototype._enable = function (cameras) {
  25278. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25279. for (var i = 0; i < _cam.length; i++) {
  25280. var camera = _cam[i];
  25281. var cameraName = camera.name;
  25282. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  25283. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  25284. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  25285. }
  25286. }
  25287. for (var passName in this._renderPasses) {
  25288. this._renderPasses[passName]._incRefCount();
  25289. }
  25290. }
  25291. };
  25292. PostProcessRenderEffect.prototype._disable = function (cameras) {
  25293. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25294. for (var i = 0; i < _cam.length; i++) {
  25295. var camera = _cam[i];
  25296. var cameraName = camera.Name;
  25297. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25298. for (var passName in this._renderPasses) {
  25299. this._renderPasses[passName]._decRefCount();
  25300. }
  25301. }
  25302. };
  25303. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  25304. if (this._singleInstance) {
  25305. return this._postProcesses[0];
  25306. }
  25307. else {
  25308. return this._postProcesses[camera.name];
  25309. }
  25310. };
  25311. PostProcessRenderEffect.prototype._linkParameters = function () {
  25312. var _this = this;
  25313. for (var index in this._postProcesses) {
  25314. if (this.applyParameters) {
  25315. this.applyParameters(this._postProcesses[index]);
  25316. }
  25317. this._postProcesses[index].onBeforeRender = function (effect) {
  25318. _this._linkTextures(effect);
  25319. };
  25320. }
  25321. };
  25322. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  25323. for (var renderPassName in this._renderPasses) {
  25324. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  25325. }
  25326. for (var renderEffectName in this._renderEffectAsPasses) {
  25327. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  25328. }
  25329. };
  25330. return PostProcessRenderEffect;
  25331. })();
  25332. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  25333. })(BABYLON || (BABYLON = {}));
  25334. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  25335. var BABYLON;
  25336. (function (BABYLON) {
  25337. var PostProcessRenderPipeline = (function () {
  25338. function PostProcessRenderPipeline(engine, name) {
  25339. this._engine = engine;
  25340. this._name = name;
  25341. this._renderEffects = {};
  25342. this._renderEffectsForIsolatedPass = {};
  25343. this._cameras = [];
  25344. }
  25345. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  25346. this._renderEffects[renderEffect._name] = renderEffect;
  25347. };
  25348. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  25349. var renderEffects = this._renderEffects[renderEffectName];
  25350. if (!renderEffects) {
  25351. return;
  25352. }
  25353. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25354. };
  25355. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  25356. var renderEffects = this._renderEffects[renderEffectName];
  25357. if (!renderEffects) {
  25358. return;
  25359. }
  25360. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25361. };
  25362. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  25363. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25364. var indicesToDelete = [];
  25365. for (var i = 0; i < _cam.length; i++) {
  25366. var camera = _cam[i];
  25367. var cameraName = camera.name;
  25368. if (this._cameras.indexOf(camera) === -1) {
  25369. this._cameras[cameraName] = camera;
  25370. }
  25371. else if (unique) {
  25372. indicesToDelete.push(i);
  25373. }
  25374. }
  25375. for (var i = 0; i < indicesToDelete.length; i++) {
  25376. cameras.splice(indicesToDelete[i], 1);
  25377. }
  25378. for (var renderEffectName in this._renderEffects) {
  25379. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25380. }
  25381. };
  25382. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25383. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25384. for (var renderEffectName in this._renderEffects) {
  25385. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25386. }
  25387. for (var i = 0; i < _cam.length; i++) {
  25388. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25389. }
  25390. };
  25391. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25392. var _this = this;
  25393. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25394. var pass = null;
  25395. for (var renderEffectName in this._renderEffects) {
  25396. pass = this._renderEffects[renderEffectName].getPass(passName);
  25397. if (pass != null) {
  25398. break;
  25399. }
  25400. }
  25401. if (pass === null) {
  25402. return;
  25403. }
  25404. for (var renderEffectName in this._renderEffects) {
  25405. this._renderEffects[renderEffectName]._disable(_cam);
  25406. }
  25407. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25408. for (var i = 0; i < _cam.length; i++) {
  25409. var camera = _cam[i];
  25410. var cameraName = camera.name;
  25411. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  25412. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  25413. });
  25414. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25415. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25416. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25417. }
  25418. };
  25419. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25420. var _this = this;
  25421. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25422. for (var i = 0; i < _cam.length; i++) {
  25423. var camera = _cam[i];
  25424. var cameraName = camera.name;
  25425. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  25426. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  25427. });
  25428. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25429. }
  25430. for (var renderEffectName in this._renderEffects) {
  25431. this._renderEffects[renderEffectName]._enable(_cam);
  25432. }
  25433. };
  25434. PostProcessRenderPipeline.prototype._update = function () {
  25435. for (var renderEffectName in this._renderEffects) {
  25436. this._renderEffects[renderEffectName]._update();
  25437. }
  25438. for (var i = 0; i < this._cameras.length; i++) {
  25439. var cameraName = this._cameras[i].name;
  25440. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25441. this._renderEffectsForIsolatedPass[cameraName]._update();
  25442. }
  25443. }
  25444. };
  25445. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25446. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25447. return PostProcessRenderPipeline;
  25448. })();
  25449. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25450. })(BABYLON || (BABYLON = {}));
  25451. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  25452. var BABYLON;
  25453. (function (BABYLON) {
  25454. var PostProcessRenderPipelineManager = (function () {
  25455. function PostProcessRenderPipelineManager() {
  25456. this._renderPipelines = {};
  25457. }
  25458. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25459. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25460. };
  25461. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25462. var renderPipeline = this._renderPipelines[renderPipelineName];
  25463. if (!renderPipeline) {
  25464. return;
  25465. }
  25466. renderPipeline._attachCameras(cameras, unique);
  25467. };
  25468. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  25469. var renderPipeline = this._renderPipelines[renderPipelineName];
  25470. if (!renderPipeline) {
  25471. return;
  25472. }
  25473. renderPipeline._detachCameras(cameras);
  25474. };
  25475. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25476. var renderPipeline = this._renderPipelines[renderPipelineName];
  25477. if (!renderPipeline) {
  25478. return;
  25479. }
  25480. renderPipeline._enableEffect(renderEffectName, cameras);
  25481. };
  25482. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25483. var renderPipeline = this._renderPipelines[renderPipelineName];
  25484. if (!renderPipeline) {
  25485. return;
  25486. }
  25487. renderPipeline._disableEffect(renderEffectName, cameras);
  25488. };
  25489. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  25490. var renderPipeline = this._renderPipelines[renderPipelineName];
  25491. if (!renderPipeline) {
  25492. return;
  25493. }
  25494. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  25495. };
  25496. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  25497. var renderPipeline = this._renderPipelines[renderPipelineName];
  25498. if (!renderPipeline) {
  25499. return;
  25500. }
  25501. renderPipeline._disableDisplayOnlyPass(cameras);
  25502. };
  25503. PostProcessRenderPipelineManager.prototype.update = function () {
  25504. for (var renderPipelineName in this._renderPipelines) {
  25505. this._renderPipelines[renderPipelineName]._update();
  25506. }
  25507. };
  25508. return PostProcessRenderPipelineManager;
  25509. })();
  25510. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25511. })(BABYLON || (BABYLON = {}));
  25512. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  25513. var __extends = this.__extends || function (d, b) {
  25514. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25515. function __() { this.constructor = d; }
  25516. __.prototype = b.prototype;
  25517. d.prototype = new __();
  25518. };
  25519. var BABYLON;
  25520. (function (BABYLON) {
  25521. var DisplayPassPostProcess = (function (_super) {
  25522. __extends(DisplayPassPostProcess, _super);
  25523. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  25524. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  25525. }
  25526. return DisplayPassPostProcess;
  25527. })(BABYLON.PostProcess);
  25528. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  25529. })(BABYLON || (BABYLON = {}));
  25530. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  25531. var BABYLON;
  25532. (function (BABYLON) {
  25533. var BoundingBoxRenderer = (function () {
  25534. function BoundingBoxRenderer(scene) {
  25535. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25536. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25537. this.showBackLines = true;
  25538. this.renderList = new BABYLON.SmartArray(32);
  25539. this._scene = scene;
  25540. }
  25541. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25542. if (this._colorShader) {
  25543. return;
  25544. }
  25545. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25546. attributes: ["position"],
  25547. uniforms: ["worldViewProjection", "color"]
  25548. });
  25549. var engine = this._scene.getEngine();
  25550. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25551. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25552. 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]);
  25553. };
  25554. BoundingBoxRenderer.prototype.reset = function () {
  25555. this.renderList.reset();
  25556. };
  25557. BoundingBoxRenderer.prototype.render = function () {
  25558. if (this.renderList.length === 0) {
  25559. return;
  25560. }
  25561. this._prepareRessources();
  25562. if (!this._colorShader.isReady()) {
  25563. return;
  25564. }
  25565. var engine = this._scene.getEngine();
  25566. engine.setDepthWrite(false);
  25567. this._colorShader._preBind();
  25568. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25569. var boundingBox = this.renderList.data[boundingBoxIndex];
  25570. var min = boundingBox.minimum;
  25571. var max = boundingBox.maximum;
  25572. var diff = max.subtract(min);
  25573. var median = min.add(diff.scale(0.5));
  25574. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  25575. // VBOs
  25576. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25577. if (this.showBackLines) {
  25578. // Back
  25579. engine.setDepthFunctionToGreaterOrEqual();
  25580. this._scene.resetCachedMaterial();
  25581. this._colorShader.setColor4("color", this.backColor.toColor4());
  25582. this._colorShader.bind(worldMatrix);
  25583. // Draw order
  25584. engine.draw(false, 0, 24);
  25585. }
  25586. // Front
  25587. engine.setDepthFunctionToLess();
  25588. this._scene.resetCachedMaterial();
  25589. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25590. this._colorShader.bind(worldMatrix);
  25591. // Draw order
  25592. engine.draw(false, 0, 24);
  25593. }
  25594. this._colorShader.unbind();
  25595. engine.setDepthFunctionToLessOrEqual();
  25596. engine.setDepthWrite(true);
  25597. };
  25598. BoundingBoxRenderer.prototype.dispose = function () {
  25599. if (!this._colorShader) {
  25600. return;
  25601. }
  25602. this._colorShader.dispose();
  25603. this._vb.dispose();
  25604. this._scene.getEngine()._releaseBuffer(this._ib);
  25605. };
  25606. return BoundingBoxRenderer;
  25607. })();
  25608. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25609. })(BABYLON || (BABYLON = {}));
  25610. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  25611. var __extends = this.__extends || function (d, b) {
  25612. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25613. function __() { this.constructor = d; }
  25614. __.prototype = b.prototype;
  25615. d.prototype = new __();
  25616. };
  25617. var BABYLON;
  25618. (function (BABYLON) {
  25619. var Condition = (function () {
  25620. function Condition(actionManager) {
  25621. this._actionManager = actionManager;
  25622. }
  25623. Condition.prototype.isValid = function () {
  25624. return true;
  25625. };
  25626. Condition.prototype._getProperty = function (propertyPath) {
  25627. return this._actionManager._getProperty(propertyPath);
  25628. };
  25629. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25630. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25631. };
  25632. return Condition;
  25633. })();
  25634. BABYLON.Condition = Condition;
  25635. var ValueCondition = (function (_super) {
  25636. __extends(ValueCondition, _super);
  25637. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25638. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25639. _super.call(this, actionManager);
  25640. this.propertyPath = propertyPath;
  25641. this.value = value;
  25642. this.operator = operator;
  25643. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25644. this._property = this._getProperty(this.propertyPath);
  25645. }
  25646. Object.defineProperty(ValueCondition, "IsEqual", {
  25647. get: function () {
  25648. return ValueCondition._IsEqual;
  25649. },
  25650. enumerable: true,
  25651. configurable: true
  25652. });
  25653. Object.defineProperty(ValueCondition, "IsDifferent", {
  25654. get: function () {
  25655. return ValueCondition._IsDifferent;
  25656. },
  25657. enumerable: true,
  25658. configurable: true
  25659. });
  25660. Object.defineProperty(ValueCondition, "IsGreater", {
  25661. get: function () {
  25662. return ValueCondition._IsGreater;
  25663. },
  25664. enumerable: true,
  25665. configurable: true
  25666. });
  25667. Object.defineProperty(ValueCondition, "IsLesser", {
  25668. get: function () {
  25669. return ValueCondition._IsLesser;
  25670. },
  25671. enumerable: true,
  25672. configurable: true
  25673. });
  25674. // Methods
  25675. ValueCondition.prototype.isValid = function () {
  25676. switch (this.operator) {
  25677. case ValueCondition.IsGreater:
  25678. return this._target[this._property] > this.value;
  25679. case ValueCondition.IsLesser:
  25680. return this._target[this._property] < this.value;
  25681. case ValueCondition.IsEqual:
  25682. case ValueCondition.IsDifferent:
  25683. var check;
  25684. if (this.value.equals) {
  25685. check = this.value.equals(this._target[this._property]);
  25686. }
  25687. else {
  25688. check = this.value === this._target[this._property];
  25689. }
  25690. return this.operator === ValueCondition.IsEqual ? check : !check;
  25691. }
  25692. return false;
  25693. };
  25694. // Statics
  25695. ValueCondition._IsEqual = 0;
  25696. ValueCondition._IsDifferent = 1;
  25697. ValueCondition._IsGreater = 2;
  25698. ValueCondition._IsLesser = 3;
  25699. return ValueCondition;
  25700. })(Condition);
  25701. BABYLON.ValueCondition = ValueCondition;
  25702. var PredicateCondition = (function (_super) {
  25703. __extends(PredicateCondition, _super);
  25704. function PredicateCondition(actionManager, predicate) {
  25705. _super.call(this, actionManager);
  25706. this.predicate = predicate;
  25707. }
  25708. PredicateCondition.prototype.isValid = function () {
  25709. return this.predicate();
  25710. };
  25711. return PredicateCondition;
  25712. })(Condition);
  25713. BABYLON.PredicateCondition = PredicateCondition;
  25714. var StateCondition = (function (_super) {
  25715. __extends(StateCondition, _super);
  25716. function StateCondition(actionManager, target, value) {
  25717. _super.call(this, actionManager);
  25718. this.value = value;
  25719. this._target = target;
  25720. }
  25721. // Methods
  25722. StateCondition.prototype.isValid = function () {
  25723. return this._target.state === this.value;
  25724. };
  25725. return StateCondition;
  25726. })(Condition);
  25727. BABYLON.StateCondition = StateCondition;
  25728. })(BABYLON || (BABYLON = {}));
  25729. //# sourceMappingURL=babylon.condition.js.map
  25730. var BABYLON;
  25731. (function (BABYLON) {
  25732. var Action = (function () {
  25733. function Action(triggerOptions, condition) {
  25734. this.triggerOptions = triggerOptions;
  25735. if (triggerOptions.parameter) {
  25736. this.trigger = triggerOptions.trigger;
  25737. this._triggerParameter = triggerOptions.parameter;
  25738. }
  25739. else {
  25740. this.trigger = triggerOptions;
  25741. }
  25742. this._nextActiveAction = this;
  25743. this._condition = condition;
  25744. }
  25745. // Methods
  25746. Action.prototype._prepare = function () {
  25747. };
  25748. Action.prototype.getTriggerParameter = function () {
  25749. return this._triggerParameter;
  25750. };
  25751. Action.prototype._executeCurrent = function (evt) {
  25752. if (this._nextActiveAction._condition) {
  25753. var condition = this._nextActiveAction._condition;
  25754. var currentRenderId = this._actionManager.getScene().getRenderId();
  25755. // We cache the current evaluation for the current frame
  25756. if (condition._evaluationId === currentRenderId) {
  25757. if (!condition._currentResult) {
  25758. return;
  25759. }
  25760. }
  25761. else {
  25762. condition._evaluationId = currentRenderId;
  25763. if (!condition.isValid()) {
  25764. condition._currentResult = false;
  25765. return;
  25766. }
  25767. condition._currentResult = true;
  25768. }
  25769. }
  25770. this._nextActiveAction.execute(evt);
  25771. if (this._nextActiveAction._child) {
  25772. if (!this._nextActiveAction._child._actionManager) {
  25773. this._nextActiveAction._child._actionManager = this._actionManager;
  25774. }
  25775. this._nextActiveAction = this._nextActiveAction._child;
  25776. }
  25777. else {
  25778. this._nextActiveAction = this;
  25779. }
  25780. };
  25781. Action.prototype.execute = function (evt) {
  25782. };
  25783. Action.prototype.then = function (action) {
  25784. this._child = action;
  25785. action._actionManager = this._actionManager;
  25786. action._prepare();
  25787. return action;
  25788. };
  25789. Action.prototype._getProperty = function (propertyPath) {
  25790. return this._actionManager._getProperty(propertyPath);
  25791. };
  25792. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25793. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25794. };
  25795. return Action;
  25796. })();
  25797. BABYLON.Action = Action;
  25798. })(BABYLON || (BABYLON = {}));
  25799. //# sourceMappingURL=babylon.action.js.map
  25800. var BABYLON;
  25801. (function (BABYLON) {
  25802. /**
  25803. * ActionEvent is the event beint sent when an action is triggered.
  25804. */
  25805. var ActionEvent = (function () {
  25806. /**
  25807. * @constructor
  25808. * @param source The mesh that triggered the action.
  25809. * @param pointerX the X mouse cursor position at the time of the event
  25810. * @param pointerY the Y mouse cursor position at the time of the event
  25811. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25812. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25813. */
  25814. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  25815. this.source = source;
  25816. this.pointerX = pointerX;
  25817. this.pointerY = pointerY;
  25818. this.meshUnderPointer = meshUnderPointer;
  25819. this.sourceEvent = sourceEvent;
  25820. }
  25821. /**
  25822. * Helper function to auto-create an ActionEvent from a source mesh.
  25823. * @param source the source mesh that triggered the event
  25824. * @param evt {Event} The original (browser) event
  25825. */
  25826. ActionEvent.CreateNew = function (source, evt) {
  25827. var scene = source.getScene();
  25828. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25829. };
  25830. /**
  25831. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25832. * @param scene the scene where the event occurred
  25833. * @param evt {Event} The original (browser) event
  25834. */
  25835. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25836. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25837. };
  25838. return ActionEvent;
  25839. })();
  25840. BABYLON.ActionEvent = ActionEvent;
  25841. /**
  25842. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25843. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25844. */
  25845. var ActionManager = (function () {
  25846. function ActionManager(scene) {
  25847. // Members
  25848. this.actions = new Array();
  25849. this._scene = scene;
  25850. scene._actionManagers.push(this);
  25851. }
  25852. Object.defineProperty(ActionManager, "NothingTrigger", {
  25853. get: function () {
  25854. return ActionManager._NothingTrigger;
  25855. },
  25856. enumerable: true,
  25857. configurable: true
  25858. });
  25859. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25860. get: function () {
  25861. return ActionManager._OnPickTrigger;
  25862. },
  25863. enumerable: true,
  25864. configurable: true
  25865. });
  25866. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25867. get: function () {
  25868. return ActionManager._OnLeftPickTrigger;
  25869. },
  25870. enumerable: true,
  25871. configurable: true
  25872. });
  25873. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25874. get: function () {
  25875. return ActionManager._OnRightPickTrigger;
  25876. },
  25877. enumerable: true,
  25878. configurable: true
  25879. });
  25880. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25881. get: function () {
  25882. return ActionManager._OnCenterPickTrigger;
  25883. },
  25884. enumerable: true,
  25885. configurable: true
  25886. });
  25887. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25888. get: function () {
  25889. return ActionManager._OnPointerOverTrigger;
  25890. },
  25891. enumerable: true,
  25892. configurable: true
  25893. });
  25894. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25895. get: function () {
  25896. return ActionManager._OnPointerOutTrigger;
  25897. },
  25898. enumerable: true,
  25899. configurable: true
  25900. });
  25901. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25902. get: function () {
  25903. return ActionManager._OnEveryFrameTrigger;
  25904. },
  25905. enumerable: true,
  25906. configurable: true
  25907. });
  25908. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25909. get: function () {
  25910. return ActionManager._OnIntersectionEnterTrigger;
  25911. },
  25912. enumerable: true,
  25913. configurable: true
  25914. });
  25915. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25916. get: function () {
  25917. return ActionManager._OnIntersectionExitTrigger;
  25918. },
  25919. enumerable: true,
  25920. configurable: true
  25921. });
  25922. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25923. get: function () {
  25924. return ActionManager._OnKeyDownTrigger;
  25925. },
  25926. enumerable: true,
  25927. configurable: true
  25928. });
  25929. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25930. get: function () {
  25931. return ActionManager._OnKeyUpTrigger;
  25932. },
  25933. enumerable: true,
  25934. configurable: true
  25935. });
  25936. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25937. get: function () {
  25938. return ActionManager._OnPickUpTrigger;
  25939. },
  25940. enumerable: true,
  25941. configurable: true
  25942. });
  25943. // Methods
  25944. ActionManager.prototype.dispose = function () {
  25945. var index = this._scene._actionManagers.indexOf(this);
  25946. if (index > -1) {
  25947. this._scene._actionManagers.splice(index, 1);
  25948. }
  25949. };
  25950. ActionManager.prototype.getScene = function () {
  25951. return this._scene;
  25952. };
  25953. /**
  25954. * Does this action manager handles actions of any of the given triggers
  25955. * @param {number[]} triggers - the triggers to be tested
  25956. * @return {boolean} whether one (or more) of the triggers is handeled
  25957. */
  25958. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25959. for (var index = 0; index < this.actions.length; index++) {
  25960. var action = this.actions[index];
  25961. if (triggers.indexOf(action.trigger) > -1) {
  25962. return true;
  25963. }
  25964. }
  25965. return false;
  25966. };
  25967. /**
  25968. * Does this action manager handles actions of a given trigger
  25969. * @param {number} trigger - the trigger to be tested
  25970. * @return {boolean} whether the trigger is handeled
  25971. */
  25972. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25973. for (var index = 0; index < this.actions.length; index++) {
  25974. var action = this.actions[index];
  25975. if (action.trigger === trigger) {
  25976. return true;
  25977. }
  25978. }
  25979. return false;
  25980. };
  25981. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25982. /**
  25983. * Does this action manager has pointer triggers
  25984. * @return {boolean} whether or not it has pointer triggers
  25985. */
  25986. get: function () {
  25987. for (var index = 0; index < this.actions.length; index++) {
  25988. var action = this.actions[index];
  25989. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25990. return true;
  25991. }
  25992. if (action.trigger == ActionManager._OnPickUpTrigger) {
  25993. return true;
  25994. }
  25995. }
  25996. return false;
  25997. },
  25998. enumerable: true,
  25999. configurable: true
  26000. });
  26001. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  26002. /**
  26003. * Does this action manager has pick triggers
  26004. * @return {boolean} whether or not it has pick triggers
  26005. */
  26006. get: function () {
  26007. for (var index = 0; index < this.actions.length; index++) {
  26008. var action = this.actions[index];
  26009. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  26010. return true;
  26011. }
  26012. }
  26013. return false;
  26014. },
  26015. enumerable: true,
  26016. configurable: true
  26017. });
  26018. /**
  26019. * Registers an action to this action manager
  26020. * @param {BABYLON.Action} action - the action to be registered
  26021. * @return {BABYLON.Action} the action amended (prepared) after registration
  26022. */
  26023. ActionManager.prototype.registerAction = function (action) {
  26024. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26025. if (this.getScene().actionManager !== this) {
  26026. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26027. return null;
  26028. }
  26029. }
  26030. this.actions.push(action);
  26031. action._actionManager = this;
  26032. action._prepare();
  26033. return action;
  26034. };
  26035. /**
  26036. * Process a specific trigger
  26037. * @param {number} trigger - the trigger to process
  26038. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26039. */
  26040. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26041. for (var index = 0; index < this.actions.length; index++) {
  26042. var action = this.actions[index];
  26043. if (action.trigger === trigger) {
  26044. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  26045. var parameter = action.getTriggerParameter();
  26046. if (parameter) {
  26047. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26048. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26049. if (actualkey !== parameter.toLowerCase()) {
  26050. continue;
  26051. }
  26052. }
  26053. }
  26054. action._executeCurrent(evt);
  26055. }
  26056. }
  26057. };
  26058. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26059. var properties = propertyPath.split(".");
  26060. for (var index = 0; index < properties.length - 1; index++) {
  26061. target = target[properties[index]];
  26062. }
  26063. return target;
  26064. };
  26065. ActionManager.prototype._getProperty = function (propertyPath) {
  26066. var properties = propertyPath.split(".");
  26067. return properties[properties.length - 1];
  26068. };
  26069. // Statics
  26070. ActionManager._NothingTrigger = 0;
  26071. ActionManager._OnPickTrigger = 1;
  26072. ActionManager._OnLeftPickTrigger = 2;
  26073. ActionManager._OnRightPickTrigger = 3;
  26074. ActionManager._OnCenterPickTrigger = 4;
  26075. ActionManager._OnPointerOverTrigger = 5;
  26076. ActionManager._OnPointerOutTrigger = 6;
  26077. ActionManager._OnEveryFrameTrigger = 7;
  26078. ActionManager._OnIntersectionEnterTrigger = 8;
  26079. ActionManager._OnIntersectionExitTrigger = 9;
  26080. ActionManager._OnKeyDownTrigger = 10;
  26081. ActionManager._OnKeyUpTrigger = 11;
  26082. ActionManager._OnPickUpTrigger = 12;
  26083. return ActionManager;
  26084. })();
  26085. BABYLON.ActionManager = ActionManager;
  26086. })(BABYLON || (BABYLON = {}));
  26087. //# sourceMappingURL=babylon.actionManager.js.map
  26088. var __extends = this.__extends || function (d, b) {
  26089. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26090. function __() { this.constructor = d; }
  26091. __.prototype = b.prototype;
  26092. d.prototype = new __();
  26093. };
  26094. var BABYLON;
  26095. (function (BABYLON) {
  26096. var InterpolateValueAction = (function (_super) {
  26097. __extends(InterpolateValueAction, _super);
  26098. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  26099. if (duration === void 0) { duration = 1000; }
  26100. _super.call(this, triggerOptions, condition);
  26101. this.propertyPath = propertyPath;
  26102. this.value = value;
  26103. this.duration = duration;
  26104. this.stopOtherAnimations = stopOtherAnimations;
  26105. this._target = target;
  26106. }
  26107. InterpolateValueAction.prototype._prepare = function () {
  26108. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26109. this._property = this._getProperty(this.propertyPath);
  26110. };
  26111. InterpolateValueAction.prototype.execute = function () {
  26112. var scene = this._actionManager.getScene();
  26113. var keys = [
  26114. {
  26115. frame: 0,
  26116. value: this._target[this._property]
  26117. },
  26118. {
  26119. frame: 100,
  26120. value: this.value
  26121. }
  26122. ];
  26123. var dataType;
  26124. if (typeof this.value === "number") {
  26125. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  26126. }
  26127. else if (this.value instanceof BABYLON.Color3) {
  26128. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  26129. }
  26130. else if (this.value instanceof BABYLON.Vector3) {
  26131. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  26132. }
  26133. else if (this.value instanceof BABYLON.Matrix) {
  26134. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  26135. }
  26136. else if (this.value instanceof BABYLON.Quaternion) {
  26137. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  26138. }
  26139. else {
  26140. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  26141. return;
  26142. }
  26143. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  26144. animation.setKeys(keys);
  26145. if (this.stopOtherAnimations) {
  26146. scene.stopAnimation(this._target);
  26147. }
  26148. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  26149. };
  26150. return InterpolateValueAction;
  26151. })(BABYLON.Action);
  26152. BABYLON.InterpolateValueAction = InterpolateValueAction;
  26153. })(BABYLON || (BABYLON = {}));
  26154. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  26155. var __extends = this.__extends || function (d, b) {
  26156. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26157. function __() { this.constructor = d; }
  26158. __.prototype = b.prototype;
  26159. d.prototype = new __();
  26160. };
  26161. var BABYLON;
  26162. (function (BABYLON) {
  26163. var SwitchBooleanAction = (function (_super) {
  26164. __extends(SwitchBooleanAction, _super);
  26165. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  26166. _super.call(this, triggerOptions, condition);
  26167. this.propertyPath = propertyPath;
  26168. this._target = target;
  26169. }
  26170. SwitchBooleanAction.prototype._prepare = function () {
  26171. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26172. this._property = this._getProperty(this.propertyPath);
  26173. };
  26174. SwitchBooleanAction.prototype.execute = function () {
  26175. this._target[this._property] = !this._target[this._property];
  26176. };
  26177. return SwitchBooleanAction;
  26178. })(BABYLON.Action);
  26179. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  26180. var SetStateAction = (function (_super) {
  26181. __extends(SetStateAction, _super);
  26182. function SetStateAction(triggerOptions, target, value, condition) {
  26183. _super.call(this, triggerOptions, condition);
  26184. this.value = value;
  26185. this._target = target;
  26186. }
  26187. SetStateAction.prototype.execute = function () {
  26188. this._target.state = this.value;
  26189. };
  26190. return SetStateAction;
  26191. })(BABYLON.Action);
  26192. BABYLON.SetStateAction = SetStateAction;
  26193. var SetValueAction = (function (_super) {
  26194. __extends(SetValueAction, _super);
  26195. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  26196. _super.call(this, triggerOptions, condition);
  26197. this.propertyPath = propertyPath;
  26198. this.value = value;
  26199. this._target = target;
  26200. }
  26201. SetValueAction.prototype._prepare = function () {
  26202. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26203. this._property = this._getProperty(this.propertyPath);
  26204. };
  26205. SetValueAction.prototype.execute = function () {
  26206. this._target[this._property] = this.value;
  26207. };
  26208. return SetValueAction;
  26209. })(BABYLON.Action);
  26210. BABYLON.SetValueAction = SetValueAction;
  26211. var IncrementValueAction = (function (_super) {
  26212. __extends(IncrementValueAction, _super);
  26213. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  26214. _super.call(this, triggerOptions, condition);
  26215. this.propertyPath = propertyPath;
  26216. this.value = value;
  26217. this._target = target;
  26218. }
  26219. IncrementValueAction.prototype._prepare = function () {
  26220. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26221. this._property = this._getProperty(this.propertyPath);
  26222. if (typeof this._target[this._property] !== "number") {
  26223. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  26224. }
  26225. };
  26226. IncrementValueAction.prototype.execute = function () {
  26227. this._target[this._property] += this.value;
  26228. };
  26229. return IncrementValueAction;
  26230. })(BABYLON.Action);
  26231. BABYLON.IncrementValueAction = IncrementValueAction;
  26232. var PlayAnimationAction = (function (_super) {
  26233. __extends(PlayAnimationAction, _super);
  26234. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  26235. _super.call(this, triggerOptions, condition);
  26236. this.from = from;
  26237. this.to = to;
  26238. this.loop = loop;
  26239. this._target = target;
  26240. }
  26241. PlayAnimationAction.prototype._prepare = function () {
  26242. };
  26243. PlayAnimationAction.prototype.execute = function () {
  26244. var scene = this._actionManager.getScene();
  26245. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  26246. };
  26247. return PlayAnimationAction;
  26248. })(BABYLON.Action);
  26249. BABYLON.PlayAnimationAction = PlayAnimationAction;
  26250. var StopAnimationAction = (function (_super) {
  26251. __extends(StopAnimationAction, _super);
  26252. function StopAnimationAction(triggerOptions, target, condition) {
  26253. _super.call(this, triggerOptions, condition);
  26254. this._target = target;
  26255. }
  26256. StopAnimationAction.prototype._prepare = function () {
  26257. };
  26258. StopAnimationAction.prototype.execute = function () {
  26259. var scene = this._actionManager.getScene();
  26260. scene.stopAnimation(this._target);
  26261. };
  26262. return StopAnimationAction;
  26263. })(BABYLON.Action);
  26264. BABYLON.StopAnimationAction = StopAnimationAction;
  26265. var DoNothingAction = (function (_super) {
  26266. __extends(DoNothingAction, _super);
  26267. function DoNothingAction(triggerOptions, condition) {
  26268. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  26269. _super.call(this, triggerOptions, condition);
  26270. }
  26271. DoNothingAction.prototype.execute = function () {
  26272. };
  26273. return DoNothingAction;
  26274. })(BABYLON.Action);
  26275. BABYLON.DoNothingAction = DoNothingAction;
  26276. var CombineAction = (function (_super) {
  26277. __extends(CombineAction, _super);
  26278. function CombineAction(triggerOptions, children, condition) {
  26279. _super.call(this, triggerOptions, condition);
  26280. this.children = children;
  26281. }
  26282. CombineAction.prototype._prepare = function () {
  26283. for (var index = 0; index < this.children.length; index++) {
  26284. this.children[index]._actionManager = this._actionManager;
  26285. this.children[index]._prepare();
  26286. }
  26287. };
  26288. CombineAction.prototype.execute = function (evt) {
  26289. for (var index = 0; index < this.children.length; index++) {
  26290. this.children[index].execute(evt);
  26291. }
  26292. };
  26293. return CombineAction;
  26294. })(BABYLON.Action);
  26295. BABYLON.CombineAction = CombineAction;
  26296. var ExecuteCodeAction = (function (_super) {
  26297. __extends(ExecuteCodeAction, _super);
  26298. function ExecuteCodeAction(triggerOptions, func, condition) {
  26299. _super.call(this, triggerOptions, condition);
  26300. this.func = func;
  26301. }
  26302. ExecuteCodeAction.prototype.execute = function (evt) {
  26303. this.func(evt);
  26304. };
  26305. return ExecuteCodeAction;
  26306. })(BABYLON.Action);
  26307. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  26308. var SetParentAction = (function (_super) {
  26309. __extends(SetParentAction, _super);
  26310. function SetParentAction(triggerOptions, target, parent, condition) {
  26311. _super.call(this, triggerOptions, condition);
  26312. this._target = target;
  26313. this._parent = parent;
  26314. }
  26315. SetParentAction.prototype._prepare = function () {
  26316. };
  26317. SetParentAction.prototype.execute = function () {
  26318. if (this._target.parent === this._parent) {
  26319. return;
  26320. }
  26321. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  26322. invertParentWorldMatrix.invert();
  26323. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  26324. this._target.parent = this._parent;
  26325. };
  26326. return SetParentAction;
  26327. })(BABYLON.Action);
  26328. BABYLON.SetParentAction = SetParentAction;
  26329. var PlaySoundAction = (function (_super) {
  26330. __extends(PlaySoundAction, _super);
  26331. function PlaySoundAction(triggerOptions, sound, condition) {
  26332. _super.call(this, triggerOptions, condition);
  26333. this._sound = sound;
  26334. }
  26335. PlaySoundAction.prototype._prepare = function () {
  26336. };
  26337. PlaySoundAction.prototype.execute = function () {
  26338. if (this._sound !== undefined)
  26339. this._sound.play();
  26340. };
  26341. return PlaySoundAction;
  26342. })(BABYLON.Action);
  26343. BABYLON.PlaySoundAction = PlaySoundAction;
  26344. var StopSoundAction = (function (_super) {
  26345. __extends(StopSoundAction, _super);
  26346. function StopSoundAction(triggerOptions, sound, condition) {
  26347. _super.call(this, triggerOptions, condition);
  26348. this._sound = sound;
  26349. }
  26350. StopSoundAction.prototype._prepare = function () {
  26351. };
  26352. StopSoundAction.prototype.execute = function () {
  26353. if (this._sound !== undefined)
  26354. this._sound.stop();
  26355. };
  26356. return StopSoundAction;
  26357. })(BABYLON.Action);
  26358. BABYLON.StopSoundAction = StopSoundAction;
  26359. })(BABYLON || (BABYLON = {}));
  26360. //# sourceMappingURL=babylon.directActions.js.map
  26361. var __extends = this.__extends || function (d, b) {
  26362. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26363. function __() { this.constructor = d; }
  26364. __.prototype = b.prototype;
  26365. d.prototype = new __();
  26366. };
  26367. var BABYLON;
  26368. (function (BABYLON) {
  26369. var Geometry = (function () {
  26370. function Geometry(id, scene, vertexData, updatable, mesh) {
  26371. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26372. this._totalVertices = 0;
  26373. this._indices = [];
  26374. this._isDisposed = false;
  26375. this.id = id;
  26376. this._engine = scene.getEngine();
  26377. this._meshes = [];
  26378. this._scene = scene;
  26379. // vertexData
  26380. if (vertexData) {
  26381. this.setAllVerticesData(vertexData, updatable);
  26382. }
  26383. else {
  26384. this._totalVertices = 0;
  26385. this._indices = [];
  26386. }
  26387. // applyToMesh
  26388. if (mesh) {
  26389. this.applyToMesh(mesh);
  26390. mesh.computeWorldMatrix(true);
  26391. }
  26392. }
  26393. Geometry.prototype.getScene = function () {
  26394. return this._scene;
  26395. };
  26396. Geometry.prototype.getEngine = function () {
  26397. return this._engine;
  26398. };
  26399. Geometry.prototype.isReady = function () {
  26400. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26401. };
  26402. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26403. vertexData.applyToGeometry(this, updatable);
  26404. this.notifyUpdate();
  26405. };
  26406. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26407. this._vertexBuffers = this._vertexBuffers || {};
  26408. if (this._vertexBuffers[kind]) {
  26409. this._vertexBuffers[kind].dispose();
  26410. }
  26411. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26412. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26413. stride = this._vertexBuffers[kind].getStrideSize();
  26414. this._totalVertices = data.length / stride;
  26415. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26416. var meshes = this._meshes;
  26417. var numOfMeshes = meshes.length;
  26418. for (var index = 0; index < numOfMeshes; index++) {
  26419. var mesh = meshes[index];
  26420. mesh._resetPointsArrayCache();
  26421. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26422. mesh._createGlobalSubMesh();
  26423. mesh.computeWorldMatrix(true);
  26424. }
  26425. }
  26426. this.notifyUpdate(kind);
  26427. };
  26428. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26429. var vertexBuffer = this.getVertexBuffer(kind);
  26430. if (!vertexBuffer) {
  26431. return;
  26432. }
  26433. vertexBuffer.updateDirectly(data, offset);
  26434. this.notifyUpdate(kind);
  26435. };
  26436. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26437. var vertexBuffer = this.getVertexBuffer(kind);
  26438. if (!vertexBuffer) {
  26439. return;
  26440. }
  26441. vertexBuffer.update(data);
  26442. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26443. var extend;
  26444. var stride = vertexBuffer.getStrideSize();
  26445. this._totalVertices = data.length / stride;
  26446. if (updateExtends) {
  26447. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26448. }
  26449. var meshes = this._meshes;
  26450. var numOfMeshes = meshes.length;
  26451. for (var index = 0; index < numOfMeshes; index++) {
  26452. var mesh = meshes[index];
  26453. mesh._resetPointsArrayCache();
  26454. if (updateExtends) {
  26455. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26456. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26457. var subMesh = mesh.subMeshes[subIndex];
  26458. subMesh.refreshBoundingInfo();
  26459. }
  26460. }
  26461. }
  26462. }
  26463. this.notifyUpdate(kind);
  26464. };
  26465. Geometry.prototype.getTotalVertices = function () {
  26466. if (!this.isReady()) {
  26467. return 0;
  26468. }
  26469. return this._totalVertices;
  26470. };
  26471. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26472. var vertexBuffer = this.getVertexBuffer(kind);
  26473. if (!vertexBuffer) {
  26474. return null;
  26475. }
  26476. var orig = vertexBuffer.getData();
  26477. if (!copyWhenShared || this._meshes.length === 1) {
  26478. return orig;
  26479. }
  26480. else {
  26481. var len = orig.length;
  26482. var copy = [];
  26483. for (var i = 0; i < len; i++) {
  26484. copy.push(orig[i]);
  26485. }
  26486. return copy;
  26487. }
  26488. };
  26489. Geometry.prototype.getVertexBuffer = function (kind) {
  26490. if (!this.isReady()) {
  26491. return null;
  26492. }
  26493. return this._vertexBuffers[kind];
  26494. };
  26495. Geometry.prototype.getVertexBuffers = function () {
  26496. if (!this.isReady()) {
  26497. return null;
  26498. }
  26499. return this._vertexBuffers;
  26500. };
  26501. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26502. if (!this._vertexBuffers) {
  26503. if (this._delayInfo) {
  26504. return this._delayInfo.indexOf(kind) !== -1;
  26505. }
  26506. return false;
  26507. }
  26508. return this._vertexBuffers[kind] !== undefined;
  26509. };
  26510. Geometry.prototype.getVerticesDataKinds = function () {
  26511. var result = [];
  26512. if (!this._vertexBuffers && this._delayInfo) {
  26513. for (var kind in this._delayInfo) {
  26514. result.push(kind);
  26515. }
  26516. }
  26517. else {
  26518. for (kind in this._vertexBuffers) {
  26519. result.push(kind);
  26520. }
  26521. }
  26522. return result;
  26523. };
  26524. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26525. if (this._indexBuffer) {
  26526. this._engine._releaseBuffer(this._indexBuffer);
  26527. }
  26528. this._indices = indices;
  26529. if (this._meshes.length !== 0 && this._indices) {
  26530. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26531. }
  26532. if (totalVertices !== undefined) {
  26533. this._totalVertices = totalVertices;
  26534. }
  26535. var meshes = this._meshes;
  26536. var numOfMeshes = meshes.length;
  26537. for (var index = 0; index < numOfMeshes; index++) {
  26538. meshes[index]._createGlobalSubMesh();
  26539. }
  26540. this.notifyUpdate();
  26541. };
  26542. Geometry.prototype.getTotalIndices = function () {
  26543. if (!this.isReady()) {
  26544. return 0;
  26545. }
  26546. return this._indices.length;
  26547. };
  26548. Geometry.prototype.getIndices = function (copyWhenShared) {
  26549. if (!this.isReady()) {
  26550. return null;
  26551. }
  26552. var orig = this._indices;
  26553. if (!copyWhenShared || this._meshes.length === 1) {
  26554. return orig;
  26555. }
  26556. else {
  26557. var len = orig.length;
  26558. var copy = [];
  26559. for (var i = 0; i < len; i++) {
  26560. copy.push(orig[i]);
  26561. }
  26562. return copy;
  26563. }
  26564. };
  26565. Geometry.prototype.getIndexBuffer = function () {
  26566. if (!this.isReady()) {
  26567. return null;
  26568. }
  26569. return this._indexBuffer;
  26570. };
  26571. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26572. var meshes = this._meshes;
  26573. var index = meshes.indexOf(mesh);
  26574. if (index === -1) {
  26575. return;
  26576. }
  26577. for (var kind in this._vertexBuffers) {
  26578. this._vertexBuffers[kind].dispose();
  26579. }
  26580. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26581. this._indexBuffer = null;
  26582. }
  26583. meshes.splice(index, 1);
  26584. mesh._geometry = null;
  26585. if (meshes.length === 0 && shouldDispose) {
  26586. this.dispose();
  26587. }
  26588. };
  26589. Geometry.prototype.applyToMesh = function (mesh) {
  26590. if (mesh._geometry === this) {
  26591. return;
  26592. }
  26593. var previousGeometry = mesh._geometry;
  26594. if (previousGeometry) {
  26595. previousGeometry.releaseForMesh(mesh);
  26596. }
  26597. var meshes = this._meshes;
  26598. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26599. mesh._geometry = this;
  26600. this._scene.pushGeometry(this);
  26601. meshes.push(mesh);
  26602. if (this.isReady()) {
  26603. this._applyToMesh(mesh);
  26604. }
  26605. else {
  26606. mesh._boundingInfo = this._boundingInfo;
  26607. }
  26608. };
  26609. Geometry.prototype._applyToMesh = function (mesh) {
  26610. var numOfMeshes = this._meshes.length;
  26611. for (var kind in this._vertexBuffers) {
  26612. if (numOfMeshes === 1) {
  26613. this._vertexBuffers[kind].create();
  26614. }
  26615. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26616. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26617. mesh._resetPointsArrayCache();
  26618. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26619. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26620. mesh._createGlobalSubMesh();
  26621. //bounding info was just created again, world matrix should be applied again.
  26622. mesh._updateBoundingInfo();
  26623. }
  26624. }
  26625. // indexBuffer
  26626. if (numOfMeshes === 1 && this._indices) {
  26627. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26628. }
  26629. if (this._indexBuffer) {
  26630. this._indexBuffer.references = numOfMeshes;
  26631. }
  26632. };
  26633. Geometry.prototype.notifyUpdate = function (kind) {
  26634. if (this.onGeometryUpdated) {
  26635. this.onGeometryUpdated(this, kind);
  26636. }
  26637. };
  26638. Geometry.prototype.load = function (scene, onLoaded) {
  26639. var _this = this;
  26640. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26641. return;
  26642. }
  26643. if (this.isReady()) {
  26644. if (onLoaded) {
  26645. onLoaded();
  26646. }
  26647. return;
  26648. }
  26649. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26650. scene._addPendingData(this);
  26651. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26652. _this._delayLoadingFunction(JSON.parse(data), _this);
  26653. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26654. _this._delayInfo = [];
  26655. scene._removePendingData(_this);
  26656. var meshes = _this._meshes;
  26657. var numOfMeshes = meshes.length;
  26658. for (var index = 0; index < numOfMeshes; index++) {
  26659. _this._applyToMesh(meshes[index]);
  26660. }
  26661. if (onLoaded) {
  26662. onLoaded();
  26663. }
  26664. }, function () {
  26665. }, scene.database);
  26666. };
  26667. Geometry.prototype.isDisposed = function () {
  26668. return this._isDisposed;
  26669. };
  26670. Geometry.prototype.dispose = function () {
  26671. var meshes = this._meshes;
  26672. var numOfMeshes = meshes.length;
  26673. var index;
  26674. for (index = 0; index < numOfMeshes; index++) {
  26675. this.releaseForMesh(meshes[index]);
  26676. }
  26677. this._meshes = [];
  26678. for (var kind in this._vertexBuffers) {
  26679. this._vertexBuffers[kind].dispose();
  26680. }
  26681. this._vertexBuffers = [];
  26682. this._totalVertices = 0;
  26683. if (this._indexBuffer) {
  26684. this._engine._releaseBuffer(this._indexBuffer);
  26685. }
  26686. this._indexBuffer = null;
  26687. this._indices = [];
  26688. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26689. this.delayLoadingFile = null;
  26690. this._delayLoadingFunction = null;
  26691. this._delayInfo = [];
  26692. this._boundingInfo = null; // todo: .dispose()
  26693. this._scene.removeGeometry(this);
  26694. this._isDisposed = true;
  26695. };
  26696. Geometry.prototype.copy = function (id) {
  26697. var vertexData = new BABYLON.VertexData();
  26698. vertexData.indices = [];
  26699. var indices = this.getIndices();
  26700. for (var index = 0; index < indices.length; index++) {
  26701. vertexData.indices.push(indices[index]);
  26702. }
  26703. var updatable = false;
  26704. var stopChecking = false;
  26705. for (var kind in this._vertexBuffers) {
  26706. // using slice() to make a copy of the array and not just reference it
  26707. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  26708. if (!stopChecking) {
  26709. updatable = this.getVertexBuffer(kind).isUpdatable();
  26710. stopChecking = !updatable;
  26711. }
  26712. }
  26713. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26714. geometry.delayLoadState = this.delayLoadState;
  26715. geometry.delayLoadingFile = this.delayLoadingFile;
  26716. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26717. for (kind in this._delayInfo) {
  26718. geometry._delayInfo = geometry._delayInfo || [];
  26719. geometry._delayInfo.push(kind);
  26720. }
  26721. // Bounding info
  26722. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  26723. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26724. return geometry;
  26725. };
  26726. // Statics
  26727. Geometry.ExtractFromMesh = function (mesh, id) {
  26728. var geometry = mesh._geometry;
  26729. if (!geometry) {
  26730. return null;
  26731. }
  26732. return geometry.copy(id);
  26733. };
  26734. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26735. // be aware Math.random() could cause collisions
  26736. Geometry.RandomId = function () {
  26737. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26738. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26739. return v.toString(16);
  26740. });
  26741. };
  26742. return Geometry;
  26743. })();
  26744. BABYLON.Geometry = Geometry;
  26745. /////// Primitives //////////////////////////////////////////////
  26746. var Geometry;
  26747. (function (Geometry) {
  26748. var Primitives;
  26749. (function (Primitives) {
  26750. /// Abstract class
  26751. var _Primitive = (function (_super) {
  26752. __extends(_Primitive, _super);
  26753. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26754. this._beingRegenerated = true;
  26755. this._canBeRegenerated = canBeRegenerated;
  26756. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26757. this._beingRegenerated = false;
  26758. }
  26759. _Primitive.prototype.canBeRegenerated = function () {
  26760. return this._canBeRegenerated;
  26761. };
  26762. _Primitive.prototype.regenerate = function () {
  26763. if (!this._canBeRegenerated) {
  26764. return;
  26765. }
  26766. this._beingRegenerated = true;
  26767. this.setAllVerticesData(this._regenerateVertexData(), false);
  26768. this._beingRegenerated = false;
  26769. };
  26770. _Primitive.prototype.asNewGeometry = function (id) {
  26771. return _super.prototype.copy.call(this, id);
  26772. };
  26773. // overrides
  26774. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26775. if (!this._beingRegenerated) {
  26776. return;
  26777. }
  26778. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26779. };
  26780. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26781. if (!this._beingRegenerated) {
  26782. return;
  26783. }
  26784. _super.prototype.setVerticesData.call(this, kind, data, false);
  26785. };
  26786. // to override
  26787. // protected
  26788. _Primitive.prototype._regenerateVertexData = function () {
  26789. throw new Error("Abstract method");
  26790. };
  26791. _Primitive.prototype.copy = function (id) {
  26792. throw new Error("Must be overriden in sub-classes.");
  26793. };
  26794. return _Primitive;
  26795. })(Geometry);
  26796. Primitives._Primitive = _Primitive;
  26797. var Ribbon = (function (_super) {
  26798. __extends(Ribbon, _super);
  26799. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26800. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26801. this.pathArray = pathArray;
  26802. this.closeArray = closeArray;
  26803. this.closePath = closePath;
  26804. this.offset = offset;
  26805. this.side = side;
  26806. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26807. }
  26808. Ribbon.prototype._regenerateVertexData = function () {
  26809. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  26810. };
  26811. Ribbon.prototype.copy = function (id) {
  26812. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26813. };
  26814. return Ribbon;
  26815. })(_Primitive);
  26816. Primitives.Ribbon = Ribbon;
  26817. var Box = (function (_super) {
  26818. __extends(Box, _super);
  26819. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26820. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26821. this.size = size;
  26822. this.side = side;
  26823. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26824. }
  26825. Box.prototype._regenerateVertexData = function () {
  26826. return BABYLON.VertexData.CreateBox(this.size, this.side);
  26827. };
  26828. Box.prototype.copy = function (id) {
  26829. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26830. };
  26831. return Box;
  26832. })(_Primitive);
  26833. Primitives.Box = Box;
  26834. var Sphere = (function (_super) {
  26835. __extends(Sphere, _super);
  26836. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26837. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26838. this.segments = segments;
  26839. this.diameter = diameter;
  26840. this.side = side;
  26841. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26842. }
  26843. Sphere.prototype._regenerateVertexData = function () {
  26844. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  26845. };
  26846. Sphere.prototype.copy = function (id) {
  26847. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26848. };
  26849. return Sphere;
  26850. })(_Primitive);
  26851. Primitives.Sphere = Sphere;
  26852. var Cylinder = (function (_super) {
  26853. __extends(Cylinder, _super);
  26854. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26855. if (subdivisions === void 0) { subdivisions = 1; }
  26856. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26857. this.height = height;
  26858. this.diameterTop = diameterTop;
  26859. this.diameterBottom = diameterBottom;
  26860. this.tessellation = tessellation;
  26861. this.subdivisions = subdivisions;
  26862. this.side = side;
  26863. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26864. }
  26865. Cylinder.prototype._regenerateVertexData = function () {
  26866. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  26867. };
  26868. Cylinder.prototype.copy = function (id) {
  26869. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26870. };
  26871. return Cylinder;
  26872. })(_Primitive);
  26873. Primitives.Cylinder = Cylinder;
  26874. var Torus = (function (_super) {
  26875. __extends(Torus, _super);
  26876. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26877. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26878. this.diameter = diameter;
  26879. this.thickness = thickness;
  26880. this.tessellation = tessellation;
  26881. this.side = side;
  26882. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26883. }
  26884. Torus.prototype._regenerateVertexData = function () {
  26885. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  26886. };
  26887. Torus.prototype.copy = function (id) {
  26888. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26889. };
  26890. return Torus;
  26891. })(_Primitive);
  26892. Primitives.Torus = Torus;
  26893. var Ground = (function (_super) {
  26894. __extends(Ground, _super);
  26895. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26896. this.width = width;
  26897. this.height = height;
  26898. this.subdivisions = subdivisions;
  26899. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26900. }
  26901. Ground.prototype._regenerateVertexData = function () {
  26902. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  26903. };
  26904. Ground.prototype.copy = function (id) {
  26905. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26906. };
  26907. return Ground;
  26908. })(_Primitive);
  26909. Primitives.Ground = Ground;
  26910. var TiledGround = (function (_super) {
  26911. __extends(TiledGround, _super);
  26912. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26913. this.xmin = xmin;
  26914. this.zmin = zmin;
  26915. this.xmax = xmax;
  26916. this.zmax = zmax;
  26917. this.subdivisions = subdivisions;
  26918. this.precision = precision;
  26919. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26920. }
  26921. TiledGround.prototype._regenerateVertexData = function () {
  26922. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  26923. };
  26924. TiledGround.prototype.copy = function (id) {
  26925. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26926. };
  26927. return TiledGround;
  26928. })(_Primitive);
  26929. Primitives.TiledGround = TiledGround;
  26930. var Plane = (function (_super) {
  26931. __extends(Plane, _super);
  26932. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26933. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26934. this.size = size;
  26935. this.side = side;
  26936. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26937. }
  26938. Plane.prototype._regenerateVertexData = function () {
  26939. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  26940. };
  26941. Plane.prototype.copy = function (id) {
  26942. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26943. };
  26944. return Plane;
  26945. })(_Primitive);
  26946. Primitives.Plane = Plane;
  26947. var TorusKnot = (function (_super) {
  26948. __extends(TorusKnot, _super);
  26949. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26950. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26951. this.radius = radius;
  26952. this.tube = tube;
  26953. this.radialSegments = radialSegments;
  26954. this.tubularSegments = tubularSegments;
  26955. this.p = p;
  26956. this.q = q;
  26957. this.side = side;
  26958. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26959. }
  26960. TorusKnot.prototype._regenerateVertexData = function () {
  26961. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  26962. };
  26963. TorusKnot.prototype.copy = function (id) {
  26964. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26965. };
  26966. return TorusKnot;
  26967. })(_Primitive);
  26968. Primitives.TorusKnot = TorusKnot;
  26969. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26970. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26971. })(BABYLON || (BABYLON = {}));
  26972. //# sourceMappingURL=babylon.geometry.js.map
  26973. var __extends = this.__extends || function (d, b) {
  26974. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26975. function __() { this.constructor = d; }
  26976. __.prototype = b.prototype;
  26977. d.prototype = new __();
  26978. };
  26979. var BABYLON;
  26980. (function (BABYLON) {
  26981. var GroundMesh = (function (_super) {
  26982. __extends(GroundMesh, _super);
  26983. function GroundMesh(name, scene) {
  26984. _super.call(this, name, scene);
  26985. this.generateOctree = false;
  26986. this._worldInverse = new BABYLON.Matrix();
  26987. }
  26988. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  26989. get: function () {
  26990. return this._subdivisions;
  26991. },
  26992. enumerable: true,
  26993. configurable: true
  26994. });
  26995. GroundMesh.prototype.optimize = function (chunksCount) {
  26996. this.subdivide(this._subdivisions);
  26997. this.createOrUpdateSubmeshesOctree(32);
  26998. };
  26999. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  27000. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  27001. this.getWorldMatrix().invertToRef(this._worldInverse);
  27002. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  27003. var pickInfo = this.intersects(ray);
  27004. if (pickInfo.hit) {
  27005. return pickInfo.pickedPoint.y;
  27006. }
  27007. return 0;
  27008. };
  27009. return GroundMesh;
  27010. })(BABYLON.Mesh);
  27011. BABYLON.GroundMesh = GroundMesh;
  27012. })(BABYLON || (BABYLON = {}));
  27013. //# sourceMappingURL=babylon.groundMesh.js.map
  27014. var __extends = this.__extends || function (d, b) {
  27015. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27016. function __() { this.constructor = d; }
  27017. __.prototype = b.prototype;
  27018. d.prototype = new __();
  27019. };
  27020. var BABYLON;
  27021. (function (BABYLON) {
  27022. var Gamepads = (function () {
  27023. function Gamepads(ongamedpadconnected) {
  27024. var _this = this;
  27025. this.babylonGamepads = [];
  27026. this.oneGamepadConnected = false;
  27027. this.isMonitoring = false;
  27028. this.gamepadEventSupported = 'GamepadEvent' in window;
  27029. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  27030. 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=";
  27031. this._callbackGamepadConnected = ongamedpadconnected;
  27032. if (this.gamepadSupportAvailable) {
  27033. // Checking if the gamepad connected event is supported (like in Firefox)
  27034. if (this.gamepadEventSupported) {
  27035. window.addEventListener('gamepadconnected', function (evt) {
  27036. _this._onGamepadConnected(evt);
  27037. }, false);
  27038. window.addEventListener('gamepaddisconnected', function (evt) {
  27039. _this._onGamepadDisconnected(evt);
  27040. }, false);
  27041. }
  27042. else {
  27043. this._startMonitoringGamepads();
  27044. }
  27045. if (!this.oneGamepadConnected) {
  27046. this._insertGamepadDOMInstructions();
  27047. }
  27048. }
  27049. else {
  27050. this._insertGamepadDOMNotSupported();
  27051. }
  27052. }
  27053. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  27054. Gamepads.gamepadDOMInfo = document.createElement("div");
  27055. var buttonAImage = document.createElement("img");
  27056. buttonAImage.src = this.buttonADataURL;
  27057. var spanMessage = document.createElement("span");
  27058. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  27059. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  27060. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  27061. Gamepads.gamepadDOMInfo.style.position = "absolute";
  27062. Gamepads.gamepadDOMInfo.style.width = "100%";
  27063. Gamepads.gamepadDOMInfo.style.height = "48px";
  27064. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  27065. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  27066. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  27067. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  27068. buttonAImage.style.position = "relative";
  27069. buttonAImage.style.bottom = "8px";
  27070. spanMessage.style.position = "relative";
  27071. spanMessage.style.fontSize = "32px";
  27072. spanMessage.style.bottom = "32px";
  27073. spanMessage.style.color = "green";
  27074. document.body.appendChild(Gamepads.gamepadDOMInfo);
  27075. };
  27076. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  27077. Gamepads.gamepadDOMInfo = document.createElement("div");
  27078. var spanMessage = document.createElement("span");
  27079. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  27080. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  27081. Gamepads.gamepadDOMInfo.style.position = "absolute";
  27082. Gamepads.gamepadDOMInfo.style.width = "100%";
  27083. Gamepads.gamepadDOMInfo.style.height = "40px";
  27084. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  27085. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  27086. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  27087. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  27088. spanMessage.style.position = "relative";
  27089. spanMessage.style.fontSize = "32px";
  27090. spanMessage.style.color = "red";
  27091. document.body.appendChild(Gamepads.gamepadDOMInfo);
  27092. };
  27093. Gamepads.prototype.dispose = function () {
  27094. if (Gamepads.gamepadDOMInfo) {
  27095. document.body.removeChild(Gamepads.gamepadDOMInfo);
  27096. }
  27097. };
  27098. Gamepads.prototype._onGamepadConnected = function (evt) {
  27099. var newGamepad = this._addNewGamepad(evt.gamepad);
  27100. if (this._callbackGamepadConnected)
  27101. this._callbackGamepadConnected(newGamepad);
  27102. this._startMonitoringGamepads();
  27103. };
  27104. Gamepads.prototype._addNewGamepad = function (gamepad) {
  27105. if (!this.oneGamepadConnected) {
  27106. this.oneGamepadConnected = true;
  27107. if (Gamepads.gamepadDOMInfo) {
  27108. document.body.removeChild(Gamepads.gamepadDOMInfo);
  27109. Gamepads.gamepadDOMInfo = null;
  27110. }
  27111. }
  27112. var newGamepad;
  27113. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  27114. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  27115. }
  27116. else {
  27117. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  27118. }
  27119. this.babylonGamepads.push(newGamepad);
  27120. return newGamepad;
  27121. };
  27122. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  27123. for (var i in this.babylonGamepads) {
  27124. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  27125. this.babylonGamepads.splice(i, 1);
  27126. break;
  27127. }
  27128. }
  27129. // If no gamepads are left, stop the polling loop.
  27130. if (this.babylonGamepads.length == 0) {
  27131. this._stopMonitoringGamepads();
  27132. }
  27133. };
  27134. Gamepads.prototype._startMonitoringGamepads = function () {
  27135. if (!this.isMonitoring) {
  27136. this.isMonitoring = true;
  27137. this._checkGamepadsStatus();
  27138. }
  27139. };
  27140. Gamepads.prototype._stopMonitoringGamepads = function () {
  27141. this.isMonitoring = false;
  27142. };
  27143. Gamepads.prototype._checkGamepadsStatus = function () {
  27144. var _this = this;
  27145. // updating gamepad objects
  27146. this._updateGamepadObjects();
  27147. for (var i in this.babylonGamepads) {
  27148. this.babylonGamepads[i].update();
  27149. }
  27150. if (this.isMonitoring) {
  27151. if (window.requestAnimationFrame) {
  27152. window.requestAnimationFrame(function () {
  27153. _this._checkGamepadsStatus();
  27154. });
  27155. }
  27156. else if (window.mozRequestAnimationFrame) {
  27157. window.mozRequestAnimationFrame(function () {
  27158. _this._checkGamepadsStatus();
  27159. });
  27160. }
  27161. else if (window.webkitRequestAnimationFrame) {
  27162. window.webkitRequestAnimationFrame(function () {
  27163. _this._checkGamepadsStatus();
  27164. });
  27165. }
  27166. }
  27167. };
  27168. // This function is called only on Chrome, which does not yet support
  27169. // connection/disconnection events, but requires you to monitor
  27170. // an array for changes.
  27171. Gamepads.prototype._updateGamepadObjects = function () {
  27172. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  27173. for (var i = 0; i < gamepads.length; i++) {
  27174. if (gamepads[i]) {
  27175. if (!(gamepads[i].index in this.babylonGamepads)) {
  27176. var newGamepad = this._addNewGamepad(gamepads[i]);
  27177. if (this._callbackGamepadConnected) {
  27178. this._callbackGamepadConnected(newGamepad);
  27179. }
  27180. }
  27181. else {
  27182. this.babylonGamepads[i].browserGamepad = gamepads[i];
  27183. }
  27184. }
  27185. }
  27186. };
  27187. return Gamepads;
  27188. })();
  27189. BABYLON.Gamepads = Gamepads;
  27190. var StickValues = (function () {
  27191. function StickValues(x, y) {
  27192. this.x = x;
  27193. this.y = y;
  27194. }
  27195. return StickValues;
  27196. })();
  27197. BABYLON.StickValues = StickValues;
  27198. var Gamepad = (function () {
  27199. function Gamepad(id, index, browserGamepad) {
  27200. this.id = id;
  27201. this.index = index;
  27202. this.browserGamepad = browserGamepad;
  27203. if (this.browserGamepad.axes.length >= 2) {
  27204. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  27205. }
  27206. if (this.browserGamepad.axes.length >= 4) {
  27207. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  27208. }
  27209. }
  27210. Gamepad.prototype.onleftstickchanged = function (callback) {
  27211. this._onleftstickchanged = callback;
  27212. };
  27213. Gamepad.prototype.onrightstickchanged = function (callback) {
  27214. this._onrightstickchanged = callback;
  27215. };
  27216. Object.defineProperty(Gamepad.prototype, "leftStick", {
  27217. get: function () {
  27218. return this._leftStick;
  27219. },
  27220. set: function (newValues) {
  27221. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  27222. this._onleftstickchanged(newValues);
  27223. }
  27224. this._leftStick = newValues;
  27225. },
  27226. enumerable: true,
  27227. configurable: true
  27228. });
  27229. Object.defineProperty(Gamepad.prototype, "rightStick", {
  27230. get: function () {
  27231. return this._rightStick;
  27232. },
  27233. set: function (newValues) {
  27234. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  27235. this._onrightstickchanged(newValues);
  27236. }
  27237. this._rightStick = newValues;
  27238. },
  27239. enumerable: true,
  27240. configurable: true
  27241. });
  27242. Gamepad.prototype.update = function () {
  27243. if (this._leftStick) {
  27244. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  27245. }
  27246. if (this._rightStick) {
  27247. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  27248. }
  27249. };
  27250. return Gamepad;
  27251. })();
  27252. BABYLON.Gamepad = Gamepad;
  27253. var GenericPad = (function (_super) {
  27254. __extends(GenericPad, _super);
  27255. function GenericPad(id, index, gamepad) {
  27256. _super.call(this, id, index, gamepad);
  27257. this.id = id;
  27258. this.index = index;
  27259. this.gamepad = gamepad;
  27260. this._buttons = new Array(gamepad.buttons.length);
  27261. }
  27262. GenericPad.prototype.onbuttondown = function (callback) {
  27263. this._onbuttondown = callback;
  27264. };
  27265. GenericPad.prototype.onbuttonup = function (callback) {
  27266. this._onbuttonup = callback;
  27267. };
  27268. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  27269. if (newValue !== currentValue) {
  27270. if (this._onbuttondown && newValue === 1) {
  27271. this._onbuttondown(buttonIndex);
  27272. }
  27273. if (this._onbuttonup && newValue === 0) {
  27274. this._onbuttonup(buttonIndex);
  27275. }
  27276. }
  27277. return newValue;
  27278. };
  27279. GenericPad.prototype.update = function () {
  27280. _super.prototype.update.call(this);
  27281. for (var index = 0; index < this._buttons.length; index++) {
  27282. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  27283. }
  27284. };
  27285. return GenericPad;
  27286. })(Gamepad);
  27287. BABYLON.GenericPad = GenericPad;
  27288. (function (Xbox360Button) {
  27289. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  27290. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  27291. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  27292. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  27293. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  27294. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  27295. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  27296. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  27297. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  27298. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  27299. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  27300. var Xbox360Button = BABYLON.Xbox360Button;
  27301. (function (Xbox360Dpad) {
  27302. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  27303. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  27304. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  27305. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  27306. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  27307. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  27308. var Xbox360Pad = (function (_super) {
  27309. __extends(Xbox360Pad, _super);
  27310. function Xbox360Pad() {
  27311. _super.apply(this, arguments);
  27312. this._leftTrigger = 0;
  27313. this._rightTrigger = 0;
  27314. this._buttonA = 0;
  27315. this._buttonB = 0;
  27316. this._buttonX = 0;
  27317. this._buttonY = 0;
  27318. this._buttonBack = 0;
  27319. this._buttonStart = 0;
  27320. this._buttonLB = 0;
  27321. this._buttonRB = 0;
  27322. this._buttonLeftStick = 0;
  27323. this._buttonRightStick = 0;
  27324. this._dPadUp = 0;
  27325. this._dPadDown = 0;
  27326. this._dPadLeft = 0;
  27327. this._dPadRight = 0;
  27328. }
  27329. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  27330. this._onlefttriggerchanged = callback;
  27331. };
  27332. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  27333. this._onrighttriggerchanged = callback;
  27334. };
  27335. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  27336. get: function () {
  27337. return this._leftTrigger;
  27338. },
  27339. set: function (newValue) {
  27340. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  27341. this._onlefttriggerchanged(newValue);
  27342. }
  27343. this._leftTrigger = newValue;
  27344. },
  27345. enumerable: true,
  27346. configurable: true
  27347. });
  27348. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  27349. get: function () {
  27350. return this._rightTrigger;
  27351. },
  27352. set: function (newValue) {
  27353. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  27354. this._onrighttriggerchanged(newValue);
  27355. }
  27356. this._rightTrigger = newValue;
  27357. },
  27358. enumerable: true,
  27359. configurable: true
  27360. });
  27361. Xbox360Pad.prototype.onbuttondown = function (callback) {
  27362. this._onbuttondown = callback;
  27363. };
  27364. Xbox360Pad.prototype.onbuttonup = function (callback) {
  27365. this._onbuttonup = callback;
  27366. };
  27367. Xbox360Pad.prototype.ondpaddown = function (callback) {
  27368. this._ondpaddown = callback;
  27369. };
  27370. Xbox360Pad.prototype.ondpadup = function (callback) {
  27371. this._ondpadup = callback;
  27372. };
  27373. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  27374. if (newValue !== currentValue) {
  27375. if (this._onbuttondown && newValue === 1) {
  27376. this._onbuttondown(buttonType);
  27377. }
  27378. if (this._onbuttonup && newValue === 0) {
  27379. this._onbuttonup(buttonType);
  27380. }
  27381. }
  27382. return newValue;
  27383. };
  27384. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  27385. if (newValue !== currentValue) {
  27386. if (this._ondpaddown && newValue === 1) {
  27387. this._ondpaddown(buttonType);
  27388. }
  27389. if (this._ondpadup && newValue === 0) {
  27390. this._ondpadup(buttonType);
  27391. }
  27392. }
  27393. return newValue;
  27394. };
  27395. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  27396. get: function () {
  27397. return this._buttonA;
  27398. },
  27399. set: function (value) {
  27400. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  27401. },
  27402. enumerable: true,
  27403. configurable: true
  27404. });
  27405. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  27406. get: function () {
  27407. return this._buttonB;
  27408. },
  27409. set: function (value) {
  27410. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  27411. },
  27412. enumerable: true,
  27413. configurable: true
  27414. });
  27415. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  27416. get: function () {
  27417. return this._buttonX;
  27418. },
  27419. set: function (value) {
  27420. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  27421. },
  27422. enumerable: true,
  27423. configurable: true
  27424. });
  27425. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  27426. get: function () {
  27427. return this._buttonY;
  27428. },
  27429. set: function (value) {
  27430. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  27431. },
  27432. enumerable: true,
  27433. configurable: true
  27434. });
  27435. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  27436. get: function () {
  27437. return this._buttonStart;
  27438. },
  27439. set: function (value) {
  27440. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  27441. },
  27442. enumerable: true,
  27443. configurable: true
  27444. });
  27445. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  27446. get: function () {
  27447. return this._buttonBack;
  27448. },
  27449. set: function (value) {
  27450. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  27451. },
  27452. enumerable: true,
  27453. configurable: true
  27454. });
  27455. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  27456. get: function () {
  27457. return this._buttonLB;
  27458. },
  27459. set: function (value) {
  27460. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  27461. },
  27462. enumerable: true,
  27463. configurable: true
  27464. });
  27465. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  27466. get: function () {
  27467. return this._buttonRB;
  27468. },
  27469. set: function (value) {
  27470. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  27471. },
  27472. enumerable: true,
  27473. configurable: true
  27474. });
  27475. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  27476. get: function () {
  27477. return this._buttonLeftStick;
  27478. },
  27479. set: function (value) {
  27480. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  27481. },
  27482. enumerable: true,
  27483. configurable: true
  27484. });
  27485. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  27486. get: function () {
  27487. return this._buttonRightStick;
  27488. },
  27489. set: function (value) {
  27490. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  27491. },
  27492. enumerable: true,
  27493. configurable: true
  27494. });
  27495. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  27496. get: function () {
  27497. return this._dPadUp;
  27498. },
  27499. set: function (value) {
  27500. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  27501. },
  27502. enumerable: true,
  27503. configurable: true
  27504. });
  27505. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  27506. get: function () {
  27507. return this._dPadDown;
  27508. },
  27509. set: function (value) {
  27510. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  27511. },
  27512. enumerable: true,
  27513. configurable: true
  27514. });
  27515. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  27516. get: function () {
  27517. return this._dPadLeft;
  27518. },
  27519. set: function (value) {
  27520. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  27521. },
  27522. enumerable: true,
  27523. configurable: true
  27524. });
  27525. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  27526. get: function () {
  27527. return this._dPadRight;
  27528. },
  27529. set: function (value) {
  27530. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  27531. },
  27532. enumerable: true,
  27533. configurable: true
  27534. });
  27535. Xbox360Pad.prototype.update = function () {
  27536. _super.prototype.update.call(this);
  27537. this.buttonA = this.browserGamepad.buttons[0].value;
  27538. this.buttonB = this.browserGamepad.buttons[1].value;
  27539. this.buttonX = this.browserGamepad.buttons[2].value;
  27540. this.buttonY = this.browserGamepad.buttons[3].value;
  27541. this.buttonLB = this.browserGamepad.buttons[4].value;
  27542. this.buttonRB = this.browserGamepad.buttons[5].value;
  27543. this.leftTrigger = this.browserGamepad.buttons[6].value;
  27544. this.rightTrigger = this.browserGamepad.buttons[7].value;
  27545. this.buttonBack = this.browserGamepad.buttons[8].value;
  27546. this.buttonStart = this.browserGamepad.buttons[9].value;
  27547. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  27548. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  27549. this.dPadUp = this.browserGamepad.buttons[12].value;
  27550. this.dPadDown = this.browserGamepad.buttons[13].value;
  27551. this.dPadLeft = this.browserGamepad.buttons[14].value;
  27552. this.dPadRight = this.browserGamepad.buttons[15].value;
  27553. };
  27554. return Xbox360Pad;
  27555. })(Gamepad);
  27556. BABYLON.Xbox360Pad = Xbox360Pad;
  27557. })(BABYLON || (BABYLON = {}));
  27558. //# sourceMappingURL=babylon.gamepads.js.map
  27559. var __extends = this.__extends || function (d, b) {
  27560. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27561. function __() { this.constructor = d; }
  27562. __.prototype = b.prototype;
  27563. d.prototype = new __();
  27564. };
  27565. var BABYLON;
  27566. (function (BABYLON) {
  27567. // We're mainly based on the logic defined into the FreeCamera code
  27568. var GamepadCamera = (function (_super) {
  27569. __extends(GamepadCamera, _super);
  27570. function GamepadCamera(name, position, scene) {
  27571. var _this = this;
  27572. _super.call(this, name, position, scene);
  27573. this.angularSensibility = 200;
  27574. this.moveSensibility = 75;
  27575. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  27576. _this._onNewGameConnected(gamepad);
  27577. });
  27578. }
  27579. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  27580. // Only the first gamepad can control the camera
  27581. if (gamepad.index === 0) {
  27582. this._gamepad = gamepad;
  27583. }
  27584. };
  27585. GamepadCamera.prototype._checkInputs = function () {
  27586. if (!this._gamepad) {
  27587. return;
  27588. }
  27589. var LSValues = this._gamepad.leftStick;
  27590. var normalizedLX = LSValues.x / this.moveSensibility;
  27591. var normalizedLY = LSValues.y / this.moveSensibility;
  27592. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  27593. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  27594. var RSValues = this._gamepad.rightStick;
  27595. var normalizedRX = RSValues.x / this.angularSensibility;
  27596. var normalizedRY = RSValues.y / this.angularSensibility;
  27597. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  27598. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  27599. ;
  27600. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  27601. var speed = this._computeLocalCameraSpeed() * 50.0;
  27602. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  27603. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  27604. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  27605. };
  27606. GamepadCamera.prototype.dispose = function () {
  27607. this._gamepads.dispose();
  27608. _super.prototype.dispose.call(this);
  27609. };
  27610. return GamepadCamera;
  27611. })(BABYLON.FreeCamera);
  27612. BABYLON.GamepadCamera = GamepadCamera;
  27613. })(BABYLON || (BABYLON = {}));
  27614. //# sourceMappingURL=babylon.gamepadCamera.js.map
  27615. var __extends = this.__extends || function (d, b) {
  27616. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27617. function __() { this.constructor = d; }
  27618. __.prototype = b.prototype;
  27619. d.prototype = new __();
  27620. };
  27621. var BABYLON;
  27622. (function (BABYLON) {
  27623. var LinesMesh = (function (_super) {
  27624. __extends(LinesMesh, _super);
  27625. function LinesMesh(name, scene, updatable) {
  27626. if (updatable === void 0) { updatable = false; }
  27627. _super.call(this, name, scene);
  27628. this.color = new BABYLON.Color3(1, 1, 1);
  27629. this.alpha = 1;
  27630. this._indices = new Array();
  27631. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27632. attributes: ["position"],
  27633. uniforms: ["worldViewProjection", "color"],
  27634. needAlphaBlending: true
  27635. });
  27636. }
  27637. Object.defineProperty(LinesMesh.prototype, "material", {
  27638. get: function () {
  27639. return this._colorShader;
  27640. },
  27641. enumerable: true,
  27642. configurable: true
  27643. });
  27644. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27645. get: function () {
  27646. return false;
  27647. },
  27648. enumerable: true,
  27649. configurable: true
  27650. });
  27651. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27652. get: function () {
  27653. return false;
  27654. },
  27655. enumerable: true,
  27656. configurable: true
  27657. });
  27658. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27659. var engine = this.getScene().getEngine();
  27660. var indexToBind = this._geometry.getIndexBuffer();
  27661. // VBOs
  27662. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27663. // Color
  27664. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27665. };
  27666. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27667. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27668. return;
  27669. }
  27670. var engine = this.getScene().getEngine();
  27671. // Draw order
  27672. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27673. };
  27674. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27675. return null;
  27676. };
  27677. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27678. this._colorShader.dispose();
  27679. _super.prototype.dispose.call(this, doNotRecurse);
  27680. };
  27681. return LinesMesh;
  27682. })(BABYLON.Mesh);
  27683. BABYLON.LinesMesh = LinesMesh;
  27684. })(BABYLON || (BABYLON = {}));
  27685. //# sourceMappingURL=babylon.linesMesh.js.map
  27686. var BABYLON;
  27687. (function (BABYLON) {
  27688. var OutlineRenderer = (function () {
  27689. function OutlineRenderer(scene) {
  27690. this._scene = scene;
  27691. }
  27692. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  27693. var _this = this;
  27694. if (useOverlay === void 0) { useOverlay = false; }
  27695. var scene = this._scene;
  27696. var engine = this._scene.getEngine();
  27697. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27698. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  27699. return;
  27700. }
  27701. var mesh = subMesh.getRenderingMesh();
  27702. var material = subMesh.getMaterial();
  27703. engine.enableEffect(this._effect);
  27704. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  27705. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  27706. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27707. // Bones
  27708. if (mesh.useBones) {
  27709. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27710. }
  27711. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  27712. // Alpha test
  27713. if (material && material.needAlphaTesting()) {
  27714. var alphaTexture = material.getAlphaTestTexture();
  27715. this._effect.setTexture("diffuseSampler", alphaTexture);
  27716. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27717. }
  27718. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  27719. _this._effect.setMatrix("world", world);
  27720. });
  27721. };
  27722. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  27723. var defines = [];
  27724. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  27725. var mesh = subMesh.getMesh();
  27726. var material = subMesh.getMaterial();
  27727. // Alpha test
  27728. if (material && material.needAlphaTesting()) {
  27729. defines.push("#define ALPHATEST");
  27730. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27731. attribs.push(BABYLON.VertexBuffer.UVKind);
  27732. defines.push("#define UV1");
  27733. }
  27734. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27735. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27736. defines.push("#define UV2");
  27737. }
  27738. }
  27739. // Bones
  27740. if (mesh.useBones) {
  27741. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27742. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27743. defines.push("#define BONES");
  27744. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27745. }
  27746. // Instances
  27747. if (useInstances) {
  27748. defines.push("#define INSTANCES");
  27749. attribs.push("world0");
  27750. attribs.push("world1");
  27751. attribs.push("world2");
  27752. attribs.push("world3");
  27753. }
  27754. // Get correct effect
  27755. var join = defines.join("\n");
  27756. if (this._cachedDefines !== join) {
  27757. this._cachedDefines = join;
  27758. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  27759. }
  27760. return this._effect.isReady();
  27761. };
  27762. return OutlineRenderer;
  27763. })();
  27764. BABYLON.OutlineRenderer = OutlineRenderer;
  27765. })(BABYLON || (BABYLON = {}));
  27766. //# sourceMappingURL=babylon.outlineRenderer.js.map
  27767. var BABYLON;
  27768. (function (BABYLON) {
  27769. var MeshAssetTask = (function () {
  27770. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  27771. this.name = name;
  27772. this.meshesNames = meshesNames;
  27773. this.rootUrl = rootUrl;
  27774. this.sceneFilename = sceneFilename;
  27775. this.isCompleted = false;
  27776. }
  27777. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27778. var _this = this;
  27779. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  27780. _this.loadedMeshes = meshes;
  27781. _this.loadedParticleSystems = particleSystems;
  27782. _this.loadedSkeletons = skeletons;
  27783. _this.isCompleted = true;
  27784. if (_this.onSuccess) {
  27785. _this.onSuccess(_this);
  27786. }
  27787. onSuccess();
  27788. }, null, function () {
  27789. if (_this.onError) {
  27790. _this.onError(_this);
  27791. }
  27792. onError();
  27793. });
  27794. };
  27795. return MeshAssetTask;
  27796. })();
  27797. BABYLON.MeshAssetTask = MeshAssetTask;
  27798. var TextFileAssetTask = (function () {
  27799. function TextFileAssetTask(name, url) {
  27800. this.name = name;
  27801. this.url = url;
  27802. this.isCompleted = false;
  27803. }
  27804. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27805. var _this = this;
  27806. BABYLON.Tools.LoadFile(this.url, function (data) {
  27807. _this.text = data;
  27808. _this.isCompleted = true;
  27809. if (_this.onSuccess) {
  27810. _this.onSuccess(_this);
  27811. }
  27812. onSuccess();
  27813. }, null, scene.database, false, function () {
  27814. if (_this.onError) {
  27815. _this.onError(_this);
  27816. }
  27817. onError();
  27818. });
  27819. };
  27820. return TextFileAssetTask;
  27821. })();
  27822. BABYLON.TextFileAssetTask = TextFileAssetTask;
  27823. var BinaryFileAssetTask = (function () {
  27824. function BinaryFileAssetTask(name, url) {
  27825. this.name = name;
  27826. this.url = url;
  27827. this.isCompleted = false;
  27828. }
  27829. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27830. var _this = this;
  27831. BABYLON.Tools.LoadFile(this.url, function (data) {
  27832. _this.data = data;
  27833. _this.isCompleted = true;
  27834. if (_this.onSuccess) {
  27835. _this.onSuccess(_this);
  27836. }
  27837. onSuccess();
  27838. }, null, scene.database, true, function () {
  27839. if (_this.onError) {
  27840. _this.onError(_this);
  27841. }
  27842. onError();
  27843. });
  27844. };
  27845. return BinaryFileAssetTask;
  27846. })();
  27847. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  27848. var ImageAssetTask = (function () {
  27849. function ImageAssetTask(name, url) {
  27850. this.name = name;
  27851. this.url = url;
  27852. this.isCompleted = false;
  27853. }
  27854. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27855. var _this = this;
  27856. var img = new Image();
  27857. img.onload = function () {
  27858. _this.image = img;
  27859. _this.isCompleted = true;
  27860. if (_this.onSuccess) {
  27861. _this.onSuccess(_this);
  27862. }
  27863. onSuccess();
  27864. };
  27865. img.onerror = function () {
  27866. if (_this.onError) {
  27867. _this.onError(_this);
  27868. }
  27869. onError();
  27870. };
  27871. img.src = this.url;
  27872. };
  27873. return ImageAssetTask;
  27874. })();
  27875. BABYLON.ImageAssetTask = ImageAssetTask;
  27876. var TextureAssetTask = (function () {
  27877. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  27878. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27879. this.name = name;
  27880. this.url = url;
  27881. this.noMipmap = noMipmap;
  27882. this.invertY = invertY;
  27883. this.samplingMode = samplingMode;
  27884. this.isCompleted = false;
  27885. }
  27886. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27887. var _this = this;
  27888. var onload = function () {
  27889. _this.isCompleted = true;
  27890. if (_this.onSuccess) {
  27891. _this.onSuccess(_this);
  27892. }
  27893. onSuccess();
  27894. };
  27895. var onerror = function () {
  27896. if (_this.onError) {
  27897. _this.onError(_this);
  27898. }
  27899. onError();
  27900. };
  27901. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  27902. };
  27903. return TextureAssetTask;
  27904. })();
  27905. BABYLON.TextureAssetTask = TextureAssetTask;
  27906. var AssetsManager = (function () {
  27907. function AssetsManager(scene) {
  27908. this._tasks = new Array();
  27909. this._waitingTasksCount = 0;
  27910. this.useDefaultLoadingScreen = true;
  27911. this._scene = scene;
  27912. }
  27913. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  27914. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  27915. this._tasks.push(task);
  27916. return task;
  27917. };
  27918. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  27919. var task = new TextFileAssetTask(taskName, url);
  27920. this._tasks.push(task);
  27921. return task;
  27922. };
  27923. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  27924. var task = new BinaryFileAssetTask(taskName, url);
  27925. this._tasks.push(task);
  27926. return task;
  27927. };
  27928. AssetsManager.prototype.addImageTask = function (taskName, url) {
  27929. var task = new ImageAssetTask(taskName, url);
  27930. this._tasks.push(task);
  27931. return task;
  27932. };
  27933. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  27934. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27935. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  27936. this._tasks.push(task);
  27937. return task;
  27938. };
  27939. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  27940. this._waitingTasksCount--;
  27941. if (this._waitingTasksCount === 0) {
  27942. if (this.onFinish) {
  27943. this.onFinish(this._tasks);
  27944. }
  27945. this._scene.getEngine().hideLoadingUI();
  27946. }
  27947. };
  27948. AssetsManager.prototype._runTask = function (task) {
  27949. var _this = this;
  27950. task.run(this._scene, function () {
  27951. if (_this.onTaskSuccess) {
  27952. _this.onTaskSuccess(task);
  27953. }
  27954. _this._decreaseWaitingTasksCount();
  27955. }, function () {
  27956. if (_this.onTaskError) {
  27957. _this.onTaskError(task);
  27958. }
  27959. _this._decreaseWaitingTasksCount();
  27960. });
  27961. };
  27962. AssetsManager.prototype.reset = function () {
  27963. this._tasks = new Array();
  27964. return this;
  27965. };
  27966. AssetsManager.prototype.load = function () {
  27967. this._waitingTasksCount = this._tasks.length;
  27968. if (this._waitingTasksCount === 0) {
  27969. if (this.onFinish) {
  27970. this.onFinish(this._tasks);
  27971. }
  27972. return this;
  27973. }
  27974. if (this.useDefaultLoadingScreen) {
  27975. this._scene.getEngine().displayLoadingUI();
  27976. }
  27977. for (var index = 0; index < this._tasks.length; index++) {
  27978. var task = this._tasks[index];
  27979. this._runTask(task);
  27980. }
  27981. return this;
  27982. };
  27983. return AssetsManager;
  27984. })();
  27985. BABYLON.AssetsManager = AssetsManager;
  27986. })(BABYLON || (BABYLON = {}));
  27987. //# sourceMappingURL=babylon.assetsManager.js.map
  27988. var __extends = this.__extends || function (d, b) {
  27989. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27990. function __() { this.constructor = d; }
  27991. __.prototype = b.prototype;
  27992. d.prototype = new __();
  27993. };
  27994. var BABYLON;
  27995. (function (BABYLON) {
  27996. var VRDeviceOrientationCamera = (function (_super) {
  27997. __extends(VRDeviceOrientationCamera, _super);
  27998. function VRDeviceOrientationCamera(name, position, scene) {
  27999. _super.call(this, name, position, scene);
  28000. this._alpha = 0;
  28001. this._beta = 0;
  28002. this._gamma = 0;
  28003. }
  28004. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  28005. this._alpha = +evt.alpha | 0;
  28006. this._beta = +evt.beta | 0;
  28007. this._gamma = +evt.gamma | 0;
  28008. if (this._gamma < 0) {
  28009. this._gamma = 90 + this._gamma;
  28010. }
  28011. else {
  28012. // Incline it in the correct angle.
  28013. this._gamma = 270 - this._gamma;
  28014. }
  28015. this.rotation.x = this._gamma / 180.0 * Math.PI;
  28016. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  28017. this.rotation.z = this._beta / 180.0 * Math.PI;
  28018. };
  28019. return VRDeviceOrientationCamera;
  28020. })(BABYLON.OculusCamera);
  28021. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  28022. })(BABYLON || (BABYLON = {}));
  28023. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  28024. var __extends = this.__extends || function (d, b) {
  28025. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28026. function __() { this.constructor = d; }
  28027. __.prototype = b.prototype;
  28028. d.prototype = new __();
  28029. };
  28030. var BABYLON;
  28031. (function (BABYLON) {
  28032. var WebVRCamera = (function (_super) {
  28033. __extends(WebVRCamera, _super);
  28034. function WebVRCamera(name, position, scene) {
  28035. _super.call(this, name, position, scene);
  28036. this._hmdDevice = null;
  28037. this._sensorDevice = null;
  28038. this._cacheState = null;
  28039. this._cacheQuaternion = new BABYLON.Quaternion();
  28040. this._cacheRotation = BABYLON.Vector3.Zero();
  28041. this._vrEnabled = false;
  28042. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  28043. }
  28044. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  28045. var size = devices.length;
  28046. var i = 0;
  28047. // Reset devices.
  28048. this._sensorDevice = null;
  28049. this._hmdDevice = null;
  28050. while (i < size && this._hmdDevice === null) {
  28051. if (devices[i] instanceof HMDVRDevice) {
  28052. this._hmdDevice = devices[i];
  28053. }
  28054. i++;
  28055. }
  28056. i = 0;
  28057. while (i < size && this._sensorDevice === null) {
  28058. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  28059. this._sensorDevice = devices[i];
  28060. }
  28061. i++;
  28062. }
  28063. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  28064. };
  28065. WebVRCamera.prototype._update = function () {
  28066. if (this._vrEnabled) {
  28067. this._cacheState = this._sensorDevice.getState();
  28068. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  28069. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  28070. this.rotation.x = -this._cacheRotation.z;
  28071. this.rotation.y = -this._cacheRotation.y;
  28072. this.rotation.z = this._cacheRotation.x;
  28073. }
  28074. _super.prototype._update.call(this);
  28075. };
  28076. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  28077. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28078. if (navigator.getVRDevices) {
  28079. navigator.getVRDevices().then(this._getWebVRDevices);
  28080. }
  28081. else if (navigator.mozGetVRDevices) {
  28082. navigator.mozGetVRDevices(this._getWebVRDevices);
  28083. }
  28084. };
  28085. WebVRCamera.prototype.detachControl = function (element) {
  28086. _super.prototype.detachControl.call(this, element);
  28087. this._vrEnabled = false;
  28088. };
  28089. return WebVRCamera;
  28090. })(BABYLON.OculusCamera);
  28091. BABYLON.WebVRCamera = WebVRCamera;
  28092. })(BABYLON || (BABYLON = {}));
  28093. //# sourceMappingURL=babylon.webVRCamera.js.map
  28094. var __extends = this.__extends || function (d, b) {
  28095. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28096. function __() { this.constructor = d; }
  28097. __.prototype = b.prototype;
  28098. d.prototype = new __();
  28099. };
  28100. var BABYLON;
  28101. (function (BABYLON) {
  28102. // Standard optimizations
  28103. var SceneOptimization = (function () {
  28104. function SceneOptimization(priority) {
  28105. if (priority === void 0) { priority = 0; }
  28106. this.priority = priority;
  28107. this.apply = function (scene) {
  28108. return true; // Return true if everything that can be done was applied
  28109. };
  28110. }
  28111. return SceneOptimization;
  28112. })();
  28113. BABYLON.SceneOptimization = SceneOptimization;
  28114. var TextureOptimization = (function (_super) {
  28115. __extends(TextureOptimization, _super);
  28116. function TextureOptimization(priority, maximumSize) {
  28117. var _this = this;
  28118. if (priority === void 0) { priority = 0; }
  28119. if (maximumSize === void 0) { maximumSize = 1024; }
  28120. _super.call(this, priority);
  28121. this.priority = priority;
  28122. this.maximumSize = maximumSize;
  28123. this.apply = function (scene) {
  28124. var allDone = true;
  28125. for (var index = 0; index < scene.textures.length; index++) {
  28126. var texture = scene.textures[index];
  28127. if (!texture.canRescale) {
  28128. continue;
  28129. }
  28130. var currentSize = texture.getSize();
  28131. var maxDimension = Math.max(currentSize.width, currentSize.height);
  28132. if (maxDimension > _this.maximumSize) {
  28133. texture.scale(0.5);
  28134. allDone = false;
  28135. }
  28136. }
  28137. return allDone;
  28138. };
  28139. }
  28140. return TextureOptimization;
  28141. })(SceneOptimization);
  28142. BABYLON.TextureOptimization = TextureOptimization;
  28143. var HardwareScalingOptimization = (function (_super) {
  28144. __extends(HardwareScalingOptimization, _super);
  28145. function HardwareScalingOptimization(priority, maximumScale) {
  28146. var _this = this;
  28147. if (priority === void 0) { priority = 0; }
  28148. if (maximumScale === void 0) { maximumScale = 2; }
  28149. _super.call(this, priority);
  28150. this.priority = priority;
  28151. this.maximumScale = maximumScale;
  28152. this._currentScale = 1;
  28153. this.apply = function (scene) {
  28154. _this._currentScale++;
  28155. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  28156. return _this._currentScale >= _this.maximumScale;
  28157. };
  28158. }
  28159. return HardwareScalingOptimization;
  28160. })(SceneOptimization);
  28161. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  28162. var ShadowsOptimization = (function (_super) {
  28163. __extends(ShadowsOptimization, _super);
  28164. function ShadowsOptimization() {
  28165. _super.apply(this, arguments);
  28166. this.apply = function (scene) {
  28167. scene.shadowsEnabled = false;
  28168. return true;
  28169. };
  28170. }
  28171. return ShadowsOptimization;
  28172. })(SceneOptimization);
  28173. BABYLON.ShadowsOptimization = ShadowsOptimization;
  28174. var PostProcessesOptimization = (function (_super) {
  28175. __extends(PostProcessesOptimization, _super);
  28176. function PostProcessesOptimization() {
  28177. _super.apply(this, arguments);
  28178. this.apply = function (scene) {
  28179. scene.postProcessesEnabled = false;
  28180. return true;
  28181. };
  28182. }
  28183. return PostProcessesOptimization;
  28184. })(SceneOptimization);
  28185. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  28186. var LensFlaresOptimization = (function (_super) {
  28187. __extends(LensFlaresOptimization, _super);
  28188. function LensFlaresOptimization() {
  28189. _super.apply(this, arguments);
  28190. this.apply = function (scene) {
  28191. scene.lensFlaresEnabled = false;
  28192. return true;
  28193. };
  28194. }
  28195. return LensFlaresOptimization;
  28196. })(SceneOptimization);
  28197. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  28198. var ParticlesOptimization = (function (_super) {
  28199. __extends(ParticlesOptimization, _super);
  28200. function ParticlesOptimization() {
  28201. _super.apply(this, arguments);
  28202. this.apply = function (scene) {
  28203. scene.particlesEnabled = false;
  28204. return true;
  28205. };
  28206. }
  28207. return ParticlesOptimization;
  28208. })(SceneOptimization);
  28209. BABYLON.ParticlesOptimization = ParticlesOptimization;
  28210. var RenderTargetsOptimization = (function (_super) {
  28211. __extends(RenderTargetsOptimization, _super);
  28212. function RenderTargetsOptimization() {
  28213. _super.apply(this, arguments);
  28214. this.apply = function (scene) {
  28215. scene.renderTargetsEnabled = false;
  28216. return true;
  28217. };
  28218. }
  28219. return RenderTargetsOptimization;
  28220. })(SceneOptimization);
  28221. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  28222. var MergeMeshesOptimization = (function (_super) {
  28223. __extends(MergeMeshesOptimization, _super);
  28224. function MergeMeshesOptimization() {
  28225. var _this = this;
  28226. _super.apply(this, arguments);
  28227. this._canBeMerged = function (abstractMesh) {
  28228. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  28229. return false;
  28230. }
  28231. var mesh = abstractMesh;
  28232. if (!mesh.isVisible || !mesh.isEnabled()) {
  28233. return false;
  28234. }
  28235. if (mesh.instances.length > 0) {
  28236. return false;
  28237. }
  28238. if (mesh.skeleton || mesh.hasLODLevels) {
  28239. return false;
  28240. }
  28241. return true;
  28242. };
  28243. this.apply = function (scene) {
  28244. var globalPool = scene.meshes.slice(0);
  28245. var globalLength = globalPool.length;
  28246. for (var index = 0; index < globalLength; index++) {
  28247. var currentPool = new Array();
  28248. var current = globalPool[index];
  28249. // Checks
  28250. if (!_this._canBeMerged(current)) {
  28251. continue;
  28252. }
  28253. currentPool.push(current);
  28254. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  28255. var otherMesh = globalPool[subIndex];
  28256. if (!_this._canBeMerged(otherMesh)) {
  28257. continue;
  28258. }
  28259. if (otherMesh.material !== current.material) {
  28260. continue;
  28261. }
  28262. if (otherMesh.checkCollisions !== current.checkCollisions) {
  28263. continue;
  28264. }
  28265. currentPool.push(otherMesh);
  28266. globalLength--;
  28267. globalPool.splice(subIndex, 1);
  28268. subIndex--;
  28269. }
  28270. if (currentPool.length < 2) {
  28271. continue;
  28272. }
  28273. // Merge meshes
  28274. BABYLON.Mesh.MergeMeshes(currentPool);
  28275. }
  28276. return true;
  28277. };
  28278. }
  28279. return MergeMeshesOptimization;
  28280. })(SceneOptimization);
  28281. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  28282. // Options
  28283. var SceneOptimizerOptions = (function () {
  28284. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  28285. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  28286. if (trackerDuration === void 0) { trackerDuration = 2000; }
  28287. this.targetFrameRate = targetFrameRate;
  28288. this.trackerDuration = trackerDuration;
  28289. this.optimizations = new Array();
  28290. }
  28291. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  28292. var result = new SceneOptimizerOptions(targetFrameRate);
  28293. var priority = 0;
  28294. result.optimizations.push(new MergeMeshesOptimization(priority));
  28295. result.optimizations.push(new ShadowsOptimization(priority));
  28296. result.optimizations.push(new LensFlaresOptimization(priority));
  28297. // Next priority
  28298. priority++;
  28299. result.optimizations.push(new PostProcessesOptimization(priority));
  28300. result.optimizations.push(new ParticlesOptimization(priority));
  28301. // Next priority
  28302. priority++;
  28303. result.optimizations.push(new TextureOptimization(priority, 1024));
  28304. return result;
  28305. };
  28306. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  28307. var result = new SceneOptimizerOptions(targetFrameRate);
  28308. var priority = 0;
  28309. result.optimizations.push(new MergeMeshesOptimization(priority));
  28310. result.optimizations.push(new ShadowsOptimization(priority));
  28311. result.optimizations.push(new LensFlaresOptimization(priority));
  28312. // Next priority
  28313. priority++;
  28314. result.optimizations.push(new PostProcessesOptimization(priority));
  28315. result.optimizations.push(new ParticlesOptimization(priority));
  28316. // Next priority
  28317. priority++;
  28318. result.optimizations.push(new TextureOptimization(priority, 512));
  28319. // Next priority
  28320. priority++;
  28321. result.optimizations.push(new RenderTargetsOptimization(priority));
  28322. // Next priority
  28323. priority++;
  28324. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  28325. return result;
  28326. };
  28327. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  28328. var result = new SceneOptimizerOptions(targetFrameRate);
  28329. var priority = 0;
  28330. result.optimizations.push(new MergeMeshesOptimization(priority));
  28331. result.optimizations.push(new ShadowsOptimization(priority));
  28332. result.optimizations.push(new LensFlaresOptimization(priority));
  28333. // Next priority
  28334. priority++;
  28335. result.optimizations.push(new PostProcessesOptimization(priority));
  28336. result.optimizations.push(new ParticlesOptimization(priority));
  28337. // Next priority
  28338. priority++;
  28339. result.optimizations.push(new TextureOptimization(priority, 256));
  28340. // Next priority
  28341. priority++;
  28342. result.optimizations.push(new RenderTargetsOptimization(priority));
  28343. // Next priority
  28344. priority++;
  28345. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  28346. return result;
  28347. };
  28348. return SceneOptimizerOptions;
  28349. })();
  28350. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  28351. // Scene optimizer tool
  28352. var SceneOptimizer = (function () {
  28353. function SceneOptimizer() {
  28354. }
  28355. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  28356. // TODO: add an epsilon
  28357. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  28358. if (onSuccess) {
  28359. onSuccess();
  28360. }
  28361. return;
  28362. }
  28363. // Apply current level of optimizations
  28364. var allDone = true;
  28365. var noOptimizationApplied = true;
  28366. for (var index = 0; index < options.optimizations.length; index++) {
  28367. var optimization = options.optimizations[index];
  28368. if (optimization.priority === currentPriorityLevel) {
  28369. noOptimizationApplied = false;
  28370. allDone = allDone && optimization.apply(scene);
  28371. }
  28372. }
  28373. // If no optimization was applied, this is a failure :(
  28374. if (noOptimizationApplied) {
  28375. if (onFailure) {
  28376. onFailure();
  28377. }
  28378. return;
  28379. }
  28380. // If all optimizations were done, move to next level
  28381. if (allDone) {
  28382. currentPriorityLevel++;
  28383. }
  28384. // Let's the system running for a specific amount of time before checking FPS
  28385. scene.executeWhenReady(function () {
  28386. setTimeout(function () {
  28387. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  28388. }, options.trackerDuration);
  28389. });
  28390. };
  28391. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  28392. if (!options) {
  28393. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  28394. }
  28395. // Let's the system running for a specific amount of time before checking FPS
  28396. scene.executeWhenReady(function () {
  28397. setTimeout(function () {
  28398. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  28399. }, options.trackerDuration);
  28400. });
  28401. };
  28402. return SceneOptimizer;
  28403. })();
  28404. BABYLON.SceneOptimizer = SceneOptimizer;
  28405. })(BABYLON || (BABYLON = {}));
  28406. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  28407. var BABYLON;
  28408. (function (BABYLON) {
  28409. var Internals;
  28410. (function (Internals) {
  28411. var MeshLODLevel = (function () {
  28412. function MeshLODLevel(distance, mesh) {
  28413. this.distance = distance;
  28414. this.mesh = mesh;
  28415. }
  28416. return MeshLODLevel;
  28417. })();
  28418. Internals.MeshLODLevel = MeshLODLevel;
  28419. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28420. })(BABYLON || (BABYLON = {}));
  28421. //# sourceMappingURL=babylon.meshLODLevel.js.map
  28422. var BABYLON;
  28423. (function (BABYLON) {
  28424. var AudioEngine = (function () {
  28425. function AudioEngine() {
  28426. this._audioContext = null;
  28427. this._audioContextInitialized = false;
  28428. this.canUseWebAudio = false;
  28429. this.WarnedWebAudioUnsupported = false;
  28430. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  28431. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  28432. this.canUseWebAudio = true;
  28433. }
  28434. }
  28435. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  28436. get: function () {
  28437. if (!this._audioContextInitialized) {
  28438. this._initializeAudioContext();
  28439. }
  28440. return this._audioContext;
  28441. },
  28442. enumerable: true,
  28443. configurable: true
  28444. });
  28445. AudioEngine.prototype._initializeAudioContext = function () {
  28446. try {
  28447. if (this.canUseWebAudio) {
  28448. this._audioContext = new AudioContext();
  28449. // create a global volume gain node
  28450. this.masterGain = this._audioContext.createGain();
  28451. this.masterGain.gain.value = 1;
  28452. this.masterGain.connect(this._audioContext.destination);
  28453. this._audioContextInitialized = true;
  28454. }
  28455. }
  28456. catch (e) {
  28457. this.canUseWebAudio = false;
  28458. BABYLON.Tools.Error("Web Audio: " + e.message);
  28459. }
  28460. };
  28461. AudioEngine.prototype.dispose = function () {
  28462. if (this.canUseWebAudio && this._audioContextInitialized) {
  28463. if (this._connectedAnalyser) {
  28464. this._connectedAnalyser.stopDebugCanvas();
  28465. this._connectedAnalyser.dispose();
  28466. this.masterGain.disconnect();
  28467. this.masterGain.connect(this._audioContext.destination);
  28468. this._connectedAnalyser = null;
  28469. }
  28470. this.masterGain.gain.value = 1;
  28471. }
  28472. this.WarnedWebAudioUnsupported = false;
  28473. };
  28474. AudioEngine.prototype.getGlobalVolume = function () {
  28475. if (this.canUseWebAudio && this._audioContextInitialized) {
  28476. return this.masterGain.gain.value;
  28477. }
  28478. else {
  28479. return -1;
  28480. }
  28481. };
  28482. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  28483. if (this.canUseWebAudio && this._audioContextInitialized) {
  28484. this.masterGain.gain.value = newVolume;
  28485. }
  28486. };
  28487. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  28488. if (this._connectedAnalyser) {
  28489. this._connectedAnalyser.stopDebugCanvas();
  28490. }
  28491. if (this.canUseWebAudio && this._audioContextInitialized) {
  28492. this._connectedAnalyser = analyser;
  28493. this.masterGain.disconnect();
  28494. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  28495. }
  28496. };
  28497. return AudioEngine;
  28498. })();
  28499. BABYLON.AudioEngine = AudioEngine;
  28500. })(BABYLON || (BABYLON = {}));
  28501. //# sourceMappingURL=babylon.audioEngine.js.map
  28502. var BABYLON;
  28503. (function (BABYLON) {
  28504. var Sound = (function () {
  28505. /**
  28506. * Create a sound and attach it to a scene
  28507. * @param name Name of your sound
  28508. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  28509. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  28510. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  28511. */
  28512. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  28513. var _this = this;
  28514. this.autoplay = false;
  28515. this.loop = false;
  28516. this.useCustomAttenuation = false;
  28517. this.spatialSound = false;
  28518. this.refDistance = 1;
  28519. this.rolloffFactor = 1;
  28520. this.maxDistance = 100;
  28521. this.distanceModel = "linear";
  28522. this._panningModel = "equalpower";
  28523. this._playbackRate = 1;
  28524. this._startTime = 0;
  28525. this._startOffset = 0;
  28526. this._position = BABYLON.Vector3.Zero();
  28527. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  28528. this._volume = 1;
  28529. this._isLoaded = false;
  28530. this._isReadyToPlay = false;
  28531. this.isPlaying = false;
  28532. this.isPaused = false;
  28533. this._isDirectional = false;
  28534. // Used if you'd like to create a directional sound.
  28535. // If not set, the sound will be omnidirectional
  28536. this._coneInnerAngle = 360;
  28537. this._coneOuterAngle = 360;
  28538. this._coneOuterGain = 0;
  28539. this.name = name;
  28540. this._scene = scene;
  28541. this._readyToPlayCallback = readyToPlayCallback;
  28542. // Default custom attenuation function is a linear attenuation
  28543. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  28544. if (currentDistance < maxDistance) {
  28545. return currentVolume * (1 - currentDistance / maxDistance);
  28546. }
  28547. else {
  28548. return 0;
  28549. }
  28550. };
  28551. if (options) {
  28552. this.autoplay = options.autoplay || false;
  28553. this.loop = options.loop || false;
  28554. // if volume === 0, we need another way to check this option
  28555. if (options.volume !== undefined) {
  28556. this._volume = options.volume;
  28557. }
  28558. this.spatialSound = options.spatialSound || false;
  28559. this.maxDistance = options.maxDistance || 100;
  28560. this.useCustomAttenuation = options.useCustomAttenuation || false;
  28561. this.rolloffFactor = options.rolloffFactor || 1;
  28562. this.refDistance = options.refDistance || 1;
  28563. this.distanceModel = options.distanceModel || "linear";
  28564. this._playbackRate = options.playbackRate || 1;
  28565. }
  28566. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28567. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  28568. this._soundGain.gain.value = this._volume;
  28569. this._inputAudioNode = this._soundGain;
  28570. this._ouputAudioNode = this._soundGain;
  28571. if (this.spatialSound) {
  28572. this._createSpatialParameters();
  28573. }
  28574. this._scene.mainSoundTrack.AddSound(this);
  28575. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  28576. if (urlOrArrayBuffer) {
  28577. // If it's an URL
  28578. if (typeof (urlOrArrayBuffer) === "string") {
  28579. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  28580. _this._soundLoaded(data);
  28581. }, null, null, true);
  28582. }
  28583. else {
  28584. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  28585. this._soundLoaded(urlOrArrayBuffer);
  28586. }
  28587. else {
  28588. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  28589. }
  28590. }
  28591. }
  28592. }
  28593. else {
  28594. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  28595. this._scene.mainSoundTrack.AddSound(this);
  28596. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  28597. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  28598. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  28599. }
  28600. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  28601. if (this._readyToPlayCallback) {
  28602. window.setTimeout(function () {
  28603. _this._readyToPlayCallback();
  28604. }, 1000);
  28605. }
  28606. }
  28607. }
  28608. Sound.prototype.dispose = function () {
  28609. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  28610. if (this.isPlaying) {
  28611. this.stop();
  28612. }
  28613. this._isReadyToPlay = false;
  28614. if (this.soundTrackId === -1) {
  28615. this._scene.mainSoundTrack.RemoveSound(this);
  28616. }
  28617. else {
  28618. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  28619. }
  28620. if (this._soundGain) {
  28621. this._soundGain.disconnect();
  28622. this._soundGain = null;
  28623. }
  28624. if (this._soundPanner) {
  28625. this._soundPanner.disconnect();
  28626. this._soundPanner = null;
  28627. }
  28628. if (this._soundSource) {
  28629. this._soundSource.disconnect();
  28630. this._soundSource = null;
  28631. }
  28632. this._audioBuffer = null;
  28633. if (this._connectedMesh) {
  28634. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  28635. this._connectedMesh = null;
  28636. }
  28637. }
  28638. };
  28639. Sound.prototype._soundLoaded = function (audioData) {
  28640. var _this = this;
  28641. this._isLoaded = true;
  28642. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  28643. _this._audioBuffer = buffer;
  28644. _this._isReadyToPlay = true;
  28645. if (_this.autoplay) {
  28646. _this.play();
  28647. }
  28648. if (_this._readyToPlayCallback) {
  28649. _this._readyToPlayCallback();
  28650. }
  28651. }, function (error) {
  28652. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  28653. });
  28654. };
  28655. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  28656. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28657. this._audioBuffer = audioBuffer;
  28658. this._isReadyToPlay = true;
  28659. }
  28660. };
  28661. Sound.prototype.updateOptions = function (options) {
  28662. if (options) {
  28663. this.loop = options.loop || this.loop;
  28664. this.maxDistance = options.maxDistance || this.maxDistance;
  28665. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  28666. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  28667. this.refDistance = options.refDistance || this.refDistance;
  28668. this.distanceModel = options.distanceModel || this.distanceModel;
  28669. this._playbackRate = options.playbackRate || this._playbackRate;
  28670. }
  28671. };
  28672. Sound.prototype._createSpatialParameters = function () {
  28673. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28674. if (this._scene.headphone) {
  28675. this._panningModel = "HRTF";
  28676. }
  28677. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  28678. if (this.useCustomAttenuation) {
  28679. // Tricks to disable in a way embedded Web Audio attenuation
  28680. this._soundPanner.distanceModel = "linear";
  28681. this._soundPanner.maxDistance = Number.MAX_VALUE;
  28682. this._soundPanner.refDistance = 1;
  28683. this._soundPanner.rolloffFactor = 1;
  28684. this._soundPanner.panningModel = this._panningModel;
  28685. }
  28686. else {
  28687. this._soundPanner.distanceModel = this.distanceModel;
  28688. this._soundPanner.maxDistance = this.maxDistance;
  28689. this._soundPanner.refDistance = this.refDistance;
  28690. this._soundPanner.rolloffFactor = this.rolloffFactor;
  28691. this._soundPanner.panningModel = this._panningModel;
  28692. }
  28693. this._soundPanner.connect(this._ouputAudioNode);
  28694. this._inputAudioNode = this._soundPanner;
  28695. }
  28696. };
  28697. Sound.prototype.switchPanningModelToHRTF = function () {
  28698. this._panningModel = "HRTF";
  28699. this._switchPanningModel();
  28700. };
  28701. Sound.prototype.switchPanningModelToEqualPower = function () {
  28702. this._panningModel = "equalpower";
  28703. this._switchPanningModel();
  28704. };
  28705. Sound.prototype._switchPanningModel = function () {
  28706. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28707. this._soundPanner.panningModel = this._panningModel;
  28708. }
  28709. };
  28710. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  28711. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28712. this._ouputAudioNode.disconnect();
  28713. this._ouputAudioNode.connect(soundTrackAudioNode);
  28714. }
  28715. };
  28716. /**
  28717. * Transform this sound into a directional source
  28718. * @param coneInnerAngle Size of the inner cone in degree
  28719. * @param coneOuterAngle Size of the outer cone in degree
  28720. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  28721. */
  28722. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  28723. if (coneOuterAngle < coneInnerAngle) {
  28724. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  28725. return;
  28726. }
  28727. this._coneInnerAngle = coneInnerAngle;
  28728. this._coneOuterAngle = coneOuterAngle;
  28729. this._coneOuterGain = coneOuterGain;
  28730. this._isDirectional = true;
  28731. if (this.isPlaying && this.loop) {
  28732. this.stop();
  28733. this.play();
  28734. }
  28735. };
  28736. Sound.prototype.setPosition = function (newPosition) {
  28737. this._position = newPosition;
  28738. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28739. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  28740. }
  28741. };
  28742. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  28743. this._localDirection = newLocalDirection;
  28744. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  28745. this._updateDirection();
  28746. }
  28747. };
  28748. Sound.prototype._updateDirection = function () {
  28749. var mat = this._connectedMesh.getWorldMatrix();
  28750. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  28751. direction.normalize();
  28752. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  28753. };
  28754. Sound.prototype.updateDistanceFromListener = function () {
  28755. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  28756. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  28757. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  28758. }
  28759. };
  28760. Sound.prototype.setAttenuationFunction = function (callback) {
  28761. this._customAttenuationFunction = callback;
  28762. };
  28763. /**
  28764. * Play the sound
  28765. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  28766. */
  28767. Sound.prototype.play = function (time) {
  28768. var _this = this;
  28769. if (this._isReadyToPlay && this._scene.audioEnabled) {
  28770. try {
  28771. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  28772. if (!this._soundSource) {
  28773. if (this.spatialSound) {
  28774. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  28775. if (this._isDirectional) {
  28776. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  28777. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  28778. this._soundPanner.coneOuterGain = this._coneOuterGain;
  28779. if (this._connectedMesh) {
  28780. this._updateDirection();
  28781. }
  28782. else {
  28783. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  28784. }
  28785. }
  28786. }
  28787. }
  28788. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  28789. this._soundSource.buffer = this._audioBuffer;
  28790. this._soundSource.connect(this._inputAudioNode);
  28791. this._soundSource.loop = this.loop;
  28792. this._soundSource.playbackRate.value = this._playbackRate;
  28793. this._startTime = startTime;
  28794. this._soundSource.onended = function () {
  28795. _this._onended();
  28796. };
  28797. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  28798. this.isPlaying = true;
  28799. this.isPaused = false;
  28800. }
  28801. catch (ex) {
  28802. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  28803. }
  28804. }
  28805. };
  28806. Sound.prototype._onended = function () {
  28807. this.isPlaying = false;
  28808. if (this.onended) {
  28809. this.onended();
  28810. }
  28811. };
  28812. /**
  28813. * Stop the sound
  28814. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  28815. */
  28816. Sound.prototype.stop = function (time) {
  28817. if (this.isPlaying) {
  28818. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  28819. this._soundSource.stop(stopTime);
  28820. this.isPlaying = false;
  28821. }
  28822. };
  28823. Sound.prototype.pause = function () {
  28824. if (this.isPlaying) {
  28825. this.stop(0);
  28826. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  28827. this.isPaused = true;
  28828. }
  28829. };
  28830. Sound.prototype.setVolume = function (newVolume, time) {
  28831. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  28832. if (time) {
  28833. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  28834. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  28835. }
  28836. else {
  28837. this._soundGain.gain.value = newVolume;
  28838. }
  28839. }
  28840. this._volume = newVolume;
  28841. };
  28842. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  28843. this._playbackRate = newPlaybackRate;
  28844. if (this.isPlaying) {
  28845. this._soundSource.playbackRate.value = this._playbackRate;
  28846. }
  28847. };
  28848. Sound.prototype.getVolume = function () {
  28849. return this._volume;
  28850. };
  28851. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  28852. var _this = this;
  28853. this._connectedMesh = meshToConnectTo;
  28854. if (!this.spatialSound) {
  28855. this._createSpatialParameters();
  28856. this.spatialSound = true;
  28857. if (this.isPlaying && this.loop) {
  28858. this.stop();
  28859. this.play();
  28860. }
  28861. }
  28862. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  28863. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  28864. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  28865. };
  28866. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  28867. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  28868. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  28869. this._updateDirection();
  28870. }
  28871. };
  28872. return Sound;
  28873. })();
  28874. BABYLON.Sound = Sound;
  28875. })(BABYLON || (BABYLON = {}));
  28876. //# sourceMappingURL=babylon.sound.js.map
  28877. var BABYLON;
  28878. (function (BABYLON) {
  28879. var SoundTrack = (function () {
  28880. function SoundTrack(scene, options) {
  28881. this.id = -1;
  28882. this._isMainTrack = false;
  28883. this._scene = scene;
  28884. this._audioEngine = BABYLON.Engine.audioEngine;
  28885. this.soundCollection = new Array();
  28886. if (this._audioEngine.canUseWebAudio) {
  28887. this._trackGain = this._audioEngine.audioContext.createGain();
  28888. this._trackGain.connect(this._audioEngine.masterGain);
  28889. if (options) {
  28890. if (options.volume) {
  28891. this._trackGain.gain.value = options.volume;
  28892. }
  28893. if (options.mainTrack) {
  28894. this._isMainTrack = options.mainTrack;
  28895. }
  28896. }
  28897. }
  28898. if (!this._isMainTrack) {
  28899. this._scene.soundTracks.push(this);
  28900. this.id = this._scene.soundTracks.length - 1;
  28901. }
  28902. }
  28903. SoundTrack.prototype.dispose = function () {
  28904. if (this._audioEngine.canUseWebAudio) {
  28905. if (this._connectedAnalyser) {
  28906. this._connectedAnalyser.stopDebugCanvas();
  28907. }
  28908. while (this.soundCollection.length) {
  28909. this.soundCollection[0].dispose();
  28910. }
  28911. this._trackGain.disconnect();
  28912. this._trackGain = null;
  28913. }
  28914. };
  28915. SoundTrack.prototype.AddSound = function (sound) {
  28916. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28917. sound.connectToSoundTrackAudioNode(this._trackGain);
  28918. }
  28919. if (sound.soundTrackId) {
  28920. if (sound.soundTrackId === -1) {
  28921. this._scene.mainSoundTrack.RemoveSound(sound);
  28922. }
  28923. else {
  28924. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  28925. }
  28926. }
  28927. this.soundCollection.push(sound);
  28928. sound.soundTrackId = this.id;
  28929. };
  28930. SoundTrack.prototype.RemoveSound = function (sound) {
  28931. var index = this.soundCollection.indexOf(sound);
  28932. if (index !== -1) {
  28933. this.soundCollection.splice(index, 1);
  28934. }
  28935. };
  28936. SoundTrack.prototype.setVolume = function (newVolume) {
  28937. if (this._audioEngine.canUseWebAudio) {
  28938. this._trackGain.gain.value = newVolume;
  28939. }
  28940. };
  28941. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  28942. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28943. for (var i = 0; i < this.soundCollection.length; i++) {
  28944. this.soundCollection[i].switchPanningModelToHRTF();
  28945. }
  28946. }
  28947. };
  28948. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  28949. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28950. for (var i = 0; i < this.soundCollection.length; i++) {
  28951. this.soundCollection[i].switchPanningModelToEqualPower();
  28952. }
  28953. }
  28954. };
  28955. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  28956. if (this._connectedAnalyser) {
  28957. this._connectedAnalyser.stopDebugCanvas();
  28958. }
  28959. this._connectedAnalyser = analyser;
  28960. if (this._audioEngine.canUseWebAudio) {
  28961. this._trackGain.disconnect();
  28962. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  28963. }
  28964. };
  28965. return SoundTrack;
  28966. })();
  28967. BABYLON.SoundTrack = SoundTrack;
  28968. })(BABYLON || (BABYLON = {}));
  28969. //# sourceMappingURL=babylon.soundtrack.js.map
  28970. var BABYLON;
  28971. (function (BABYLON) {
  28972. var DebugLayer = (function () {
  28973. function DebugLayer(scene) {
  28974. var _this = this;
  28975. this._transformationMatrix = BABYLON.Matrix.Identity();
  28976. this._enabled = false;
  28977. this._labelsEnabled = false;
  28978. this._displayStatistics = true;
  28979. this._displayTree = false;
  28980. this._displayLogs = false;
  28981. this._identityMatrix = BABYLON.Matrix.Identity();
  28982. this.axisRatio = 0.02;
  28983. this.accentColor = "orange";
  28984. this._scene = scene;
  28985. this._syncPositions = function () {
  28986. var engine = _this._scene.getEngine();
  28987. var canvasRect = engine.getRenderingCanvasClientRect();
  28988. if (_this._showUI) {
  28989. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  28990. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  28991. _this._statsDiv.style.width = "400px";
  28992. _this._statsDiv.style.height = "auto";
  28993. _this._statsSubsetDiv.style.maxHeight = "240px";
  28994. _this._optionsDiv.style.left = "0px";
  28995. _this._optionsDiv.style.top = "10px";
  28996. _this._optionsDiv.style.width = "200px";
  28997. _this._optionsDiv.style.height = "auto";
  28998. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  28999. _this._logDiv.style.left = "0px";
  29000. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29001. _this._logDiv.style.width = "600px";
  29002. _this._logDiv.style.height = "160px";
  29003. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29004. _this._treeDiv.style.top = "10px";
  29005. _this._treeDiv.style.width = "300px";
  29006. _this._treeDiv.style.height = "auto";
  29007. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29008. }
  29009. _this._globalDiv.style.left = canvasRect.left + "px";
  29010. _this._globalDiv.style.top = canvasRect.top + "px";
  29011. _this._drawingCanvas.style.left = "0px";
  29012. _this._drawingCanvas.style.top = "0px";
  29013. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29014. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29015. var devicePixelRatio = window.devicePixelRatio || 1;
  29016. var context = _this._drawingContext;
  29017. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  29018. _this._ratio = devicePixelRatio / backingStoreRatio;
  29019. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29020. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29021. };
  29022. this._onCanvasClick = function (evt) {
  29023. _this._clickPosition = {
  29024. x: evt.clientX * _this._ratio,
  29025. y: evt.clientY * _this._ratio
  29026. };
  29027. };
  29028. this._syncUI = function () {
  29029. if (_this._showUI) {
  29030. if (_this._displayStatistics) {
  29031. _this._displayStats();
  29032. _this._statsDiv.style.display = "";
  29033. }
  29034. else {
  29035. _this._statsDiv.style.display = "none";
  29036. }
  29037. if (_this._displayLogs) {
  29038. _this._logDiv.style.display = "";
  29039. }
  29040. else {
  29041. _this._logDiv.style.display = "none";
  29042. }
  29043. if (_this._displayTree) {
  29044. _this._treeDiv.style.display = "";
  29045. if (_this._needToRefreshMeshesTree) {
  29046. _this._needToRefreshMeshesTree = false;
  29047. _this._refreshMeshesTreeContent();
  29048. }
  29049. }
  29050. else {
  29051. _this._treeDiv.style.display = "none";
  29052. }
  29053. }
  29054. };
  29055. this._syncData = function () {
  29056. if (_this._labelsEnabled || !_this._showUI) {
  29057. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29058. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29059. var engine = _this._scene.getEngine();
  29060. var viewport = _this._camera.viewport;
  29061. var globalViewport = viewport.toGlobal(engine);
  29062. // Meshes
  29063. var meshes = _this._camera.getActiveMeshes();
  29064. for (var index = 0; index < meshes.length; index++) {
  29065. var mesh = meshes.data[index];
  29066. var position = mesh.getBoundingInfo().boundingSphere.center;
  29067. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29068. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29069. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29070. }
  29071. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29072. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  29073. mesh.renderOverlay = !mesh.renderOverlay;
  29074. }, function () {
  29075. return mesh.renderOverlay ? 'red' : 'black';
  29076. });
  29077. }
  29078. }
  29079. // Cameras
  29080. var cameras = _this._scene.cameras;
  29081. for (index = 0; index < cameras.length; index++) {
  29082. var camera = cameras[index];
  29083. if (camera === _this._camera) {
  29084. continue;
  29085. }
  29086. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29087. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29088. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29089. _this._camera.detachControl(engine.getRenderingCanvas());
  29090. _this._camera = camera;
  29091. _this._camera.attachControl(engine.getRenderingCanvas());
  29092. }, function () {
  29093. return "purple";
  29094. });
  29095. }
  29096. }
  29097. // Lights
  29098. var lights = _this._scene.lights;
  29099. for (index = 0; index < lights.length; index++) {
  29100. var light = lights[index];
  29101. if (light.position) {
  29102. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29103. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29104. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29105. light.setEnabled(!light.isEnabled());
  29106. }, function () {
  29107. return light.isEnabled() ? "orange" : "gray";
  29108. });
  29109. }
  29110. }
  29111. }
  29112. }
  29113. _this._clickPosition = undefined;
  29114. };
  29115. }
  29116. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29117. while (this._treeSubsetDiv.hasChildNodes()) {
  29118. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29119. }
  29120. // Add meshes
  29121. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29122. sortedArray.sort(function (a, b) {
  29123. if (a.name === b.name) {
  29124. return 0;
  29125. }
  29126. return (a.name > b.name) ? 1 : -1;
  29127. });
  29128. for (var index = 0; index < sortedArray.length; index++) {
  29129. var mesh = sortedArray[index];
  29130. if (!mesh.isEnabled()) {
  29131. continue;
  29132. }
  29133. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29134. m.isVisible = element.checked;
  29135. }, mesh);
  29136. }
  29137. };
  29138. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29139. this._drawingContext.beginPath();
  29140. this._drawingContext.moveTo(zero.x, zero.y);
  29141. this._drawingContext.lineTo(unit.x, unit.y);
  29142. this._drawingContext.strokeStyle = color;
  29143. this._drawingContext.lineWidth = 4;
  29144. this._drawingContext.stroke();
  29145. this._drawingContext.font = "normal 14px Segoe UI";
  29146. this._drawingContext.fillStyle = color;
  29147. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29148. };
  29149. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29150. var position = mesh.getBoundingInfo().boundingSphere.center;
  29151. var worldMatrix = mesh.getWorldMatrix();
  29152. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29153. var unit = (unprojectedVector.subtract(position)).length();
  29154. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29155. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29156. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29157. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29158. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29159. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29160. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29161. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29162. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29163. };
  29164. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29165. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29166. this._drawingContext.font = "normal 12px Segoe UI";
  29167. var textMetrics = this._drawingContext.measureText(text);
  29168. var centerX = projectedPosition.x - textMetrics.width / 2;
  29169. var centerY = projectedPosition.y;
  29170. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29171. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29172. onClick();
  29173. }
  29174. this._drawingContext.beginPath();
  29175. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29176. this._drawingContext.fillStyle = getFillStyle();
  29177. this._drawingContext.globalAlpha = 0.5;
  29178. this._drawingContext.fill();
  29179. this._drawingContext.globalAlpha = 1.0;
  29180. this._drawingContext.strokeStyle = '#FFFFFF';
  29181. this._drawingContext.lineWidth = 1;
  29182. this._drawingContext.stroke();
  29183. this._drawingContext.fillStyle = "#FFFFFF";
  29184. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29185. this._drawingContext.beginPath();
  29186. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29187. this._drawingContext.fill();
  29188. }
  29189. };
  29190. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29191. if (!this._clickPosition) {
  29192. return false;
  29193. }
  29194. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29195. return false;
  29196. }
  29197. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29198. return false;
  29199. }
  29200. return true;
  29201. };
  29202. DebugLayer.prototype.isVisible = function () {
  29203. return this._enabled;
  29204. };
  29205. DebugLayer.prototype.hide = function () {
  29206. if (!this._enabled) {
  29207. return;
  29208. }
  29209. this._enabled = false;
  29210. var engine = this._scene.getEngine();
  29211. this._scene.unregisterBeforeRender(this._syncData);
  29212. this._scene.unregisterAfterRender(this._syncUI);
  29213. document.body.removeChild(this._globalDiv);
  29214. window.removeEventListener("resize", this._syncPositions);
  29215. this._scene.forceShowBoundingBoxes = false;
  29216. this._scene.forceWireframe = false;
  29217. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29218. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29219. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29220. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29221. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29222. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29223. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29224. this._scene.shadowsEnabled = true;
  29225. this._scene.particlesEnabled = true;
  29226. this._scene.postProcessesEnabled = true;
  29227. this._scene.collisionsEnabled = true;
  29228. this._scene.lightsEnabled = true;
  29229. this._scene.texturesEnabled = true;
  29230. this._scene.lensFlaresEnabled = true;
  29231. this._scene.proceduralTexturesEnabled = true;
  29232. this._scene.renderTargetsEnabled = true;
  29233. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29234. };
  29235. DebugLayer.prototype.show = function (showUI, camera) {
  29236. if (showUI === void 0) { showUI = true; }
  29237. if (camera === void 0) { camera = null; }
  29238. if (this._enabled) {
  29239. return;
  29240. }
  29241. this._enabled = true;
  29242. if (camera) {
  29243. this._camera = camera;
  29244. }
  29245. else {
  29246. this._camera = this._scene.activeCamera;
  29247. }
  29248. this._showUI = showUI;
  29249. var engine = this._scene.getEngine();
  29250. this._globalDiv = document.createElement("div");
  29251. document.body.appendChild(this._globalDiv);
  29252. this._generateDOMelements();
  29253. window.addEventListener("resize", this._syncPositions);
  29254. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29255. this._syncPositions();
  29256. this._scene.registerBeforeRender(this._syncData);
  29257. this._scene.registerAfterRender(this._syncUI);
  29258. };
  29259. DebugLayer.prototype._clearLabels = function () {
  29260. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29261. for (var index = 0; index < this._scene.meshes.length; index++) {
  29262. var mesh = this._scene.meshes[index];
  29263. mesh.renderOverlay = false;
  29264. }
  29265. };
  29266. DebugLayer.prototype._generateheader = function (root, text) {
  29267. var header = document.createElement("div");
  29268. header.innerHTML = text + "&nbsp;";
  29269. header.style.textAlign = "right";
  29270. header.style.width = "100%";
  29271. header.style.color = "white";
  29272. header.style.backgroundColor = "Black";
  29273. header.style.padding = "5px 5px 4px 0px";
  29274. header.style.marginLeft = "-5px";
  29275. header.style.fontWeight = "bold";
  29276. root.appendChild(header);
  29277. };
  29278. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29279. var label = document.createElement("label");
  29280. label.innerHTML = title;
  29281. label.style.color = color;
  29282. root.appendChild(label);
  29283. root.appendChild(document.createElement("br"));
  29284. };
  29285. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29286. if (tag === void 0) { tag = null; }
  29287. var label = document.createElement("label");
  29288. var boundingBoxesCheckbox = document.createElement("input");
  29289. boundingBoxesCheckbox.type = "checkbox";
  29290. boundingBoxesCheckbox.checked = initialState;
  29291. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29292. task(evt.target, tag);
  29293. });
  29294. label.appendChild(boundingBoxesCheckbox);
  29295. var container = document.createElement("span");
  29296. var leftPart = document.createElement("span");
  29297. var rightPart = document.createElement("span");
  29298. rightPart.style.cssFloat = "right";
  29299. leftPart.innerHTML = leftTitle;
  29300. rightPart.innerHTML = rightTitle;
  29301. rightPart.style.fontSize = "12px";
  29302. rightPart.style.maxWidth = "200px";
  29303. container.appendChild(leftPart);
  29304. container.appendChild(rightPart);
  29305. label.appendChild(container);
  29306. root.appendChild(label);
  29307. root.appendChild(document.createElement("br"));
  29308. };
  29309. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29310. if (tag === void 0) { tag = null; }
  29311. var label = document.createElement("label");
  29312. var checkBox = document.createElement("input");
  29313. checkBox.type = "checkbox";
  29314. checkBox.checked = initialState;
  29315. checkBox.addEventListener("change", function (evt) {
  29316. task(evt.target, tag);
  29317. });
  29318. label.appendChild(checkBox);
  29319. label.appendChild(document.createTextNode(title));
  29320. root.appendChild(label);
  29321. root.appendChild(document.createElement("br"));
  29322. };
  29323. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29324. if (tag === void 0) { tag = null; }
  29325. var button = document.createElement("button");
  29326. button.innerHTML = title;
  29327. button.style.height = "24px";
  29328. button.style.color = "#444444";
  29329. button.style.border = "1px solid white";
  29330. button.className = "debugLayerButton";
  29331. button.addEventListener("click", function (evt) {
  29332. task(evt.target, tag);
  29333. });
  29334. root.appendChild(button);
  29335. root.appendChild(document.createElement("br"));
  29336. };
  29337. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29338. if (tag === void 0) { tag = null; }
  29339. var label = document.createElement("label");
  29340. var boundingBoxesRadio = document.createElement("input");
  29341. boundingBoxesRadio.type = "radio";
  29342. boundingBoxesRadio.name = name;
  29343. boundingBoxesRadio.checked = initialState;
  29344. boundingBoxesRadio.addEventListener("change", function (evt) {
  29345. task(evt.target, tag);
  29346. });
  29347. label.appendChild(boundingBoxesRadio);
  29348. label.appendChild(document.createTextNode(title));
  29349. root.appendChild(label);
  29350. root.appendChild(document.createElement("br"));
  29351. };
  29352. DebugLayer.prototype._generateDOMelements = function () {
  29353. var _this = this;
  29354. this._globalDiv.id = "DebugLayer";
  29355. this._globalDiv.style.position = "absolute";
  29356. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29357. this._globalDiv.style.fontSize = "14px";
  29358. this._globalDiv.style.color = "white";
  29359. // Drawing canvas
  29360. this._drawingCanvas = document.createElement("canvas");
  29361. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29362. this._drawingCanvas.style.position = "absolute";
  29363. this._drawingCanvas.style.pointerEvents = "none";
  29364. this._drawingContext = this._drawingCanvas.getContext("2d");
  29365. this._globalDiv.appendChild(this._drawingCanvas);
  29366. if (this._showUI) {
  29367. var background = "rgba(128, 128, 128, 0.4)";
  29368. var border = "rgb(180, 180, 180) solid 1px";
  29369. // Stats
  29370. this._statsDiv = document.createElement("div");
  29371. this._statsDiv.id = "DebugLayerStats";
  29372. this._statsDiv.style.border = border;
  29373. this._statsDiv.style.position = "absolute";
  29374. this._statsDiv.style.background = background;
  29375. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29376. this._generateheader(this._statsDiv, "STATISTICS");
  29377. this._statsSubsetDiv = document.createElement("div");
  29378. this._statsSubsetDiv.style.paddingTop = "5px";
  29379. this._statsSubsetDiv.style.paddingBottom = "5px";
  29380. this._statsSubsetDiv.style.overflowY = "auto";
  29381. this._statsDiv.appendChild(this._statsSubsetDiv);
  29382. // Tree
  29383. this._treeDiv = document.createElement("div");
  29384. this._treeDiv.id = "DebugLayerTree";
  29385. this._treeDiv.style.border = border;
  29386. this._treeDiv.style.position = "absolute";
  29387. this._treeDiv.style.background = background;
  29388. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29389. this._treeDiv.style.display = "none";
  29390. this._generateheader(this._treeDiv, "MESHES TREE");
  29391. this._treeSubsetDiv = document.createElement("div");
  29392. this._treeSubsetDiv.style.paddingTop = "5px";
  29393. this._treeSubsetDiv.style.paddingRight = "5px";
  29394. this._treeSubsetDiv.style.overflowY = "auto";
  29395. this._treeSubsetDiv.style.maxHeight = "300px";
  29396. this._treeDiv.appendChild(this._treeSubsetDiv);
  29397. this._needToRefreshMeshesTree = true;
  29398. // Logs
  29399. this._logDiv = document.createElement("div");
  29400. this._logDiv.style.border = border;
  29401. this._logDiv.id = "DebugLayerLogs";
  29402. this._logDiv.style.position = "absolute";
  29403. this._logDiv.style.background = background;
  29404. this._logDiv.style.padding = "0px 0px 0px 5px";
  29405. this._logDiv.style.display = "none";
  29406. this._generateheader(this._logDiv, "LOGS");
  29407. this._logSubsetDiv = document.createElement("div");
  29408. this._logSubsetDiv.style.height = "127px";
  29409. this._logSubsetDiv.style.paddingTop = "5px";
  29410. this._logSubsetDiv.style.overflowY = "auto";
  29411. this._logSubsetDiv.style.fontSize = "12px";
  29412. this._logSubsetDiv.style.fontFamily = "consolas";
  29413. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29414. this._logDiv.appendChild(this._logSubsetDiv);
  29415. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29416. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29417. };
  29418. // Options
  29419. this._optionsDiv = document.createElement("div");
  29420. this._optionsDiv.id = "DebugLayerOptions";
  29421. this._optionsDiv.style.border = border;
  29422. this._optionsDiv.style.position = "absolute";
  29423. this._optionsDiv.style.background = background;
  29424. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29425. this._optionsDiv.style.overflowY = "auto";
  29426. this._generateheader(this._optionsDiv, "OPTIONS");
  29427. this._optionsSubsetDiv = document.createElement("div");
  29428. this._optionsSubsetDiv.style.paddingTop = "5px";
  29429. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29430. this._optionsSubsetDiv.style.overflowY = "auto";
  29431. this._optionsSubsetDiv.style.maxHeight = "200px";
  29432. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29433. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29434. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  29435. _this._displayStatistics = element.checked;
  29436. });
  29437. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  29438. _this._displayLogs = element.checked;
  29439. });
  29440. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29441. _this._displayTree = element.checked;
  29442. _this._needToRefreshMeshesTree = true;
  29443. });
  29444. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29445. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29446. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  29447. _this._scene.forceShowBoundingBoxes = element.checked;
  29448. });
  29449. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29450. _this._labelsEnabled = element.checked;
  29451. if (!_this._labelsEnabled) {
  29452. _this._clearLabels();
  29453. }
  29454. });
  29455. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29456. if (element.checked) {
  29457. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29458. }
  29459. else {
  29460. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29461. }
  29462. });
  29463. ;
  29464. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29465. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29466. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29467. if (element.checked) {
  29468. _this._scene.forceWireframe = false;
  29469. _this._scene.forcePointsCloud = false;
  29470. }
  29471. });
  29472. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29473. if (element.checked) {
  29474. _this._scene.forceWireframe = true;
  29475. _this._scene.forcePointsCloud = false;
  29476. }
  29477. });
  29478. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29479. if (element.checked) {
  29480. _this._scene.forceWireframe = false;
  29481. _this._scene.forcePointsCloud = true;
  29482. }
  29483. });
  29484. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29485. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29486. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  29487. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  29488. });
  29489. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  29490. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  29491. });
  29492. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  29493. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  29494. });
  29495. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  29496. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  29497. });
  29498. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  29499. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  29500. });
  29501. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  29502. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  29503. });
  29504. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  29505. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  29506. });
  29507. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  29508. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  29509. });
  29510. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29511. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29512. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  29513. _this._scene.animationsEnabled = element.checked;
  29514. });
  29515. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  29516. _this._scene.collisionsEnabled = element.checked;
  29517. });
  29518. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  29519. _this._scene.fogEnabled = element.checked;
  29520. });
  29521. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  29522. _this._scene.lensFlaresEnabled = element.checked;
  29523. });
  29524. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  29525. _this._scene.lightsEnabled = element.checked;
  29526. });
  29527. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  29528. _this._scene.particlesEnabled = element.checked;
  29529. });
  29530. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  29531. _this._scene.postProcessesEnabled = element.checked;
  29532. });
  29533. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  29534. _this._scene.proceduralTexturesEnabled = element.checked;
  29535. });
  29536. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  29537. _this._scene.renderTargetsEnabled = element.checked;
  29538. });
  29539. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  29540. _this._scene.shadowsEnabled = element.checked;
  29541. });
  29542. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  29543. _this._scene.skeletonsEnabled = element.checked;
  29544. });
  29545. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  29546. _this._scene.spritesEnabled = element.checked;
  29547. });
  29548. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  29549. _this._scene.texturesEnabled = element.checked;
  29550. });
  29551. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29552. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29553. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29554. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29555. if (element.checked) {
  29556. _this._scene.headphone = true;
  29557. }
  29558. });
  29559. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29560. if (element.checked) {
  29561. _this._scene.headphone = false;
  29562. }
  29563. });
  29564. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29565. _this._scene.audioEnabled = !element.checked;
  29566. });
  29567. }
  29568. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29569. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29570. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  29571. _this._scene.dumpNextRenderTargets = true;
  29572. });
  29573. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29574. this._globalDiv.appendChild(this._statsDiv);
  29575. this._globalDiv.appendChild(this._logDiv);
  29576. this._globalDiv.appendChild(this._optionsDiv);
  29577. this._globalDiv.appendChild(this._treeDiv);
  29578. }
  29579. };
  29580. DebugLayer.prototype._displayStats = function () {
  29581. var scene = this._scene;
  29582. var engine = scene.getEngine();
  29583. var glInfo = engine.getGlInfo();
  29584. 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>";
  29585. if (this.customStatsFunction) {
  29586. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29587. }
  29588. };
  29589. return DebugLayer;
  29590. })();
  29591. BABYLON.DebugLayer = DebugLayer;
  29592. })(BABYLON || (BABYLON = {}));
  29593. //# sourceMappingURL=babylon.debugLayer.js.map
  29594. var __extends = this.__extends || function (d, b) {
  29595. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  29596. function __() { this.constructor = d; }
  29597. __.prototype = b.prototype;
  29598. d.prototype = new __();
  29599. };
  29600. var BABYLON;
  29601. (function (BABYLON) {
  29602. var RawTexture = (function (_super) {
  29603. __extends(RawTexture, _super);
  29604. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  29605. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29606. if (invertY === void 0) { invertY = false; }
  29607. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29608. _super.call(this, null, scene, !generateMipMaps, invertY);
  29609. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  29610. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29611. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29612. }
  29613. // Statics
  29614. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29615. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29616. if (invertY === void 0) { invertY = false; }
  29617. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29618. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  29619. };
  29620. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29621. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29622. if (invertY === void 0) { invertY = false; }
  29623. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29624. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29625. };
  29626. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29627. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29628. if (invertY === void 0) { invertY = false; }
  29629. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29630. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29631. };
  29632. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29633. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29634. if (invertY === void 0) { invertY = false; }
  29635. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29636. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  29637. };
  29638. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29639. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29640. if (invertY === void 0) { invertY = false; }
  29641. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29642. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  29643. };
  29644. return RawTexture;
  29645. })(BABYLON.Texture);
  29646. BABYLON.RawTexture = RawTexture;
  29647. })(BABYLON || (BABYLON = {}));
  29648. //# sourceMappingURL=babylon.rawTexture.js.map
  29649. var __extends = this.__extends || function (d, b) {
  29650. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  29651. function __() { this.constructor = d; }
  29652. __.prototype = b.prototype;
  29653. d.prototype = new __();
  29654. };
  29655. var BABYLON;
  29656. (function (BABYLON) {
  29657. var IndexedVector2 = (function (_super) {
  29658. __extends(IndexedVector2, _super);
  29659. function IndexedVector2(original, index) {
  29660. _super.call(this, original.x, original.y);
  29661. this.index = index;
  29662. }
  29663. return IndexedVector2;
  29664. })(BABYLON.Vector2);
  29665. var PolygonPoints = (function () {
  29666. function PolygonPoints() {
  29667. this.elements = new Array();
  29668. }
  29669. PolygonPoints.prototype.add = function (originalPoints) {
  29670. var _this = this;
  29671. var result = new Array();
  29672. originalPoints.forEach(function (point) {
  29673. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  29674. var newPoint = new IndexedVector2(point, _this.elements.length);
  29675. result.push(newPoint);
  29676. _this.elements.push(newPoint);
  29677. }
  29678. });
  29679. return result;
  29680. };
  29681. PolygonPoints.prototype.computeBounds = function () {
  29682. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29683. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29684. this.elements.forEach(function (point) {
  29685. // x
  29686. if (point.x < lmin.x) {
  29687. lmin.x = point.x;
  29688. }
  29689. else if (point.x > lmax.x) {
  29690. lmax.x = point.x;
  29691. }
  29692. // y
  29693. if (point.y < lmin.y) {
  29694. lmin.y = point.y;
  29695. }
  29696. else if (point.y > lmax.y) {
  29697. lmax.y = point.y;
  29698. }
  29699. });
  29700. return {
  29701. min: lmin,
  29702. max: lmax,
  29703. width: lmax.x - lmin.x,
  29704. height: lmax.y - lmin.y
  29705. };
  29706. };
  29707. return PolygonPoints;
  29708. })();
  29709. var Polygon = (function () {
  29710. function Polygon() {
  29711. }
  29712. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  29713. return [
  29714. new BABYLON.Vector2(xmin, ymin),
  29715. new BABYLON.Vector2(xmax, ymin),
  29716. new BABYLON.Vector2(xmax, ymax),
  29717. new BABYLON.Vector2(xmin, ymax)
  29718. ];
  29719. };
  29720. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  29721. if (cx === void 0) { cx = 0; }
  29722. if (cy === void 0) { cy = 0; }
  29723. if (numberOfSides === void 0) { numberOfSides = 32; }
  29724. var result = new Array();
  29725. var angle = 0;
  29726. var increment = (Math.PI * 2) / numberOfSides;
  29727. for (var i = 0; i < numberOfSides; i++) {
  29728. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  29729. angle -= increment;
  29730. }
  29731. return result;
  29732. };
  29733. Polygon.Parse = function (input) {
  29734. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  29735. var i, result = [];
  29736. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  29737. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  29738. }
  29739. return result;
  29740. };
  29741. Polygon.StartingAt = function (x, y) {
  29742. return BABYLON.Path2.StartingAt(x, y);
  29743. };
  29744. return Polygon;
  29745. })();
  29746. BABYLON.Polygon = Polygon;
  29747. var PolygonMeshBuilder = (function () {
  29748. function PolygonMeshBuilder(name, contours, scene) {
  29749. this._points = new PolygonPoints();
  29750. if (!("poly2tri" in window)) {
  29751. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  29752. }
  29753. this._name = name;
  29754. this._scene = scene;
  29755. var points;
  29756. if (contours instanceof BABYLON.Path2) {
  29757. points = contours.getPoints();
  29758. }
  29759. else {
  29760. points = contours;
  29761. }
  29762. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  29763. }
  29764. PolygonMeshBuilder.prototype.addHole = function (hole) {
  29765. this._swctx.addHole(this._points.add(hole));
  29766. return this;
  29767. };
  29768. PolygonMeshBuilder.prototype.build = function (updatable) {
  29769. if (updatable === void 0) { updatable = false; }
  29770. var result = new BABYLON.Mesh(this._name, this._scene);
  29771. var normals = [];
  29772. var positions = [];
  29773. var uvs = [];
  29774. var bounds = this._points.computeBounds();
  29775. this._points.elements.forEach(function (p) {
  29776. normals.push(0, 1.0, 0);
  29777. positions.push(p.x, 0, p.y);
  29778. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  29779. });
  29780. var indices = [];
  29781. this._swctx.triangulate();
  29782. this._swctx.getTriangles().forEach(function (triangle) {
  29783. triangle.getPoints().forEach(function (point) {
  29784. indices.push(point.index);
  29785. });
  29786. });
  29787. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  29788. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  29789. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  29790. result.setIndices(indices);
  29791. return result;
  29792. };
  29793. return PolygonMeshBuilder;
  29794. })();
  29795. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  29796. })(BABYLON || (BABYLON = {}));
  29797. //# sourceMappingURL=babylon.polygonMesh.js.map
  29798. var BABYLON;
  29799. (function (BABYLON) {
  29800. var SimplificationSettings = (function () {
  29801. function SimplificationSettings(quality, distance, optimizeMesh) {
  29802. this.quality = quality;
  29803. this.distance = distance;
  29804. this.optimizeMesh = optimizeMesh;
  29805. }
  29806. return SimplificationSettings;
  29807. })();
  29808. BABYLON.SimplificationSettings = SimplificationSettings;
  29809. var SimplificationQueue = (function () {
  29810. function SimplificationQueue() {
  29811. this.running = false;
  29812. this._simplificationArray = [];
  29813. }
  29814. SimplificationQueue.prototype.addTask = function (task) {
  29815. this._simplificationArray.push(task);
  29816. };
  29817. SimplificationQueue.prototype.executeNext = function () {
  29818. var task = this._simplificationArray.pop();
  29819. if (task) {
  29820. this.running = true;
  29821. this.runSimplification(task);
  29822. }
  29823. else {
  29824. this.running = false;
  29825. }
  29826. };
  29827. SimplificationQueue.prototype.runSimplification = function (task) {
  29828. var _this = this;
  29829. if (task.parallelProcessing) {
  29830. //parallel simplifier
  29831. task.settings.forEach(function (setting) {
  29832. var simplifier = _this.getSimplifier(task);
  29833. simplifier.simplify(setting, function (newMesh) {
  29834. task.mesh.addLODLevel(setting.distance, newMesh);
  29835. newMesh.isVisible = true;
  29836. //check if it is the last
  29837. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  29838. //all done, run the success callback.
  29839. task.successCallback();
  29840. }
  29841. _this.executeNext();
  29842. });
  29843. });
  29844. }
  29845. else {
  29846. //single simplifier.
  29847. var simplifier = this.getSimplifier(task);
  29848. var runDecimation = function (setting, callback) {
  29849. simplifier.simplify(setting, function (newMesh) {
  29850. task.mesh.addLODLevel(setting.distance, newMesh);
  29851. newMesh.isVisible = true;
  29852. //run the next quality level
  29853. callback();
  29854. });
  29855. };
  29856. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  29857. runDecimation(task.settings[loop.index], function () {
  29858. loop.executeNext();
  29859. });
  29860. }, function () {
  29861. //execution ended, run the success callback.
  29862. if (task.successCallback) {
  29863. task.successCallback();
  29864. }
  29865. _this.executeNext();
  29866. });
  29867. }
  29868. };
  29869. SimplificationQueue.prototype.getSimplifier = function (task) {
  29870. switch (task.simplificationType) {
  29871. case 0 /* QUADRATIC */:
  29872. default:
  29873. return new QuadraticErrorSimplification(task.mesh);
  29874. }
  29875. };
  29876. return SimplificationQueue;
  29877. })();
  29878. BABYLON.SimplificationQueue = SimplificationQueue;
  29879. /**
  29880. * The implemented types of simplification.
  29881. * At the moment only Quadratic Error Decimation is implemented.
  29882. */
  29883. (function (SimplificationType) {
  29884. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  29885. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  29886. var SimplificationType = BABYLON.SimplificationType;
  29887. var DecimationTriangle = (function () {
  29888. function DecimationTriangle(vertices) {
  29889. this.vertices = vertices;
  29890. this.error = new Array(4);
  29891. this.deleted = false;
  29892. this.isDirty = false;
  29893. this.deletePending = false;
  29894. this.borderFactor = 0;
  29895. }
  29896. return DecimationTriangle;
  29897. })();
  29898. BABYLON.DecimationTriangle = DecimationTriangle;
  29899. var DecimationVertex = (function () {
  29900. function DecimationVertex(position, id) {
  29901. this.position = position;
  29902. this.id = id;
  29903. this.isBorder = true;
  29904. this.q = new QuadraticMatrix();
  29905. this.triangleCount = 0;
  29906. this.triangleStart = 0;
  29907. this.originalOffsets = [];
  29908. }
  29909. DecimationVertex.prototype.updatePosition = function (newPosition) {
  29910. this.position.copyFrom(newPosition);
  29911. };
  29912. return DecimationVertex;
  29913. })();
  29914. BABYLON.DecimationVertex = DecimationVertex;
  29915. var QuadraticMatrix = (function () {
  29916. function QuadraticMatrix(data) {
  29917. this.data = new Array(10);
  29918. for (var i = 0; i < 10; ++i) {
  29919. if (data && data[i]) {
  29920. this.data[i] = data[i];
  29921. }
  29922. else {
  29923. this.data[i] = 0;
  29924. }
  29925. }
  29926. }
  29927. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  29928. 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];
  29929. return det;
  29930. };
  29931. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  29932. for (var i = 0; i < 10; ++i) {
  29933. this.data[i] += matrix.data[i];
  29934. }
  29935. };
  29936. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  29937. for (var i = 0; i < 10; ++i) {
  29938. this.data[i] += data[i];
  29939. }
  29940. };
  29941. QuadraticMatrix.prototype.add = function (matrix) {
  29942. var m = new QuadraticMatrix();
  29943. for (var i = 0; i < 10; ++i) {
  29944. m.data[i] = this.data[i] + matrix.data[i];
  29945. }
  29946. return m;
  29947. };
  29948. QuadraticMatrix.FromData = function (a, b, c, d) {
  29949. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  29950. };
  29951. //returning an array to avoid garbage collection
  29952. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  29953. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  29954. };
  29955. return QuadraticMatrix;
  29956. })();
  29957. BABYLON.QuadraticMatrix = QuadraticMatrix;
  29958. var Reference = (function () {
  29959. function Reference(vertexId, triangleId) {
  29960. this.vertexId = vertexId;
  29961. this.triangleId = triangleId;
  29962. }
  29963. return Reference;
  29964. })();
  29965. BABYLON.Reference = Reference;
  29966. /**
  29967. * An implementation of the Quadratic Error simplification algorithm.
  29968. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  29969. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  29970. * @author RaananW
  29971. */
  29972. var QuadraticErrorSimplification = (function () {
  29973. function QuadraticErrorSimplification(_mesh) {
  29974. this._mesh = _mesh;
  29975. this.initialized = false;
  29976. this.syncIterations = 5000;
  29977. this.aggressiveness = 7;
  29978. this.decimationIterations = 100;
  29979. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  29980. }
  29981. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  29982. var _this = this;
  29983. this.initDecimatedMesh();
  29984. //iterating through the submeshes array, one after the other.
  29985. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  29986. _this.initWithMesh(loop.index, function () {
  29987. _this.runDecimation(settings, loop.index, function () {
  29988. loop.executeNext();
  29989. });
  29990. }, settings.optimizeMesh);
  29991. }, function () {
  29992. setTimeout(function () {
  29993. successCallback(_this._reconstructedMesh);
  29994. }, 0);
  29995. });
  29996. };
  29997. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  29998. var _this = this;
  29999. var gCount = 0;
  30000. triangle.vertices.forEach(function (vertex) {
  30001. var count = 0;
  30002. var vPos = vertex.position;
  30003. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30004. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30005. ++count;
  30006. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  30007. ++count;
  30008. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  30009. ++count;
  30010. if (count > 1) {
  30011. ++gCount;
  30012. }
  30013. ;
  30014. });
  30015. if (gCount > 1) {
  30016. console.log(triangle, gCount);
  30017. }
  30018. return gCount > 1;
  30019. };
  30020. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30021. var _this = this;
  30022. var targetCount = ~~(this.triangles.length * settings.quality);
  30023. var deletedTriangles = 0;
  30024. var triangleCount = this.triangles.length;
  30025. var iterationFunction = function (iteration, callback) {
  30026. setTimeout(function () {
  30027. if (iteration % 5 === 0) {
  30028. _this.updateMesh(iteration === 0);
  30029. }
  30030. for (var i = 0; i < _this.triangles.length; ++i) {
  30031. _this.triangles[i].isDirty = false;
  30032. }
  30033. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30034. var trianglesIterator = function (i) {
  30035. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30036. var t = _this.triangles[tIdx];
  30037. if (!t)
  30038. return;
  30039. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30040. return;
  30041. }
  30042. for (var j = 0; j < 3; ++j) {
  30043. if (t.error[j] < threshold) {
  30044. var deleted0 = [];
  30045. var deleted1 = [];
  30046. var v0 = t.vertices[j];
  30047. var v1 = t.vertices[(j + 1) % 3];
  30048. if (v0.isBorder !== v1.isBorder)
  30049. continue;
  30050. var p = BABYLON.Vector3.Zero();
  30051. var n = BABYLON.Vector3.Zero();
  30052. var uv = BABYLON.Vector2.Zero();
  30053. var color = new BABYLON.Color4(0, 0, 0, 1);
  30054. _this.calculateError(v0, v1, p, n, uv, color);
  30055. var delTr = [];
  30056. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30057. continue;
  30058. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30059. continue;
  30060. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30061. continue;
  30062. var uniqueArray = [];
  30063. delTr.forEach(function (deletedT) {
  30064. if (uniqueArray.indexOf(deletedT) === -1) {
  30065. deletedT.deletePending = true;
  30066. uniqueArray.push(deletedT);
  30067. }
  30068. });
  30069. if (uniqueArray.length % 2 != 0) {
  30070. continue;
  30071. }
  30072. v0.q = v1.q.add(v0.q);
  30073. v0.updatePosition(p);
  30074. var tStart = _this.references.length;
  30075. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30076. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30077. var tCount = _this.references.length - tStart;
  30078. if (tCount <= v0.triangleCount) {
  30079. if (tCount) {
  30080. for (var c = 0; c < tCount; c++) {
  30081. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30082. }
  30083. }
  30084. }
  30085. else {
  30086. v0.triangleStart = tStart;
  30087. }
  30088. v0.triangleCount = tCount;
  30089. break;
  30090. }
  30091. }
  30092. };
  30093. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  30094. return (triangleCount - deletedTriangles <= targetCount);
  30095. });
  30096. }, 0);
  30097. };
  30098. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30099. if (triangleCount - deletedTriangles <= targetCount)
  30100. loop.breakLoop();
  30101. else {
  30102. iterationFunction(loop.index, function () {
  30103. loop.executeNext();
  30104. });
  30105. }
  30106. }, function () {
  30107. setTimeout(function () {
  30108. //reconstruct this part of the mesh
  30109. _this.reconstructMesh(submeshIndex);
  30110. successCallback();
  30111. }, 0);
  30112. });
  30113. };
  30114. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30115. var _this = this;
  30116. this.vertices = [];
  30117. this.triangles = [];
  30118. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30119. var indices = this._mesh.getIndices();
  30120. var submesh = this._mesh.subMeshes[submeshIndex];
  30121. var findInVertices = function (positionToSearch) {
  30122. if (optimizeMesh) {
  30123. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30124. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30125. return _this.vertices[ii];
  30126. }
  30127. }
  30128. }
  30129. return null;
  30130. };
  30131. var vertexReferences = [];
  30132. var vertexInit = function (i) {
  30133. var offset = i + submesh.verticesStart;
  30134. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30135. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30136. vertex.originalOffsets.push(offset);
  30137. if (vertex.id == _this.vertices.length) {
  30138. _this.vertices.push(vertex);
  30139. }
  30140. vertexReferences.push(vertex.id);
  30141. };
  30142. //var totalVertices = mesh.getTotalVertices();
  30143. var totalVertices = submesh.verticesCount;
  30144. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30145. var indicesInit = function (i) {
  30146. var offset = (submesh.indexStart / 3) + i;
  30147. var pos = (offset * 3);
  30148. var i0 = indices[pos + 0];
  30149. var i1 = indices[pos + 1];
  30150. var i2 = indices[pos + 2];
  30151. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30152. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30153. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30154. var triangle = new DecimationTriangle([v0, v1, v2]);
  30155. triangle.originalOffset = pos;
  30156. _this.triangles.push(triangle);
  30157. };
  30158. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30159. _this.init(callback);
  30160. });
  30161. });
  30162. };
  30163. QuadraticErrorSimplification.prototype.init = function (callback) {
  30164. var _this = this;
  30165. var triangleInit1 = function (i) {
  30166. var t = _this.triangles[i];
  30167. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30168. for (var j = 0; j < 3; j++) {
  30169. 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))));
  30170. }
  30171. };
  30172. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30173. var triangleInit2 = function (i) {
  30174. var t = _this.triangles[i];
  30175. for (var j = 0; j < 3; ++j) {
  30176. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30177. }
  30178. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30179. };
  30180. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30181. _this.initialized = true;
  30182. callback();
  30183. });
  30184. });
  30185. };
  30186. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30187. var newTriangles = [];
  30188. var i;
  30189. for (i = 0; i < this.vertices.length; ++i) {
  30190. this.vertices[i].triangleCount = 0;
  30191. }
  30192. var t;
  30193. var j;
  30194. for (i = 0; i < this.triangles.length; ++i) {
  30195. if (!this.triangles[i].deleted) {
  30196. t = this.triangles[i];
  30197. for (j = 0; j < 3; ++j) {
  30198. t.vertices[j].triangleCount = 1;
  30199. }
  30200. newTriangles.push(t);
  30201. }
  30202. }
  30203. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  30204. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  30205. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  30206. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  30207. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30208. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30209. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30210. var vertexCount = 0;
  30211. for (i = 0; i < this.vertices.length; ++i) {
  30212. var vertex = this.vertices[i];
  30213. vertex.id = vertexCount;
  30214. if (vertex.triangleCount) {
  30215. vertex.originalOffsets.forEach(function (originalOffset) {
  30216. newPositionData.push(vertex.position.x);
  30217. newPositionData.push(vertex.position.y);
  30218. newPositionData.push(vertex.position.z);
  30219. newNormalData.push(normalData[originalOffset * 3]);
  30220. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30221. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30222. if (uvs && uvs.length) {
  30223. newUVsData.push(uvs[(originalOffset * 2)]);
  30224. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30225. }
  30226. else if (colorsData && colorsData.length) {
  30227. newColorsData.push(colorsData[(originalOffset * 4)]);
  30228. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30229. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30230. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30231. }
  30232. ++vertexCount;
  30233. });
  30234. }
  30235. }
  30236. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30237. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30238. var submeshesArray = this._reconstructedMesh.subMeshes;
  30239. this._reconstructedMesh.subMeshes = [];
  30240. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30241. var originalIndices = this._mesh.getIndices();
  30242. for (i = 0; i < newTriangles.length; ++i) {
  30243. var t = newTriangles[i];
  30244. //now get the new referencing point for each vertex
  30245. [0, 1, 2].forEach(function (idx) {
  30246. var id = originalIndices[t.originalOffset + idx];
  30247. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30248. if (offset < 0)
  30249. offset = 0;
  30250. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30251. });
  30252. }
  30253. //overwriting the old vertex buffers and indices.
  30254. this._reconstructedMesh.setIndices(newIndicesArray);
  30255. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30256. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30257. if (newUVsData.length > 0)
  30258. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30259. if (newColorsData.length > 0)
  30260. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30261. //create submesh
  30262. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30263. if (submeshIndex > 0) {
  30264. this._reconstructedMesh.subMeshes = [];
  30265. submeshesArray.forEach(function (submesh) {
  30266. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30267. });
  30268. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30269. }
  30270. };
  30271. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30272. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30273. this._reconstructedMesh.material = this._mesh.material;
  30274. this._reconstructedMesh.parent = this._mesh.parent;
  30275. this._reconstructedMesh.isVisible = false;
  30276. };
  30277. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30278. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30279. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30280. if (t.deleted)
  30281. continue;
  30282. var s = this.references[vertex1.triangleStart + i].vertexId;
  30283. var v1 = t.vertices[(s + 1) % 3];
  30284. var v2 = t.vertices[(s + 2) % 3];
  30285. if ((v1 === vertex2 || v2 === vertex2)) {
  30286. deletedArray[i] = true;
  30287. delTr.push(t);
  30288. continue;
  30289. }
  30290. var d1 = v1.position.subtract(point);
  30291. d1 = d1.normalize();
  30292. var d2 = v2.position.subtract(point);
  30293. d2 = d2.normalize();
  30294. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30295. return true;
  30296. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30297. deletedArray[i] = false;
  30298. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30299. return true;
  30300. }
  30301. return false;
  30302. };
  30303. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30304. var newDeleted = deletedTriangles;
  30305. for (var i = 0; i < vertex.triangleCount; ++i) {
  30306. var ref = this.references[vertex.triangleStart + i];
  30307. var t = this.triangles[ref.triangleId];
  30308. if (t.deleted)
  30309. continue;
  30310. if (deletedArray[i] && t.deletePending) {
  30311. t.deleted = true;
  30312. newDeleted++;
  30313. continue;
  30314. }
  30315. t.vertices[ref.vertexId] = origVertex;
  30316. t.isDirty = true;
  30317. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30318. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30319. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30320. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30321. this.references.push(ref);
  30322. }
  30323. return newDeleted;
  30324. };
  30325. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30326. for (var i = 0; i < this.vertices.length; ++i) {
  30327. var vCount = [];
  30328. var vId = [];
  30329. var v = this.vertices[i];
  30330. var j;
  30331. for (j = 0; j < v.triangleCount; ++j) {
  30332. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30333. for (var ii = 0; ii < 3; ii++) {
  30334. var ofs = 0;
  30335. var vv = triangle.vertices[ii];
  30336. while (ofs < vCount.length) {
  30337. if (vId[ofs] === vv.id)
  30338. break;
  30339. ++ofs;
  30340. }
  30341. if (ofs === vCount.length) {
  30342. vCount.push(1);
  30343. vId.push(vv.id);
  30344. }
  30345. else {
  30346. vCount[ofs]++;
  30347. }
  30348. }
  30349. }
  30350. for (j = 0; j < vCount.length; ++j) {
  30351. if (vCount[j] === 1) {
  30352. this.vertices[vId[j]].isBorder = true;
  30353. }
  30354. else {
  30355. this.vertices[vId[j]].isBorder = false;
  30356. }
  30357. }
  30358. }
  30359. };
  30360. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30361. if (identifyBorders === void 0) { identifyBorders = false; }
  30362. var i;
  30363. if (!identifyBorders) {
  30364. var newTrianglesVector = [];
  30365. for (i = 0; i < this.triangles.length; ++i) {
  30366. if (!this.triangles[i].deleted) {
  30367. newTrianglesVector.push(this.triangles[i]);
  30368. }
  30369. }
  30370. this.triangles = newTrianglesVector;
  30371. }
  30372. for (i = 0; i < this.vertices.length; ++i) {
  30373. this.vertices[i].triangleCount = 0;
  30374. this.vertices[i].triangleStart = 0;
  30375. }
  30376. var t;
  30377. var j;
  30378. var v;
  30379. for (i = 0; i < this.triangles.length; ++i) {
  30380. t = this.triangles[i];
  30381. for (j = 0; j < 3; ++j) {
  30382. v = t.vertices[j];
  30383. v.triangleCount++;
  30384. }
  30385. }
  30386. var tStart = 0;
  30387. for (i = 0; i < this.vertices.length; ++i) {
  30388. this.vertices[i].triangleStart = tStart;
  30389. tStart += this.vertices[i].triangleCount;
  30390. this.vertices[i].triangleCount = 0;
  30391. }
  30392. var newReferences = new Array(this.triangles.length * 3);
  30393. for (i = 0; i < this.triangles.length; ++i) {
  30394. t = this.triangles[i];
  30395. for (j = 0; j < 3; ++j) {
  30396. v = t.vertices[j];
  30397. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30398. v.triangleCount++;
  30399. }
  30400. }
  30401. this.references = newReferences;
  30402. if (identifyBorders) {
  30403. this.identifyBorder();
  30404. }
  30405. };
  30406. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30407. var x = point.x;
  30408. var y = point.y;
  30409. var z = point.z;
  30410. 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];
  30411. };
  30412. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30413. var q = vertex1.q.add(vertex2.q);
  30414. var border = vertex1.isBorder && vertex2.isBorder;
  30415. var error = 0;
  30416. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30417. if (qDet !== 0 && !border) {
  30418. if (!pointResult) {
  30419. pointResult = BABYLON.Vector3.Zero();
  30420. }
  30421. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30422. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30423. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30424. error = this.vertexError(q, pointResult);
  30425. }
  30426. else {
  30427. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30428. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30429. var error1 = this.vertexError(q, vertex1.position);
  30430. var error2 = this.vertexError(q, vertex2.position);
  30431. var error3 = this.vertexError(q, p3);
  30432. error = Math.min(error1, error2, error3);
  30433. if (error === error1) {
  30434. if (pointResult) {
  30435. pointResult.copyFrom(vertex1.position);
  30436. }
  30437. }
  30438. else if (error === error2) {
  30439. if (pointResult) {
  30440. pointResult.copyFrom(vertex2.position);
  30441. }
  30442. }
  30443. else {
  30444. if (pointResult) {
  30445. pointResult.copyFrom(p3);
  30446. }
  30447. }
  30448. }
  30449. return error;
  30450. };
  30451. return QuadraticErrorSimplification;
  30452. })();
  30453. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30454. })(BABYLON || (BABYLON = {}));
  30455. //# sourceMappingURL=babylon.meshSimplification.js.map
  30456. var BABYLON;
  30457. (function (BABYLON) {
  30458. var Analyser = (function () {
  30459. function Analyser(scene) {
  30460. this.SMOOTHING = 0.75;
  30461. this.FFT_SIZE = 512;
  30462. this.BARGRAPHAMPLITUDE = 256;
  30463. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  30464. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  30465. this._scene = scene;
  30466. this._audioEngine = BABYLON.Engine.audioEngine;
  30467. if (this._audioEngine.canUseWebAudio) {
  30468. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  30469. this._webAudioAnalyser.minDecibels = -140;
  30470. this._webAudioAnalyser.maxDecibels = 0;
  30471. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30472. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30473. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  30474. }
  30475. }
  30476. Analyser.prototype.getFrequencyBinCount = function () {
  30477. if (this._audioEngine.canUseWebAudio) {
  30478. return this._webAudioAnalyser.frequencyBinCount;
  30479. }
  30480. else {
  30481. return 0;
  30482. }
  30483. };
  30484. Analyser.prototype.getByteFrequencyData = function () {
  30485. if (this._audioEngine.canUseWebAudio) {
  30486. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30487. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30488. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  30489. }
  30490. return this._byteFreqs;
  30491. };
  30492. Analyser.prototype.getByteTimeDomainData = function () {
  30493. if (this._audioEngine.canUseWebAudio) {
  30494. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30495. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30496. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  30497. }
  30498. return this._byteTime;
  30499. };
  30500. Analyser.prototype.getFloatFrequencyData = function () {
  30501. if (this._audioEngine.canUseWebAudio) {
  30502. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30503. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30504. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  30505. }
  30506. return this._floatFreqs;
  30507. };
  30508. Analyser.prototype.drawDebugCanvas = function () {
  30509. var _this = this;
  30510. if (this._audioEngine.canUseWebAudio) {
  30511. if (!this._debugCanvas) {
  30512. this._debugCanvas = document.createElement("canvas");
  30513. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  30514. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  30515. this._debugCanvas.style.position = "absolute";
  30516. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  30517. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  30518. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  30519. document.body.appendChild(this._debugCanvas);
  30520. this._registerFunc = function () {
  30521. _this.drawDebugCanvas();
  30522. };
  30523. this._scene.registerBeforeRender(this._registerFunc);
  30524. }
  30525. if (this._registerFunc) {
  30526. var workingArray = this.getByteFrequencyData();
  30527. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  30528. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  30529. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  30530. var value = workingArray[i];
  30531. var percent = value / this.BARGRAPHAMPLITUDE;
  30532. var height = this.DEBUGCANVASSIZE.height * percent;
  30533. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  30534. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  30535. var hue = i / this.getFrequencyBinCount() * 360;
  30536. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  30537. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  30538. }
  30539. }
  30540. }
  30541. };
  30542. Analyser.prototype.stopDebugCanvas = function () {
  30543. if (this._debugCanvas) {
  30544. this._scene.unregisterBeforeRender(this._registerFunc);
  30545. this._registerFunc = null;
  30546. document.body.removeChild(this._debugCanvas);
  30547. this._debugCanvas = null;
  30548. this._debugCanvasContext = null;
  30549. }
  30550. };
  30551. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  30552. if (this._audioEngine.canUseWebAudio) {
  30553. inputAudioNode.connect(this._webAudioAnalyser);
  30554. this._webAudioAnalyser.connect(outputAudioNode);
  30555. }
  30556. };
  30557. Analyser.prototype.dispose = function () {
  30558. if (this._audioEngine.canUseWebAudio) {
  30559. this._webAudioAnalyser.disconnect();
  30560. }
  30561. };
  30562. return Analyser;
  30563. })();
  30564. BABYLON.Analyser = Analyser;
  30565. })(BABYLON || (BABYLON = {}));
  30566. //# sourceMappingURL=babylon.analyser.js.map
  30567. var BABYLON;
  30568. (function (BABYLON) {
  30569. var DepthRenderer = (function () {
  30570. function DepthRenderer(scene, type) {
  30571. var _this = this;
  30572. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  30573. this._viewMatrix = BABYLON.Matrix.Zero();
  30574. this._projectionMatrix = BABYLON.Matrix.Zero();
  30575. this._transformMatrix = BABYLON.Matrix.Zero();
  30576. this._worldViewProjection = BABYLON.Matrix.Zero();
  30577. this._scene = scene;
  30578. var engine = scene.getEngine();
  30579. // Render target
  30580. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  30581. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30582. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30583. this._depthMap.refreshRate = 1;
  30584. this._depthMap.renderParticles = false;
  30585. this._depthMap.renderList = null;
  30586. // set default depth value to 1.0 (far away)
  30587. this._depthMap.onClear = function (engine) {
  30588. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  30589. };
  30590. // Custom render function
  30591. var renderSubMesh = function (subMesh) {
  30592. var mesh = subMesh.getRenderingMesh();
  30593. var scene = _this._scene;
  30594. var engine = scene.getEngine();
  30595. // Culling
  30596. engine.setState(subMesh.getMaterial().backFaceCulling);
  30597. // Managing instances
  30598. var batch = mesh._getInstancesRenderList(subMesh._id);
  30599. if (batch.mustReturn) {
  30600. return;
  30601. }
  30602. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  30603. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  30604. engine.enableEffect(_this._effect);
  30605. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  30606. var material = subMesh.getMaterial();
  30607. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30608. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  30609. // Alpha test
  30610. if (material && material.needAlphaTesting()) {
  30611. var alphaTexture = material.getAlphaTestTexture();
  30612. _this._effect.setTexture("diffuseSampler", alphaTexture);
  30613. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30614. }
  30615. // Bones
  30616. if (mesh.useBones) {
  30617. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30618. }
  30619. // Draw
  30620. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  30621. }
  30622. };
  30623. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  30624. var index;
  30625. for (index = 0; index < opaqueSubMeshes.length; index++) {
  30626. renderSubMesh(opaqueSubMeshes.data[index]);
  30627. }
  30628. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  30629. renderSubMesh(alphaTestSubMeshes.data[index]);
  30630. }
  30631. };
  30632. }
  30633. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  30634. var defines = [];
  30635. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30636. var mesh = subMesh.getMesh();
  30637. var scene = mesh.getScene();
  30638. var material = subMesh.getMaterial();
  30639. // Alpha test
  30640. if (material && material.needAlphaTesting()) {
  30641. defines.push("#define ALPHATEST");
  30642. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30643. attribs.push(BABYLON.VertexBuffer.UVKind);
  30644. defines.push("#define UV1");
  30645. }
  30646. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30647. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30648. defines.push("#define UV2");
  30649. }
  30650. }
  30651. // Bones
  30652. if (mesh.useBones) {
  30653. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30654. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30655. defines.push("#define BONES");
  30656. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30657. }
  30658. // Instances
  30659. if (useInstances) {
  30660. defines.push("#define INSTANCES");
  30661. attribs.push("world0");
  30662. attribs.push("world1");
  30663. attribs.push("world2");
  30664. attribs.push("world3");
  30665. }
  30666. // Get correct effect
  30667. var join = defines.join("\n");
  30668. if (this._cachedDefines !== join) {
  30669. this._cachedDefines = join;
  30670. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  30671. }
  30672. return this._effect.isReady();
  30673. };
  30674. DepthRenderer.prototype.getDepthMap = function () {
  30675. return this._depthMap;
  30676. };
  30677. // Methods
  30678. DepthRenderer.prototype.dispose = function () {
  30679. this._depthMap.dispose();
  30680. };
  30681. return DepthRenderer;
  30682. })();
  30683. BABYLON.DepthRenderer = DepthRenderer;
  30684. })(BABYLON || (BABYLON = {}));
  30685. //# sourceMappingURL=babylon.depthRenderer.js.map
  30686. var __extends = this.__extends || function (d, b) {
  30687. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30688. function __() { this.constructor = d; }
  30689. __.prototype = b.prototype;
  30690. d.prototype = new __();
  30691. };
  30692. var BABYLON;
  30693. (function (BABYLON) {
  30694. var SSAORenderingPipeline = (function (_super) {
  30695. __extends(SSAORenderingPipeline, _super);
  30696. /**
  30697. * @constructor
  30698. * @param {string} name - The rendering pipeline name
  30699. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  30700. * @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 }
  30701. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  30702. */
  30703. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  30704. var _this = this;
  30705. _super.call(this, scene.getEngine(), name);
  30706. // Members
  30707. /**
  30708. * The PassPostProcess id in the pipeline that contains the original scene color
  30709. * @type {string}
  30710. */
  30711. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  30712. /**
  30713. * The SSAO PostProcess id in the pipeline
  30714. * @type {string}
  30715. */
  30716. this.SSAORenderEffect = "SSAORenderEffect";
  30717. /**
  30718. * The horizontal blur PostProcess id in the pipeline
  30719. * @type {string}
  30720. */
  30721. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  30722. /**
  30723. * The vertical blur PostProcess id in the pipeline
  30724. * @type {string}
  30725. */
  30726. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  30727. /**
  30728. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  30729. * @type {string}
  30730. */
  30731. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  30732. /**
  30733. * The output strength of the SSAO post-process. Default value is 1.0.
  30734. * @type {number}
  30735. */
  30736. this.totalStrength = 1.0;
  30737. /**
  30738. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  30739. * @type {number}
  30740. */
  30741. this.radius = 0.0002;
  30742. /**
  30743. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  30744. * Must not be equal to fallOff and superior to fallOff.
  30745. * Default value is 0.0075
  30746. * @type {number}
  30747. */
  30748. this.area = 0.0075;
  30749. /**
  30750. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  30751. * Must not be equal to area and inferior to area.
  30752. * Default value is 0.0002
  30753. * @type {number}
  30754. */
  30755. this.fallOff = 0.0002;
  30756. this._firstUpdate = true;
  30757. this._scene = scene;
  30758. // Set up assets
  30759. this._createRandomTexture();
  30760. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  30761. var ssaoRatio = ratio.ssaoRatio || ratio;
  30762. var combineRatio = ratio.combineRatio || ratio;
  30763. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  30764. this._createSSAOPostProcess(ssaoRatio);
  30765. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  30766. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  30767. this._createSSAOCombinePostProcess(combineRatio);
  30768. // Set up pipeline
  30769. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  30770. return _this._originalColorPostProcess;
  30771. }, true));
  30772. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  30773. return _this._ssaoPostProcess;
  30774. }, true));
  30775. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  30776. return _this._blurHPostProcess;
  30777. }, true));
  30778. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  30779. return _this._blurVPostProcess;
  30780. }, true));
  30781. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  30782. return _this._ssaoCombinePostProcess;
  30783. }, true));
  30784. // Finish
  30785. scene.postProcessRenderPipelineManager.addPipeline(this);
  30786. if (cameras)
  30787. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  30788. }
  30789. // Public Methods
  30790. /**
  30791. * Returns the horizontal blur PostProcess
  30792. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  30793. */
  30794. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  30795. return this._blurHPostProcess;
  30796. };
  30797. /**
  30798. * Returns the vertical blur PostProcess
  30799. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  30800. */
  30801. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  30802. return this._blurVPostProcess;
  30803. };
  30804. /**
  30805. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  30806. */
  30807. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  30808. if (disableDepthRender === void 0) { disableDepthRender = false; }
  30809. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  30810. this._originalColorPostProcess = undefined;
  30811. this._ssaoPostProcess = undefined;
  30812. this._blurHPostProcess = undefined;
  30813. this._blurVPostProcess = undefined;
  30814. this._ssaoCombinePostProcess = undefined;
  30815. this._randomTexture.dispose();
  30816. if (disableDepthRender)
  30817. this._scene.disableDepthRenderer();
  30818. };
  30819. // Private Methods
  30820. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  30821. var _this = this;
  30822. var sampleSphere = [
  30823. 0.5381,
  30824. 0.1856,
  30825. -0.4319,
  30826. 0.1379,
  30827. 0.2486,
  30828. 0.4430,
  30829. 0.3371,
  30830. 0.5679,
  30831. -0.0057,
  30832. -0.6999,
  30833. -0.0451,
  30834. -0.0019,
  30835. 0.0689,
  30836. -0.1598,
  30837. -0.8547,
  30838. 0.0560,
  30839. 0.0069,
  30840. -0.1843,
  30841. -0.0146,
  30842. 0.1402,
  30843. 0.0762,
  30844. 0.0100,
  30845. -0.1924,
  30846. -0.0344,
  30847. -0.3577,
  30848. -0.5301,
  30849. -0.4358,
  30850. -0.3169,
  30851. 0.1063,
  30852. 0.0158,
  30853. 0.0103,
  30854. -0.5869,
  30855. 0.0046,
  30856. -0.0897,
  30857. -0.4940,
  30858. 0.3287,
  30859. 0.7119,
  30860. -0.0154,
  30861. -0.0918,
  30862. -0.0533,
  30863. 0.0596,
  30864. -0.5411,
  30865. 0.0352,
  30866. -0.0631,
  30867. 0.5460,
  30868. -0.4776,
  30869. 0.2847,
  30870. -0.0271
  30871. ];
  30872. var samplesFactor = 1.0 / 16.0;
  30873. 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);
  30874. this._ssaoPostProcess.onApply = function (effect) {
  30875. if (_this._firstUpdate) {
  30876. effect.setArray3("sampleSphere", sampleSphere);
  30877. effect.setFloat("samplesFactor", samplesFactor);
  30878. effect.setFloat("randTextureTiles", 4.0 / ratio);
  30879. _this._firstUpdate = false;
  30880. }
  30881. effect.setFloat("totalStrength", _this.totalStrength);
  30882. effect.setFloat("radius", _this.radius);
  30883. effect.setFloat("area", _this.area);
  30884. effect.setFloat("fallOff", _this.fallOff);
  30885. effect.setTexture("textureSampler", _this._depthTexture);
  30886. effect.setTexture("randomSampler", _this._randomTexture);
  30887. };
  30888. };
  30889. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  30890. var _this = this;
  30891. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30892. this._ssaoCombinePostProcess.onApply = function (effect) {
  30893. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  30894. };
  30895. };
  30896. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  30897. var size = 512;
  30898. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  30899. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30900. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30901. var context = this._randomTexture.getContext();
  30902. var rand = function (min, max) {
  30903. return Math.random() * (max - min) + min;
  30904. };
  30905. for (var x = 0; x < size; x++) {
  30906. for (var y = 0; y < size; y++) {
  30907. var randVector = BABYLON.Vector3.Zero();
  30908. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  30909. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  30910. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  30911. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  30912. context.fillRect(x, y, 1, 1);
  30913. }
  30914. }
  30915. this._randomTexture.update(false);
  30916. };
  30917. return SSAORenderingPipeline;
  30918. })(BABYLON.PostProcessRenderPipeline);
  30919. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  30920. })(BABYLON || (BABYLON = {}));
  30921. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  30922. var __extends = this.__extends || function (d, b) {
  30923. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30924. function __() { this.constructor = d; }
  30925. __.prototype = b.prototype;
  30926. d.prototype = new __();
  30927. };
  30928. var BABYLON;
  30929. (function (BABYLON) {
  30930. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  30931. var VolumetricLightScatteringPostProcess = (function (_super) {
  30932. __extends(VolumetricLightScatteringPostProcess, _super);
  30933. /**
  30934. * @constructor
  30935. * @param {string} name - The post-process name
  30936. * @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)
  30937. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  30938. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  30939. * @param {number} samples - The post-process quality, default 100
  30940. * @param {number} samplingMode - The post-process filtering mode
  30941. * @param {BABYLON.Engine} engine - The babylon engine
  30942. * @param {boolean} reusable - If the post-process is reusable
  30943. */
  30944. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  30945. var _this = this;
  30946. if (samples === void 0) { samples = 100; }
  30947. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  30948. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  30949. this._screenCoordinates = BABYLON.Vector2.Zero();
  30950. /**
  30951. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  30952. * @type {boolean}
  30953. */
  30954. this.useCustomMeshPosition = false;
  30955. /**
  30956. * If the post-process should inverse the light scattering direction
  30957. * @type {boolean}
  30958. */
  30959. this.invert = true;
  30960. /**
  30961. * Array containing the excluded meshes not rendered in the internal pass
  30962. */
  30963. this.excludedMeshes = new Array();
  30964. this.exposure = 0.3;
  30965. this.decay = 0.96815;
  30966. this.weight = 0.58767;
  30967. this.density = 0.926;
  30968. var scene = camera.getScene();
  30969. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  30970. // Configure mesh
  30971. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  30972. // Configure
  30973. this._createPass(scene, ratio.passRatio || ratio);
  30974. this.onApply = function (effect) {
  30975. _this._updateMeshScreenCoordinates(scene);
  30976. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  30977. effect.setFloat("exposure", _this.exposure);
  30978. effect.setFloat("decay", _this.decay);
  30979. effect.setFloat("weight", _this.weight);
  30980. effect.setFloat("density", _this.density);
  30981. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  30982. };
  30983. }
  30984. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  30985. var mesh = subMesh.getMesh();
  30986. var defines = [];
  30987. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30988. var material = subMesh.getMaterial();
  30989. var needUV = false;
  30990. // Render this.mesh as default
  30991. if (mesh === this.mesh) {
  30992. defines.push("#define BASIC_RENDER");
  30993. defines.push("#define NEED_UV");
  30994. needUV = true;
  30995. }
  30996. // Alpha test
  30997. if (material) {
  30998. if (material.needAlphaTesting() || mesh === this.mesh)
  30999. defines.push("#define ALPHATEST");
  31000. if (material.opacityTexture !== undefined) {
  31001. defines.push("#define OPACITY");
  31002. if (material.opacityTexture.getAlphaFromRGB)
  31003. defines.push("#define OPACITYRGB");
  31004. if (!needUV)
  31005. defines.push("#define NEED_UV");
  31006. }
  31007. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31008. attribs.push(BABYLON.VertexBuffer.UVKind);
  31009. defines.push("#define UV1");
  31010. }
  31011. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31012. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31013. defines.push("#define UV2");
  31014. }
  31015. }
  31016. // Bones
  31017. if (mesh.useBones) {
  31018. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31019. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31020. defines.push("#define BONES");
  31021. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31022. }
  31023. // Instances
  31024. if (useInstances) {
  31025. defines.push("#define INSTANCES");
  31026. attribs.push("world0");
  31027. attribs.push("world1");
  31028. attribs.push("world2");
  31029. attribs.push("world3");
  31030. }
  31031. // Get correct effect
  31032. var join = defines.join("\n");
  31033. if (this._cachedDefines !== join) {
  31034. this._cachedDefines = join;
  31035. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  31036. }
  31037. return this._volumetricLightScatteringPass.isReady();
  31038. };
  31039. /**
  31040. * Sets the new light position for light scattering effect
  31041. * @param {BABYLON.Vector3} The new custom light position
  31042. */
  31043. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  31044. this._customMeshPosition = position;
  31045. };
  31046. /**
  31047. * Returns the light position for light scattering effect
  31048. * @return {BABYLON.Vector3} The custom light position
  31049. */
  31050. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  31051. return this._customMeshPosition;
  31052. };
  31053. /**
  31054. * Disposes the internal assets and detaches the post-process from the camera
  31055. */
  31056. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  31057. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  31058. if (rttIndex !== -1) {
  31059. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  31060. }
  31061. this._volumetricLightScatteringRTT.dispose();
  31062. _super.prototype.dispose.call(this, camera);
  31063. };
  31064. /**
  31065. * Returns the render target texture used by the post-process
  31066. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  31067. */
  31068. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  31069. return this._volumetricLightScatteringRTT;
  31070. };
  31071. // Private methods
  31072. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  31073. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  31074. return true;
  31075. }
  31076. return false;
  31077. };
  31078. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  31079. var _this = this;
  31080. var engine = scene.getEngine();
  31081. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  31082. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31083. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31084. this._volumetricLightScatteringRTT.renderList = null;
  31085. this._volumetricLightScatteringRTT.renderParticles = false;
  31086. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  31087. // Custom render function for submeshes
  31088. var renderSubMesh = function (subMesh) {
  31089. var mesh = subMesh.getRenderingMesh();
  31090. if (_this._meshExcluded(mesh)) {
  31091. return;
  31092. }
  31093. var scene = mesh.getScene();
  31094. var engine = scene.getEngine();
  31095. // Culling
  31096. engine.setState(subMesh.getMaterial().backFaceCulling);
  31097. // Managing instances
  31098. var batch = mesh._getInstancesRenderList(subMesh._id);
  31099. if (batch.mustReturn) {
  31100. return;
  31101. }
  31102. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31103. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31104. engine.enableEffect(_this._volumetricLightScatteringPass);
  31105. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  31106. var material = subMesh.getMaterial();
  31107. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  31108. // Alpha test
  31109. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  31110. var alphaTexture = material.getAlphaTestTexture();
  31111. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  31112. if (alphaTexture) {
  31113. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31114. }
  31115. if (material.opacityTexture !== undefined) {
  31116. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  31117. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  31118. }
  31119. }
  31120. // Bones
  31121. if (mesh.useBones) {
  31122. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31123. }
  31124. // Draw
  31125. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  31126. }
  31127. };
  31128. // Render target texture callbacks
  31129. var savedSceneClearColor;
  31130. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  31131. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  31132. savedSceneClearColor = scene.clearColor;
  31133. scene.clearColor = sceneClearColor;
  31134. };
  31135. this._volumetricLightScatteringRTT.onAfterRender = function () {
  31136. scene.clearColor = savedSceneClearColor;
  31137. };
  31138. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  31139. var engine = scene.getEngine();
  31140. var index;
  31141. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31142. renderSubMesh(opaqueSubMeshes.data[index]);
  31143. }
  31144. engine.setAlphaTesting(true);
  31145. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31146. renderSubMesh(alphaTestSubMeshes.data[index]);
  31147. }
  31148. engine.setAlphaTesting(false);
  31149. if (transparentSubMeshes.length) {
  31150. for (index = 0; index < transparentSubMeshes.length; index++) {
  31151. var submesh = transparentSubMeshes.data[index];
  31152. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  31153. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  31154. }
  31155. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  31156. sortedArray.sort(function (a, b) {
  31157. // Alpha index first
  31158. if (a._alphaIndex > b._alphaIndex) {
  31159. return 1;
  31160. }
  31161. if (a._alphaIndex < b._alphaIndex) {
  31162. return -1;
  31163. }
  31164. // Then distance to camera
  31165. if (a._distanceToCamera < b._distanceToCamera) {
  31166. return 1;
  31167. }
  31168. if (a._distanceToCamera > b._distanceToCamera) {
  31169. return -1;
  31170. }
  31171. return 0;
  31172. });
  31173. // Render sub meshes
  31174. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31175. for (index = 0; index < sortedArray.length; index++) {
  31176. renderSubMesh(sortedArray[index]);
  31177. }
  31178. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31179. }
  31180. };
  31181. };
  31182. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  31183. var transform = scene.getTransformMatrix();
  31184. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  31185. this._screenCoordinates.x = pos.x / this._viewPort.width;
  31186. this._screenCoordinates.y = pos.y / this._viewPort.height;
  31187. if (this.invert)
  31188. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  31189. };
  31190. // Static methods
  31191. /**
  31192. * Creates a default mesh for the Volumeric Light Scattering post-process
  31193. * @param {string} The mesh name
  31194. * @param {BABYLON.Scene} The scene where to create the mesh
  31195. * @return {BABYLON.Mesh} the default mesh
  31196. */
  31197. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  31198. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  31199. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  31200. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  31201. return mesh;
  31202. };
  31203. return VolumetricLightScatteringPostProcess;
  31204. })(BABYLON.PostProcess);
  31205. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  31206. })(BABYLON || (BABYLON = {}));
  31207. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  31208. var __extends = this.__extends || function (d, b) {
  31209. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31210. function __() { this.constructor = d; }
  31211. __.prototype = b.prototype;
  31212. d.prototype = new __();
  31213. };
  31214. var BABYLON;
  31215. (function (BABYLON) {
  31216. var LensRenderingPipeline = (function (_super) {
  31217. __extends(LensRenderingPipeline, _super);
  31218. /**
  31219. * @constructor
  31220. *
  31221. * Effect parameters are as follow:
  31222. * {
  31223. * chromatic_aberration: number; // from 0 to x (1 for realism)
  31224. * edge_blur: number; // from 0 to x (1 for realism)
  31225. * distortion: number; // from 0 to x (1 for realism)
  31226. * grain_amount: number; // from 0 to 1
  31227. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  31228. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  31229. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  31230. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  31231. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  31232. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  31233. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  31234. * }
  31235. * Note: if an effect parameter is unset, effect is disabled
  31236. *
  31237. * @param {string} name - The rendering pipeline name
  31238. * @param {object} parameters - An object containing all parameters (see above)
  31239. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31240. * @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)
  31241. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31242. */
  31243. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  31244. var _this = this;
  31245. if (ratio === void 0) { ratio = 1.0; }
  31246. _super.call(this, scene.getEngine(), name);
  31247. // Lens effects can be of the following:
  31248. // - chromatic aberration (slight shift of RGB colors)
  31249. // - blur on the edge of the lens
  31250. // - lens distortion
  31251. // - depth-of-field blur & highlights enhancing
  31252. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  31253. // - grain effect (noise or custom texture)
  31254. // Two additional texture samplers are needed:
  31255. // - depth map (for depth-of-field)
  31256. // - grain texture
  31257. /**
  31258. * The chromatic aberration PostProcess id in the pipeline
  31259. * @type {string}
  31260. */
  31261. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  31262. /**
  31263. * The highlights enhancing PostProcess id in the pipeline
  31264. * @type {string}
  31265. */
  31266. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  31267. /**
  31268. * The depth-of-field PostProcess id in the pipeline
  31269. * @type {string}
  31270. */
  31271. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  31272. this._scene = scene;
  31273. // Fetch texture samplers
  31274. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31275. if (parameters.grain_texture) {
  31276. this._grainTexture = parameters.grain_texture;
  31277. }
  31278. else {
  31279. this._createGrainTexture();
  31280. }
  31281. // save parameters
  31282. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  31283. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  31284. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  31285. this._distortion = parameters.distortion ? parameters.distortion : 0;
  31286. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  31287. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  31288. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  31289. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  31290. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  31291. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  31292. // Create effects
  31293. this._createChromaticAberrationPostProcess(ratio);
  31294. this._createHighlightsPostProcess(ratio);
  31295. this._createDepthOfFieldPostProcess(ratio);
  31296. // Set up pipeline
  31297. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  31298. return _this._chromaticAberrationPostProcess;
  31299. }, true));
  31300. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () {
  31301. return _this._highlightsPostProcess;
  31302. }, true));
  31303. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  31304. return _this._depthOfFieldPostProcess;
  31305. }, true));
  31306. if (this._highlightsGain == -1) {
  31307. this._disableEffect(this.HighlightsEnhancingEffect, null);
  31308. }
  31309. // Finish
  31310. scene.postProcessRenderPipelineManager.addPipeline(this);
  31311. if (cameras) {
  31312. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31313. }
  31314. }
  31315. // public methods (self explanatory)
  31316. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  31317. this._edgeBlur = amount;
  31318. };
  31319. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  31320. this._edgeBlur = 0;
  31321. };
  31322. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  31323. this._grainAmount = amount;
  31324. };
  31325. LensRenderingPipeline.prototype.disableGrain = function () {
  31326. this._grainAmount = 0;
  31327. };
  31328. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  31329. this._chromaticAberration = amount;
  31330. };
  31331. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  31332. this._chromaticAberration = 0;
  31333. };
  31334. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  31335. this._distortion = amount;
  31336. };
  31337. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  31338. this._distortion = 0;
  31339. };
  31340. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  31341. this._dofDepth = amount;
  31342. };
  31343. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  31344. this._dofDepth = -1;
  31345. };
  31346. LensRenderingPipeline.prototype.setAperture = function (amount) {
  31347. this._dofAperture = amount;
  31348. };
  31349. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  31350. this._dofPentagon = true;
  31351. };
  31352. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  31353. this._dofPentagon = false;
  31354. };
  31355. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  31356. this._blurNoise = true;
  31357. };
  31358. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  31359. this._blurNoise = false;
  31360. };
  31361. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  31362. this._highlightsGain = amount;
  31363. };
  31364. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  31365. if (this._highlightsGain == -1) {
  31366. this._highlightsGain = 1.0;
  31367. }
  31368. this._highlightsThreshold = amount;
  31369. };
  31370. LensRenderingPipeline.prototype.disableHighlights = function () {
  31371. this._highlightsGain = -1;
  31372. };
  31373. /**
  31374. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  31375. */
  31376. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31377. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31378. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31379. this._chromaticAberrationPostProcess = undefined;
  31380. this._highlightsPostProcess = undefined;
  31381. this._depthOfFieldPostProcess = undefined;
  31382. this._grainTexture.dispose();
  31383. if (disableDepthRender)
  31384. this._scene.disableDepthRenderer();
  31385. };
  31386. // colors shifting and distortion
  31387. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  31388. var _this = this;
  31389. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31390. this._chromaticAberrationPostProcess.onApply = function (effect) {
  31391. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  31392. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31393. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31394. };
  31395. };
  31396. // highlights enhancing
  31397. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  31398. var _this = this;
  31399. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31400. this._highlightsPostProcess.onApply = function (effect) {
  31401. effect.setFloat('gain', _this._highlightsGain);
  31402. effect.setFloat('threshold', _this._highlightsThreshold);
  31403. effect.setBool('pentagon', _this._dofPentagon);
  31404. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  31405. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31406. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31407. };
  31408. };
  31409. // colors shifting and distortion
  31410. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  31411. var _this = this;
  31412. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  31413. "focus_depth",
  31414. "aperture",
  31415. "pentagon",
  31416. "maxZ",
  31417. "edge_blur",
  31418. "chromatic_aberration",
  31419. "distortion",
  31420. "blur_noise",
  31421. "grain_amount",
  31422. "screen_width",
  31423. "screen_height",
  31424. "highlights"
  31425. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31426. this._depthOfFieldPostProcess.onApply = function (effect) {
  31427. effect.setBool('blur_noise', _this._blurNoise);
  31428. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  31429. effect.setFloat('grain_amount', _this._grainAmount);
  31430. effect.setTexture("depthSampler", _this._depthTexture);
  31431. effect.setTexture("grainSampler", _this._grainTexture);
  31432. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  31433. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  31434. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31435. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31436. effect.setFloat('distortion', _this._distortion);
  31437. effect.setFloat('focus_depth', _this._dofDepth);
  31438. effect.setFloat('aperture', _this._dofAperture);
  31439. effect.setFloat('edge_blur', _this._edgeBlur);
  31440. effect.setBool('highlights', (_this._highlightsGain != -1));
  31441. };
  31442. };
  31443. // creates a black and white random noise texture, 512x512
  31444. LensRenderingPipeline.prototype._createGrainTexture = function () {
  31445. var size = 512;
  31446. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31447. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31448. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31449. var context = this._grainTexture.getContext();
  31450. var rand = function (min, max) {
  31451. return Math.random() * (max - min) + min;
  31452. };
  31453. var value;
  31454. for (var x = 0; x < size; x++) {
  31455. for (var y = 0; y < size; y++) {
  31456. value = Math.floor(rand(0.42, 0.58) * 255);
  31457. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  31458. context.fillRect(x, y, 1, 1);
  31459. }
  31460. }
  31461. this._grainTexture.update(false);
  31462. };
  31463. return LensRenderingPipeline;
  31464. })(BABYLON.PostProcessRenderPipeline);
  31465. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  31466. })(BABYLON || (BABYLON = {}));
  31467. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  31468. //
  31469. // This post-process allows the modification of rendered colors by using
  31470. // a 'look-up table' (LUT). This effect is also called Color Grading.
  31471. //
  31472. // The object needs to be provided an url to a texture containing the color
  31473. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  31474. // Use an image editing software to tweak the LUT to match your needs.
  31475. //
  31476. // For an example of a color LUT, see here:
  31477. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  31478. // For explanations on color grading, see here:
  31479. // http://udn.epicgames.com/Three/ColorGrading.html
  31480. //
  31481. var __extends = this.__extends || function (d, b) {
  31482. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31483. function __() { this.constructor = d; }
  31484. __.prototype = b.prototype;
  31485. d.prototype = new __();
  31486. };
  31487. var BABYLON;
  31488. (function (BABYLON) {
  31489. var ColorCorrectionPostProcess = (function (_super) {
  31490. __extends(ColorCorrectionPostProcess, _super);
  31491. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  31492. var _this = this;
  31493. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  31494. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  31495. this._colorTableTexture.anisotropicFilteringLevel = 1;
  31496. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31497. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31498. this.onApply = function (effect) {
  31499. effect.setTexture("colorTable", _this._colorTableTexture);
  31500. };
  31501. }
  31502. return ColorCorrectionPostProcess;
  31503. })(BABYLON.PostProcess);
  31504. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  31505. })(BABYLON || (BABYLON = {}));
  31506. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  31507. 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}"};
  31508. 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);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}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){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!i._lastColliderWorldVertices||!i._lastColliderTransformMatrix.equals(e)){i._lastColliderTransformMatrix=e.clone(),i._lastColliderWorldVertices=[],i._trianglePlanes=[];for(var n=i.verticesStart,a=i.verticesStart+i.verticesCount,t=n;a>t;t++)i._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],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]&&!this._collisionsCallbackArray[n+1e5]){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(n,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.y?s=new r(0,-1,0):1!==i.x?s=new r(1,0,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&&window.SIMD.float32x4&&window.SIMD.float32x4.swizzle&&R.EnableSIMD()}(BABYLON||(BABYLON={}));";